Position From Depth in GLSL

Commenter “Me” was kind enough to share his GLSL implementation of a deferred point light shader, which makes use of one of the methods I previously posted for reconstructing position from depth. So I figured I’d post it here, for all of you unfortunate enough to be stuck with writing shaders in GLSL. :P

// deferred shading VERTEX (GEOMETRY)
varying vec3 normalv, posv;

void main( void ) {
    normalv = ( gl_NormalMatrix * gl_Normal ).xyz;
    posv = ( gl_ModelViewMatrix * gl_Vertex ).xyz;
    gl_Position = ftransform();
}

// deferred shading FRAGMENT (GEOMETRY)
varying vec3  normalv, posv;
uniform vec2  nfv;

void main( void ){
    gl_FragData[0] = vec4( normalize( normalv ) * 0.5 + 0.5, -posv.z / nfv.y );
}

// deferred shading VERTEX (LIGHTING: POINT)
varying vec3 posv;

void main( void ){
    posv = ( gl_ModelViewMatrix * gl_Vertex ).xyz;
    gl_Position = ftransform();
    gl_FrontColor = gl_Color;
}

// deferred shading FRAGMENT (LIGHTING: POINT)
varying vec3 posv;
uniform float lradius;
uniform vec3 lcenter;
uniform vec2 nfv, sic;
uniform sampler2D geotexture;

void main( void ){
    vec2 tcoord = gl_FragCoord.xy * sic;
    vec4 geometry = texture2D( geotexture, tcoord );
    vec3 viewray = vec3( posv.xy * ( -nfv.y / posv.z ), -nfv.y );
    vec3 vscoord = viewray * geometry.a;
    float dlight = length( lcenter - vscoord );
    float factor = 1.0 - dlight/lradius;
    if( dlight > lradius ) discard;
    gl_FragData[0] = vec4( gl_Color.rgb, factor );
}

Comments:

Lukas Meindl -

This is a good code basis for a deferred spotlight shader. To make it more understandable I would like to add: - “uniform vec2 nfv;” should be “uniform float farClipDistance” - Replace “nfv.y” by “farClipDistance”, x is never used and i can’t think of a way of using it here. - I would change “vec2 tcoord = gl_FragCoord.xy * sic;” to “vec4 ex_persp_position = gl_FragCoord / gl_FragCoord.w; vec2 texCoord = ex_persp_position.xy * 0.5 + vec2(0.5);” This should work- the variable “sic” can be removed then…