0
votes

I'm trying to determine the position of a cube after the execution of the following code:

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(3.0, 2.0, 1.0);

glPushMatrix();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glTranslatef(1.0, 2.0, 3.0);

glPushMatrix();
glTranslatef(1.0, 1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glPopMatrix();

glTranslatef(2.0, 2.0, 2.0);
glutWireCube(1.0);

I don't know if i should consider the GL_MODELVIEW matrix or the GL_PROJECTION matrix. After the first glPushMatrix() the glMatrixMode is changed from GL_MODELVIEW to GL_PROJECTION, so should I ignore the glTranslatef(3.0, 2.0, 1.0), so the final position is of the cube is: (3.0, 4.0, 5.0)?

1
Since this code pushes twice and pops only once, it will quickly overflow the matrix stack if called in a render loop.Thomas

1 Answers

3
votes

Lets take just the MODELVIEW matrix stack:

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(3.0, 2.0, 1.0);
glPushMatrix();
glPopMatrix();   // nullifies the above push
glTranslatef(2.0, 2.0, 2.0);

The stack starts with one entry; you set it to identity, then multiply it with a translation matrix. PushMatrix creates a copy of this matrix in a new entry atop the older one, on the stack and then you undo this by PopMatrix. So you continue to have the first matrix, which is then multiplied by another translation matrix. Effectively your model view transform, which transforms the cube from its model space into the world space, is

| 1  0  0  5 |
| 0  1  0  4 |
| 0  0  1  3 |
| 0  0  0  1 |

A cube which is centered at (5, 4, 3) in the world space.

Then you go on to set the projection matrix stack with the following

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glTranslatef(1.0, 2.0, 3.0);
glPushMatrix();
glTranslatef(1.0, 1.0, 1.0);

Based on the same logic as above, you've an effective projection matrix of

| 1  0  0  2 |
| 0  1  0  3 |
| 0  0  1  4 |
| 0  0  0  1 |

This isn't a valid projection transformation matrix; neither orthogonal nor perspective. You can create a valid projection matrix using the helper functions glFrustum (for a perspective camera) or glOrtho (for orthographic camera). The GLU functions gluPerspective and gluOrtho2D are slightly more intuitive than their gl counterparts. See the OpenGL FAQ on Using Viewing and Camera Transforms for details.