Skip to main content
GameDev.net gamedev.net
🔒 Locked 🎯 Unreal

GLSL, getting depth of fragment

Started by patrrr Jul 1, 2007 at 6:46 AM 1 replies 11.1k views
Original Post
patrrr
patrrr
Hello! I'm trying to render a primitive in grayscale where black is closest to the viewer and white is far away, like when you render the depth buffer to a texture. So I wrote this fragment shader:

void main() 
{
   float depth = gl_FragDepth;
   gl_FragColor = vec4(depth, depth, depth, 1.0);
}
But the primitive has the same color everywhere, and it doesn't change with distance. Now when I render the depth buffer of this to a texture all I get is black! So, is gl_FragDepth only for writing? Should I instead get the depth by ftransform'ing the vertices of the primitive and getting the z-component, then subtracting fNear and dividing by (fFar - fNear)? Can I get fFar and fNear from the projection matrix in the shader or do I have to pass them as attributes? Like this?

Vertex shader:

varying float depth;
attribute float fNear, fFar;

void main() {
   gl_Position = ftransform();
   depth = (gl_Position.z - fNear) / (fFar - fNear);
}

Fragment shader:

varying float depth;

void main() {
   gl_FragColor = vec4(depth, depth, depth, 1.0);
}
Yann L
Yann L
The easiest way is to simply use gl_FragCoord.z, since gl_FragDepth is write only.

You could also do it manually (and you might have to, due to some obscure driver bugs on some ATI chips *sigh*), however it won't work the way you outlined it. Don't forget you have to do the perspective divide, and that the znear/zfar range remapping is done after the divide, which has to be done per-fragment.

Anyway, gl_FragCoord.z is the easiest and fastest way.
patrrr
patrrr
Thanks alot! Think I missed that variable.
Is gl_FragCoord.z the exact value calculated in the vertex shader? Some web pages say the perspective divide is carried out after the fragment shader, others say it's after the vertex shader but before the fragment shader.
The z value is after all in the range 0-1, wouldn't that mean it has been divided already?

What exactly is the "perspective divide"? vec4 pos = ftransform(); pos.z /= pos.w; ?

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.