# Reconstructing depth from depth buffer texture

Hello~

I have looked at many posts now on how to reconstruct world position from a depth value. However I am trying to avoid writing my depth out to a separate fbo and instead use the depth in my depth buffer as a texture to reconstruct the world position. I previously had this working by writing out linear depth to a separate fbo, but now I want to not write to that extra fbo…

I believe the bottom of this page shows me how to do it: Position From Depth 3: Back In The Habit – The Danger Zone But I have had no luck. Could someone tell me what “EyeZAxis” is supposed to represent? I thought it was the direction the camera is looking in world space?

Thanks!

This should get you back to EYE-SPACE:

``````
vec3 PositionFromDepth_DarkPhoton(in float depth)
{
vec2 ndc;             // Reconstructed NDC-space position
vec3 eye;             // Reconstructed EYE-space position

eye.z = near * far / ((depth * (far - near)) - far);

ndc.x = ((gl_FragCoord.x * widthInv) - 0.5) * 2.0;
ndc.y = ((gl_FragCoord.y * heightInv) - 0.5) * 2.0;

eye.x = ( (-ndc.x * eye.z) * (right-left)/(2*near)
- eye.z * (right+left)/(2*near) );
eye.y = ( (-ndc.y * eye.z) * (top-bottom)/(2*near)
- eye.z * (top+bottom)/(2*near) );

return eye;
}

``````

depth is the 0…1 input depth buffer value, gl_FragCoord.xy is its 0…1 position across the window, widthInv and heightInv are 1/resolution values, and left/right/bottom/top/near/far are your glFrustum projection parameters

Thanks dark photon! Is it correct that my depth is going to be 0…1 ? Because I am using the depth straight out of the depth buffer so it will not be linear. (At least it doesn’t seem to be)

The eye-space Z (-near,-far) range is mapped to the window-space Z range you specify with glDepthRange() (by default 0…1). The above math presumes a 0…1 window-space Z range, though you can easily modify it if that’s not the case.

Because I am using the depth straight out of the depth buffer so it will not be linear. (At least it doesn’t seem to be)

Correct, if you are using a Perspective projection. The above math presumes Perspective and re-linearizes the depth value (notice the 1/depth in computing eye.z).

(Note however that, different from Perspective, Orthographic projection maps eye-space Z linearly to window-space Z.)