So, I've got an imposter (the real geometry is a cube, possibly clipped, and the imposter geometry is a Menger sponge) and I need to calculate its depth.
I can calculate the amount to offset in world space fairly easily. Unfortunately, I've spent hours failing to perturb the depth with it.
The only correct results I can get are when I go:
gl_FragDepth = gl_FragCoord.z
Basically, I need to know how gl_FragCoord.z is calculated so that I can:
- Take the inverse transformation from gl_FragCoord.z to eye space
- Add the depth perturbation
- Transform this perturbed depth back into the same space as the original gl_FragCoord.z.
I apologize if this seems like a duplicate question; there's a number of other posts here that address similar things. However, after implementing all of them, none work correctly. Rather than trying to pick one to get help with, at this point, I'm asking for complete code that does it. It should just be a few lines.
For another future reference, this is the same formula as given by imallett, which was working for me in an OpenGL 4.0 application:
Here,
modelview_projection
is 4x4 modelview-projection matrix andv_position
is object-space position of the pixel being rendered (in my case calculated by a raymarcher).The equation comes from the window coordinates section of this manual. Note that in my code, near is
0.0
and far is1.0
, which are the default values ofgl_DepthRange
. Note thatgl_DepthRange
is not the same thing as the near/far distance in the formula for perspective projection matrix! The only trick is using the0.0
and1.0
(orgl_DepthRange
in case you actually need to change it), I've been struggling for an hour with the other depth range - but that is already "baked" in my (perspective) projection matrix.Note that this way, the equation really contains just a single multiply by a constant (
(far - near) / 2
) and a single addition of another constant ((far + near) / 2
). Compare that to multiply, add and divide (possibly converted to a multiply by an optimizing compiler) that is required in the code of imallett.For future reference, the key code is: