Contents / Previous / Next


Matrix Stacks

A stack of matrices is useful for constructing hierarchical models, in which complicated objects are constructed from simpler ones.

All the matrix operations that have been described so far (glLoadMatrix(), glMultMatrix(), glLoadIdentity() and the commands that create specific transformation matrices) deal with the current matrix, or the top matrix on the stack.

You can control which matrix is on top with the commands that perform stack operations: glPushMatrix(), which copies the current matrix and adds the copy to the top of the stack, and glPopMatrix(), which discards the top matrix on the stack.
The current matrix is always the matrix on the top.
The current stack is determined by glMatrixMode().

glPushMatrix() means "remember where you are" and glPopMatrix() means "go back to where you were."

void glPushMatrix(void); 
Pushes all matrices in the current stack down one level. The topmost matrix is copied, so its contents are duplicated in both the top and second-from-the-top matrix.
If too many matrices are pushed, an error is generated.

glPopMatrix() pops the top matrix off the stack, destroying the contents of the popped matrix. What was the second-from-the-top matrix becomes the top matrix.
void glPopMatrix(void); 
If the stack contains a single matrix, calling glPopMatrix() generates an error.


The Modelview Matrix Stack

The modelview matrix contains the cumulative product of multiplying viewing and modeling transformation matrices. Each viewing or modeling transformation creates a new matrix that multiplies the current modelview matrix; the result, which becomes the new current matrix, represents the composite transformation.

The modelview matrix stack contains at least thirty-two 4x4 matrices; initially, the topmost matrix is the identity matrix. Some implementations of OpenGL may support more than thirty-two matrices on the stack. To find the maximum allowable number of matrices, you can use the query command:

glGetIntegerv(GL_MAX_MODELVIEW_STACK_DEPTH, GLint *params).  


The Projection Matrix Stack

The projection matrix contains a matrix for the projection transformation, which describes the viewing volume. Generally, you do not want to compose projection matrices, so you issue glLoadIdentity() before performing a projection transformation. Also for this reason, the projection matrix stack need be only two levels deep; some OpenGL implementations may allow more than two 4x4 matrices. To find the stack depth, call:

glGetIntegerv(GL_MAX_PROJECTION_STACK_DEPTH, GLint *params)

One use for a second matrix in the stack would be an application that needs to display a help window with text in it, in addition to its normal window showing a three-dimensional scene. Since text is most easily positioned with an orthographic projection, you could change temporarily to an orthographic projection, display the help, and then return to your previous projection: