Favn Hghksd
Favn Hghksd

Reputation: 321

Opengl glPush and glPop functions

I have read about the glPushMatrix and glPopMatrix function and how they serve as a form of savepoint. I was trying out simple code that draws a basic cube with a scaling operation before it and I noticed something: if all I have in the draw code is to scale then draw the cube, there is a difference if I used the Push and Pop matrices functions. That is, there is a difference if I used:

glPushMatrix(); 
    glScalef (2.0, 0.4, 1.0); 
    glutWireCube (1.0);
glPopMatrix(); 

vs just using:

 glScalef (2.0, 0.4, 1.0);         
 glutWireCube (1.0);

without the push and pop.

The first will draw the cube correctly while the second code (without the push and pop) very wide on the x-axis - again, this is without any other transformation function before and after. Why does it do this?

Upvotes: 1

Views: 1292

Answers (1)

Codesmith
Codesmith

Reputation: 6752

In your first example, here's what's happening:

// initial transform stack: [identity]

// copies last stack item and adds to the stack: [identity][identity]
glPushMatrix();

    // multiply top of stack by scalar matrix: [identity][scale matrix]
    glScalef (2.0, 0.4, 1.0);

    // draw cube with top of stack: [identity][scale matrix]
    glutWireCube (1.0);

// pop the last item off the stack: [identity]
glPopMatrix();

// at this point, on the next loop, the stack will be [identity]

As you'll note, the stack's end-state is the same as its begin state.

Here's what's happening in your second example:

Loop #1

// initial transform stack: [identity]

// multiply top of stack by scalar matrix: [scale matrix]
glScalef (2.0, 0.4, 1.0);
glutWireCube (1.0);

// at this point, on the next loop, the stack will be [scale matrix]

Loop #2

// current transform stack: [scale matrix]

// multiply top of stack by scalar matrix: [scale matrix * scale matrix]
glScalef (2.0, 0.4, 1.0);
glutWireCube (1.0);

// at this point, on the next loop, the stack will be [scale matrix * scale matrix]

As you can see, since you're not clearing the transform, it's accumulating the previous transform each iteration.

You can check out glPushMatrix for more information if it helps.

Upvotes: 3

Related Questions