Question about glPushMatrix?

Hey all, I’m a beginner here so bear with me. As far as I understand it when you push a new matrix on it’s kinda like creating a copy of your current scene and then you can act accordingly and then you can pop it off and be left your original scene. (this may be wrong, please correct me if so) What I don’t get is how come this code:


//position is an array of random values, this is a while loop which goes through all the points and creates a cube
glPushMatrix();
        glTranslated(-positionx[i], -positiony[i] - 3, -positionz[i]); //translate the cube
        
        glColor3f (1.0f, 0.0f, 0.0f);   
        glutSolidCube(2); //draw the cube
        glPopMatrix();

doesn’t work without the push and pop of the matrix. Could someone clarify this for me? Thanks!

Hello interwound!

Well glPushMatrix() actually saves the current matrix. So that means that all depends on your previous call of glMatrixMode(). So because everything depends on that can you tell us what was the parameter of your previous call to this function? Make sure that it was GL_MODELVIEW because what you are trying to achieve concerns the modelview matrix.

Oh I think I’m starting to understand, do I have to save the current matrix so that after each translation and adding of cube I can go back to my original starting point so that each cube is added from the same origin?

Yep, that’s pretty much it.
Even though the code is kind of outdated, you can observe a nice example of hierarchical usage of push/pop matrix in order to draw a complex model in the link below.

http://www.gamedev.net/page/resources/_/technical/opengl/opengl-object-hierarchy-r1267

Just as an additional note though, remember that from openGL 3.0 and up both glPush() and glPop Matrix have been deprecated, which means you would have to have your own implementation of them.