PDA

View Full Version : How does gluLookAt() work with gluPerspective()?



myst_iori
06-07-2011, 10:17 PM
This is very simple example. I tried to draw three coordinates, each of length 100 -- start from the origin (0,0,0). However, I still couldn't figure out what did I mess up so that only a black window was displayed. A hint would be greatly appreciated.

Thank you,



#include <cstdio>
#include <cstdlib>
#include <iostream>

#include <GL/glut.h>

using namespace std;

void setupScene() {
glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
gluLookAt(
5.0, 10.0, 50.0, // eye location
0.0, 0.0, 0.0, // center location
0.0, 1.0, 0.0 // up vector
);
}

void drawAxes() {
glLineWidth( 3.0 );
glBegin( GL_LINES );
glColor3f( 1.0, 0.0, 0.0 );
glVertex3i( 0, 0, 0 );
glVertex3i( 100, 0, 0);
glColor3f( 0.0, 1.0, 0.0 );
glVertex3i( 0, 0, 0 );
glVertex3i( 0, 100, 0 );
glColor3f( 0.0, 0.0, 1.0 );
glVertex3i( 0, 0, 0 );
glVertex3i( 0, 0, 100 );
glEnd();
}

void reshapeWindow( int w, int h ) {
if( h == 0 ) {
h = 1;
}
float aspectRatio = ( float )w / h;
glViewport( 0, 0, w, h );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective( 45.0, aspectRatio, 1.0, 1000.0 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
}

void renderScene() {
glClear( GL_COLOR_BUFFER_BIT );
drawAxes();
glFlush();
}

void handleKeyPress( unsigned char key, int x, int y ) {
if( key == 27 )
exit( 0 );
}

int main( int argc, char** argv ) {
glutInit( &amp;argc, argv );
glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB );
glutInitWindowSize( 800, 600 );
glutCreateWindow( "XYZ" );
glutReshapeFunc( reshapeWindow );
glutDisplayFunc( renderScene );
glutKeyboardFunc( handleKeyPress );
setupScene();
glutMainLoop();
return 0;
}

aqnuep
06-08-2011, 01:41 AM
gluPerspective is usually used for setting up the projection matrix and gluLookAt is usually used for manipulating the modelview matrix, so they should not interfere. Anyway, your usage of those seems to be just right.

Your problem is that even though you set up the modelview matrix in the setupScene() function, that will be replaced with the identity matrix when the next call to reshapeWindow() happens, and actually it will happen for sure when you call glutMainLoop().

Remove the last line of the reshapeWindow() function so you no longer reset the modelview matrix or simply call setupScene() in the renderScene() function to be sure to have the proper modelview matrix in every frame.

myst_iori
06-08-2011, 12:25 PM
@aqnep:
Great thanks! I saw my problem, I always thinks I have to reset to identity matrix for the next call to render function, but in fact, it depends on the implementation of my render function. I checked several examples in the book, and I saw them load the modelview matrix within the draw routine, which I missed.