How do I access depth values in a depth texture?

I have copied the depth buffer to a depth texture using the following code:

glGenTextures (1, &hDepthBuffer);
glBindTexture (GL_TEXTURE_2D, hDepthBuffer);
glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D (GL_TEXTURE_2D, 0, 1, <width>, <height>, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glCopyTexImage2D (GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 0, 0, <width>, <height>, 0);

How do I access depth values from that texture in a GLSL shader?

My shader looks like this:


uniform sampler2DShadow depthTex;
void main (void) 
{
float depth = shadow2D (depthTex, gl_FragCoord.xy).x;
}

Is that correct?

Is there anything I have to regard (I have read something about a texture compare mode)?

shadow2D does not return depth value - it returns depth comparison result. That’s why you pass the z coordinate in it’s 2nd argument (there is an error in your code, because you pass gl_FragCoord.xy, and you should pass a vec3 there).

Note that for the shadow2D function to work you need to enable depth comparison in your tex env.
If you use shadow2D function with depth comparison disabled, then results are undefined.

Thank you very much. What would I have to do to access the contents of the depth buffer in a fragment shader then? Or just the current depth value at a given fragment position?

Is it correct this way:


uniform sampler2D depthTex;
void main (void)
{
float depth = texture2D (depthTex, gl_FragCoord.xy).r;
}

Set TEXTURE_COMPARE_MODE to none and use texture2D to read depth values.

Is this correct now?


glGenTextures (1, &hDepthBuffer);
glBindTexture (GL_TEXTURE_2D, hDepthBuffer);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
glTexParameteri (GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_ALPHA);
glTexImage2D (GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, <width>, <height>, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glCopyTexImage2D (GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 0, 0, <width>, <height>, 0);


uniform texture2D depthTex;
void main ()
{
float depth = texture2D (depthTex, gl_FragCoord.xy).a;
}