2
votes

last week,i've saw one shader script,which does deferred shading .but i was confused by some transform the vertex shader does.such as the following:

vert:

varying vec3 normals;
varying vec4 position;
uniform mat4 ModelMatrix;
uniform mat4 WorldMatrix;

void main( void )
{
    // Move the normals back from the camera space to the world space
    mat3 worldRotationInverse = transpose(mat3(WorldMatrix));

    gl_Position     = gl_ModelViewProjectionMatrix * gl_Vertex;
    gl_TexCoord[0]  = gl_MultiTexCoord0;
    **normals           = normalize(worldRotationInverse * gl_NormalMatrix * gl_Normal);         <<<<<**
    position        = gl_ModelViewMatrix * gl_Vertex;
    gl_FrontColor = vec4(1.0, 1.0, 1.0, 1.0);
}

frag :

varying vec4        position;
varying vec3        normals;
varying mat4        TBN;
uniform sampler2D   tDiffuse;

void main( void )
{
    gl_FragData[0]      = vec4(texture2D(tDiffuse,gl_TexCoord[0].st).rgb, 0);
    gl_FragData[1]      = vec4(position.xyz,0);
    gl_FragData[2]      = vec4(normals.xyz,0);
}

i really don't understand why transform the normal to world space(modelspace).beacause the reason that my think is the normal in eyespace(cameraspace) can at least eliminate invisible vertices,and even ploygon. i don't know whether i understand something wrong or not.

1
Where are your #version directives?genpfault

1 Answers

2
votes

Lighting can be done in any pre-projection space (e.g., world coordinates or eye coordinates), as long as all the objects and lights are all in that same space.

This shader does lighting in eye coordinates - you can tell by the use of the legacy gl_NormalMatrix implicit uniform variable. This approach mimics what was done in the legacy OpenGL pipeline where lighting (done by the OpenGL implementation when there weren't shaders) was done in eye coordinates. There's nothing wrong with doing lighting in eye coordinates, it's just not quite as intuitive as other spaces.

More modern approaches do lighting in world coordinates and don't require the use of the normal transform matrix (which is the inverse transpose of the upper 3x3 of the current model-view matrix).