Reputation: 1665
I have some code that performs various transformations and sets colour between calls to glPushMatrix() and glPopMatrix(), essentially like this:
glLoadIdentity();
glPushMatrix();
glPushMatrix();
// C++ code to perform transformations
// C++ code to set colour
// C++ code to draw polygon
glPopMatrix();
// Other similar code "blocks" between calls to glPushMatrix() and glPopMatrix()
glPushMatrix();
// C++ code to perform transformations
// C++ code to set colour
// C++ code to draw polygon
glPopMatrix();
My understanding was that an identity matrix is pushed onto the stack at the beginning and subsequently copied, transformed, rendered, and popped by each successive "block" of code and that popping removes all of the effects from the previous transformations.
However, if I comment out the code that sets the colour in any block that is not the final block, that block now inherits the colour that is set in the final block
This makes sense if colour is applied to the whole stack and therefore survives the calls to glPopMatrix(). But, the polygon created in the final block appears to be rendered last since it is on top of all of the other polygons -- so I do not see how the colour that is set in the final block could be applied to polygons that have already been rendered.
Questions:
1) What attributes/effects survive calls to glPopMatrix()?
2) What is the order of the operations in the above code? Are the blocks executed in reverse order, is the code in each block executed in reverse order, or both?
Upvotes: 0
Views: 255
Reputation: 4778
As their names imply, glPushMatrix()
and glPopMatrix()
only save/restore the matrix state. Color values are not stored - you'd need to use glPushAttrib()
instead.
OpenGL instructions are handled in the order that you'd expect: From first to last. If you remove the glColor3f()
stuff for the first polygon, you'll generally see the color value from the final polygon being used because the last defined color value (i.e. the one set for the final polygon) will still be the "active" color value when the screen is re-drawn.
Incidentally, you don't need to push the matrix state twice at the start:
glLoadIdentity();
glPushMatrix();
glPushMatrix();
The glLoadIdentity()
function sets the current matrix state - there's no need to push it on to the stack afterwards. Your code could either look like this:
glLoadIdentity(); // Set the matrix to an "identity" state.
glPushMatrix(); // Save the identity matrix.
transformTheMatrix();
drawSomething();
glPopMatrix(); // Restore the identity matrix.
glPushMatrix(); // Save the identity matrix.
transformTheMatrix();
drawSomething();
glPopMatrix(); // Restore the identity matrix.
...or even this:
glLoadIdentity();
transformTheMatrix();
drawSomething();
glLoadIdentity();
transformTheMatrix();
drawSomething();
Upvotes: 2