views:

34

answers:

1

Can someone explain what is happening in the example below:

glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glRotatef(45,0,0,1);
DrawCube();
glTranslatef(4,0,0);
glRotatef(-45,0,0,1);
DrawCube();
glPopMatrix();

I am assuming that it will just rotate the square, shift it right 4 units, and then rotate it back to its original rotation. It seems too easy though, is there something I am missing?

A: 

Roughly-

  • Make sure OpenGL applies matrix operations to the modelview stack
  • Save the current value of the stack (to be reverted by the pop later)
  • Load the identity, clearing any and all rotates/transforms/whatever
  • Rotate the current matrix transformation 45 degrees around the X axis
  • Draw a cube (using the current matrix transformation, which has been rotated)
  • Translate the current matrix transformation 4 units in the X axis
  • Rotate the current matrix transformation -45 degrees around the x axis
  • Draw another cube that has been translated and rotate from the position of the first cube
  • Restore the original matrix transform that was saved by the Push

This results in two cubes being drawn. The first is in the center, and rotated 45 degrees, and the second 4 units away on the rotated x-axis, and itself rotated -45 degrees.

luke
Are the top and bottom of each square falling on the same x-axis then? Or is one higher than another?
Kira
I wasn't very clear on that. No, they wouldn't be on the same x-axis. There is a rotate before that translate, so the orientation of the x-axis has changed.
luke
Thank you, I realize that's why it is drawing it slightly above the original.
Kira
You're quite welcome.
luke
@luke, you might want to change the final sentence of your answer, which says "and the second 4 units away *on the x-axis*". As you noted, it's not on the (world) x-axis. Also, the rotations are not "in the X axis" but rather "around the Z axis".
LarsH
@LarsH, good points. I've changed the language to be more clear.
luke