I have a platform where this extension is not available ( non NVIDIA ). How could I emulate this functionality ? I need it to solve far plane clipping problem when rendering stencil shadow volumes with z-fail algorithm.
Asked
Active
Viewed 2,917 times
2
-
I am trying to emulate this extension in the fragment shader with `gl_FragDepth = clamp( gl_FragCoord.z, gl_DepthRange.near, gl_DepthRange.far );` but it is not working as it should. – user265149 May 12 '11 at 12:53
-
The reason why clamping the output z-value doesn't work is because the triangle rasterization rules prevents fragments from being generated in the first place. – kusma Mar 05 '12 at 11:58
2 Answers
5
Since you say you're using OpenGL ES, but also mentioned trying to clamp gl_FragDepth, I'm assuming you're using OpenGL ES 2.0, so here's a shader trick:
You can emulate ARB_depth_clamp by using a separate varying for the z-component.
Vertex Shader:
varying float z;
void main()
{
gl_Position = ftransform();
// transform z to window coordinates
z = gl_Position.z / gl_Position.w;
z = (gl_DepthRange.diff * z + gl_DepthRange.near + gl_DepthRange.far) * 0.5;
// prevent z-clipping
gl_Position.z = 0.0;
}
Fragment shader:
varying float z;
void main()
{
gl_FragColor = vec4(vec3(z), 1.0);
gl_FragDepth = clamp(z, 0.0, 1.0);
}

kusma
- 6,516
- 2
- 22
- 26
-
Would it be correct to clamp z already in vertex shader? Would it help performance? – Constantin Nov 09 '14 at 16:42
1
"Fall back" to ARB_depth_clamp
?
Check if NV_depth_clamp
exists anyway? For example my ATI card supports five "NVidia-only" GL extensions.

genpfault
- 51,148
- 11
- 85
- 139