When dealing with a single, static model, lights are no problem. The light vector is calculated as the difference between the untransformed light position and the untransformed vertex position. Nothing complicated at all, eh?
However, trouble begins when one is dealing with multiple models. Since each model has its own transformation matrix to move it into position in the scene, one has to make sure to transform the position of the light to be correct relative to the model. Somehow, I’ve been having an extremely difficult time with this.
My solution was to use a program matrix that contains the position and orientation of the mesh itself, ignoring the perspective and the camera’s position and orientation. I take the inverse of that matrix in the vertex program and multiply it with the light position to get the light’s relative position. Here’s some code:
When I’m rendering each model:
float afMatrix[16] = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, m_afPosition[0], m_afPosition[1], m_afPosition[2], 1.0f}; glMatrixMode (GL_MATRIX10_ARB); glLoadMatrixf (afMatrix); glMatrixMode (GL_MODELVIEW);
And a snippit from the vertex program:
DP4 tLightPos.x, iIPM0[0], iLightPos; DP4 tLightPos.y, iIPM0[1], iLightPos; DP4 tLightPos.z, iIPM0[2], iLightPos; DP4 tLightPos.w, iIPM0[3], iLightPos; SUB tLightPos, tLightPos, iPos;
Where iIPM0 is the inverse of program matrix 0, iLightPos is the untransformed light position, and iPos is the untransformed vertex position.
Is there a way to do this where I don’t have to create a whole new matrix just so I can reliably transform the light position?
More code available upon specific request. . .