Depth texture GLSL

I have a texture with GL_DEPTH_COMPONENT and retrieved the values via glCopyTexture function, in debugger everything is fine and depth can be seen properly. I can’t figure out how to read the depth in a fragment shader since on the web some suggest texture2D function while others say it will return undefined results and shadow2D is the only way. Also the compare texture mode is confusing. Help and source examples are welcome.

Edit: Should have posted in GLSL forums.

It’s not difficult to read from a depth texture - every engine starts to do it that sooner or later :wink:

First, set texture compare mode to None. Second, access your texture with texture2D (picking R component). That’s all.

Use shadow2D with set up texture compare mode if you want HW depth comparison instead of a simple fetch.

DmitryM’s got you covered. A bit more detail from what I’ve read.

You have a choice: do hardware depth compare (with or without PCF) or not.

For pre-GLSL 1.3: For depth compare, use a Shadow sampler, enable GL_TEXTURE_COMPARE_MODE and use shadow* texture access method (e.g. shadow2DProj). For no depth compare, use a non-Shadow sampler, don’t enable GL_TEXTURE_COMPARE_MODE and use a texture* texture access method (e.g. texture2DProj).

For GLSL 1.3+: Same, except GLSL 1.3 removes the typing redundancy between sampler names and texture access method names. Just use the appropriate texture* texture access method in all cases (e.g. textureProj).

Thanks so far. I tried both ways and seen that the returned value is actually strange for sampler2D. Someone on the web powered the returned R to 70 to get proper depth. <pow(depthv,70.0)>. Apparently they are distributed in 0.9 - 1.0 range or something like that. Why the specs say using GL_DEPTH_COMPONENT an sampler2D will be undefined yet many people use it? I’m missing something?

Maybe it’s the 1/z you’re missing. And the near-plane. A pow() has no place there.

Could easily be. It all depends on the projection transform in-play when you’re rendering that depth map. With a standard perspective (point lights), most of your precision is clustered near the near plane (0.0).

For better precision in your scene (e.g. widen that 0.9…1.0 range), push the near clip out before computing your light-space projection transform.

_NK47, you read the spec incorrectly.

It states that the result of sampling is undefined if you mix compare mode with sampler type in a bad way (true + texture2d, false + shadow2d).

Careful touch opens doors for you to GL treasures :wink:

Add: I use to pow(depth,50) for the debug output as well.

that seems enough to get started. will use sampler2D for the actual depth here since the sampler2DShadow returns plain 0.0 or 1.0. thanks everyone.