GLSL normals problem?

Started by
1 comment, last by Geometrian 11 years, 8 months ago
So, I've been trying to add very simple normal lighting..if a face is facing a light, then it's illuminated. otherwise, it progressively gets dimmer, and when it's behind the face, then the face isn't illuminated at all. Now, this works perfectly when I have a cube set up at the origin.

However, when I started to rotate the cube, the light seemed static in the cube--for example, a light spot on the cube would stay in the same place, even while the cube is rotating. I found the problem to be that the normals were not being rotated with the object.

So, do you guys have any idea how to do this?

I tried normal=normalize(gl_NormalMatrix*gl_Normal);

but the problem is that the normal is translated into camera coordinates (with the camera being (0,0,0); so a face would always have a normal of (0,0,1) if the camera was looking at it). So, my question is...how do I rotate an object, and have the normals rotated as well?

Thanks in advance!
Advertisement
Hi you have to rotate the normal like:
[source lang="cpp"]mat4 rotate_x(float theta)
{
return mat4(
1.0, 0.0, 0.0, 0.0,
0.0, cos(theta), sin(theta), 0.0,
0.0, -sin(theta), cos(theta), 0.0,
0.0, 0.0, 0.0, 1.0
);
}

void main()
{
....
....

mat4 tRotation = rotate_x(originalRotation.x);
vec4 newTranslation = vec4(tRotation * PositionFromAttributes);
vec3 eyeNormal = NormalMatrix3x3 * vec3(newTranslation) * NormalFromAttributes;
....
....
}[/source]
The issue is that there are three common matrices: the model, the view, and the projection. The model matrix transforms the object from object space into world space. The view matrix transforms from world space into eye space (everything relative to camera). The projection matrix transforms from eye space to clip space (everything perspective correct). OpenGL 2 and before combine the model and view matrices into the modelview matrix.

Multiplying by gl_NormalMatrix as in your original post is correct (gl_NormalMatrix is only the rotational part of the model matrix).

But remember, because OpenGL combines the model and view matrices into the modelview matrix, when you multiplied by gl_NormalMatrix, you also incidentally multiplied by the view matrix! This is why the view screwed up the normals. The classic solution? Transform the light too!

To do this, put the light position AFTER your camera call. Something like this pseudo-C-like language:[source lang="c"]//Begin frame
glLoadIdentity();

//Set camera
gluLookAt(/*stuff*/);
//Set light
glLightfv(GL_LIGHTn,GL_POSITION,/*something*/);

//Draw stuff with your original shader
//...

//Flip buffers
//...

//End frame[/source]-G

[size="1"]And a Unix user said rm -rf *.* and all was null and void...|There's no place like 127.0.0.1|The Application "Programmer" has unexpectedly quit. An error of type A.M. has occurred.
[size="2"]

This topic is closed to new replies.

Advertisement