Lighting rotating with gluLookAt(...)

Hello, I’m currently experimenting with OpenGL in combination with SDL.

My problem:

As the camera rotates, the way the terrain is being lighted changes completely, as if the camera transformation is being taken into account during the lighting calculation.

I guess that the problem lies in the order I’m applying my matrices. This is my rendering code (simplified form):


    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluPerspective(45, 800.f / 500.f, 1, 1000);

    //Initialize Modelview Matrix
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);

gluLookAt(position.getX(),position.getY(),position.getZ(),
                    lookAtPosition.getX(),lookAtPosition.getY(),lookAtPosition.getZ(),
                    upDirection.getX(),upDirection.getY(),upDirection.getZ());

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    // Draw all the stuff in the world
    for (vector<Entity*>::iterator itr=entityManager->entities.begin(); itr != entityManager->entities.end();itr++){
        (*itr)->render();
    }

Ok, found it already…

I had to put the gluLookAt inside the projection matrix code.

That won’t work with specular lighting, as the eye position is taken as the origin in eye space. In general, the projection matrix shouldn’t contain a translation.

If moving the camera changes the lighting, that suggests that you’re setting the light position before the camera transformation has been applied. The light position is transformed by the current modelview matrix when glLight(GL_POSITION) is called, and stored in eye coordinates. If you set a fixed light position prior to applying the camera transformation, that means that the light position is fixed in eye space, when you probably want it fixed in “world” space.