Calculating Depth value in Fragment Shaders.

Is it possible to compute a fragment’s depth value in a fragment shader, and if so, does anyone have an equation or algorithm that does this? Or is the equation used to generate depth values platform specific? I want to use it to compare a fragment’s depth value with those stored in a depth texture representing a terrain mess’ depth values, sort of like doing depth testing in the fragment shader but with more control.

in glsl the fixed function fragments depth can be optained with gl_FragCoord.z (or is this not what u mean)

I’m using Cg, so I don’t think I have access to that value.

Actually, does that represent the value that would be written to the depth buffer?

You have access to that in Cg. Search the Cg manual for the WPOS semantic.

And for the other question read the GLSL spec.
“The variable gl_FragCoord is available as a read-only variable from within fragment shaders and it holds the window relative coordinates x, y, z, and 1/w values for the fragment. This value is the result of the fixed functionality that interpolates primitives after vertex processing to generate fragments. The z component is the depth value that would be used for the fragment’s depth if a shader contained no writes to gl_FragDepth. This is useful for invariance if a shader conditionally computes gl_FragDepth but otherwise wants the fixed functionality fragment depth.”

With respect to distance from eye, what kind of function is used to calculated depth? I know it’s not linear.

Depends on the space. E.g. distance from eye is linear in eye-space.
Check the transformation matrices in the OpenGL Programming Guide (RedBook, search for the PDF) appendix about homogenous transformations or read the OpenGL 2.0 spec chapter 2.11 on transformations.