Espen
Espen

Reputation: 3727

When to call glMatrixMode()

Most OpenGL ES tutorials for Android I've followed has its onSurfaceChanged() function like this:

public void onSurfaceChanged( GL10 gl, int width, int height ) {
    gl.glViewport( 0, 0, width, height );
    gl.glMatrixMode( GL10.GL_PROJECTION );
    gl.glLoadIdentity();
    GLU.gluPerspective( gl, 45.0f, ( ( float )width / ( float )height ), 0.1f, 100.0f );
    gl.glMatrixMode( GL10.GL_MODELVIEW );
    gl.glLoadIdentity();
}

However, what is the grouping here? Must glMatrixMode() be called after glViewport? And must a glLoadIdentity() be called right after glMatrixMode()?

I've been coding for "full" OpengGL before, and in my old codes I first called glMatrixMode(), then gluPerspective and last glLoadIdentity(). As if one first set what matrix should be used for gluPerspective() and last set glIdentity() to finish it.

What is the correct order for calling glMatrixMode(), glIdentity() and gluPerspective() - and why? Are there differences between OpenGL and OpenGL ES for setting up glMatrixMode()?

Upvotes: 2

Views: 3910

Answers (2)

user487158
user487158

Reputation: 450

glViewport() is completely independent of the matrix transform stacks and can be called at any time.

glLoadIdentity() is typically called immediately after a matrix mode change so you are starting "fresh" if you will. Matrix transforms such as the gluPerspective(), glOrtho(), glFrustum(), glRotate(), glMultMatrix(), glTranslate() are cumulative operations because they aggregate to allow you to describe complex 3D world space transforms or to describe your OpenGL viewing volume. Example: if I want a cube translated in the +X direction then rotated around the Z axis I issue a glRotate() followed by a glTranslate().

glLoadIdentity() wipes out the matrix (of the current matrix mode) with the identity matrix so following a gluPerspective() by glLoadIdentity() is equivalent to a single call to glLoadIdentity(). In other words, that sequence is nonsensical.

Reverse the order of these because gluPerspective() will multiply the current matrix by the perspective transform. If the current matrix is identity then the multiply will simply result in the gluPerspective() matrix transform which is what you want for your projection matrix mode 99% of the time when perspective viewing.

There are no differences between OpenGL and OpenGL ES with respect to the behavior of glMatrixMode() or how these matrix functions modify GL matrix state.

Upvotes: 9

Sebastian Negraszus
Sebastian Negraszus

Reputation: 12215

glLoadIdentity loads an identity matrix into the current matrix (activated by glMatrixMode), thereby resetting it. I don't understand how first calling gluPerspective and then glLoadIdentity would accomplish anything reasonable.

The code you posted is exactly how you would do it in ordinary OpenGL, too.

Upvotes: 2

Related Questions