Calculate Normals in vertex shader?

AFAIK this should do it (from the top of my head, might or might not work, didn’t try it):

Possible vertex shader:


#version 330

uniform mat4 projection;
uniform mat4 modelview;

layout(location=0) in vec4 V_POSITION;

void main( )
{
     gl_Position = projection * modelview * V_POSITION;
}

Possible geometry shader:


#version 330

layout(triangles) in;
layout(triangle_strip, max_vertices=3) out;

out vec3 normal;

void main( void )
{
    vec3 a = ( gl_in[1].gl_Position - gl_in[0].gl_Position ).xyz;
    vec3 b = ( gl_in[2].gl_Position - gl_in[0].gl_Position ).xyz;
    vec3 N = normalize( cross( b, a ) );

    for( int i=0; i<gl_in.length( ); ++i )
    {
        gl_Position = gl_in[i].gl_Position;
        normal = N;
        EmitVertex( );
    }

    EndPrimitive( );
}

Possible fragment shader:


#version 330

layout(location=0) out vec3 COLOR0;

in vec3 normal;

void main( )
{
    COLOR0 = normal;
}