GLSL and z-buffer

Happy New Year !!

Is there any way to read the value of z-buffer in fragment shader? The idea is to perform early z-cull and descard the fragment, not to wait shader execution and later fixed z-test.

Originally posted by nik_bg:
[b]Happy New Year !!

Is there any way to read the value of z-buffer in fragment shader? The idea is to perform early z-cull and descard the fragment, not to wait shader execution and later fixed z-test.[/b]
If you do not change the z-value in the fragment shader, it WILL do early z-testing before the shader is executed.
But if you change the z-value, it can’t do that… (for obvious reasons)

And if you have like me a GfFX, the descard command doesn’t make the shader any faster at all. It still goes trough every instruction.

Where did you read it WILL do early z-cull if no assignment to z value is done in the shader? I was unable to find this in the GLSL specification… I can’t remember the exact page, but it states that all z/stencil tests are done AFTER shader execution.

nik_bg, early Z rejection is not in the spec.

But it is nice for the hardware to know that a particular fragment does not need shading because it will be rejected anyway. Most modern cards do this, and that is a reason why many engines (such as Doom3 etc) do a first pass with only ambient lighting and Z filling. Subsequent passes will benefit from early z rejection.

Of course if the shader modify the Z value, this early z test can not happen.

Don’t forget that GPUs are not CPUs, branching and testing in shaders cost a LOT MORE than doing a bunch of unuseful pipelined operations.

The OpenGL Graphics System: A Specification
(Version 2.0 - October 22, 2004) p. 3:

1.5 Our View
We view OpenGL as a state machine that controls a set of specific drawing operations. This model should engender a specification that satisfies the needs of both programmers and implementors. It does not, however, necessarily provide a model for implementation. An implementation must produce results conforming to those produced by the specified methods, but there may be ways to carry out a particular computation that are more efficient than the one specified. (emphasis mine)

So, even though the specification says to depth test AFTER shading, implementations are free to find more efficient methods so long as the RESULTS are the same. Since depth testing is cheap compared to shading, depth tests before shading may be far more efficient. Several implementations will do early depth tests.

A good paper on using early depth test to accelerate shading is Sander, Tatarchuck and Mitchell’s “Explicit Early-Z Culling for Efficient Fluid Flow Simulation and Rendering.”

http://www.ati.com/developer/techreports/ATITechReport_EarlyZFlow.pdf

-mr. bill

Thank you very much :slight_smile: )