PDA

View Full Version : Retrieving eye-space position from depth buffer?



CortS
07-25-2010, 02:40 AM
Apologies for asking a question that's been asked several times before in various forms, but...how do I reconstruct the eye-space coordinates of a pixel given its corresponding raw depth buffer value?

Here's my current, incorrect code (based on the docs for gluUnproject (http://pyopengl.sourceforge.net/documentation/manual/gluUnProject.3G.html)):

// BAD CODE -- DOESN'T WORK!!!

// Sample the depth buffer (stored as float32 data)
float rawDepth = texture2D(depthTex, texCoord.xy).r;

// Construct clip-space position using gl_FragCoord, raw
// depth value, and the GL viewport
vec4 clipPos = vec4(
2.0 * (gl_FragCoord.x - viewport.x) / viewport.z - 1.0,
2.0 * (gl_FragCoord.y - viewport.y) / viewport.w - 1.0,
2.0 * rawDepth - 1.0,
1.0
);

// Multiply by inverse projection matrix to get
// eye-space position
vec4 eyePos = matInverseProj * clipPos;


But this doesn't seem to work 100%. Am I missing a perspective divide by W somewhere? Do I need to pre-process the raw depth value before using it in the formula for clipPos?

Thanks!
- cort

Ilian Dinev
07-25-2010, 06:19 AM
Yes, only at the end, add:

eyePos = eyePos/eyePos.w;

CortS
07-27-2010, 01:55 PM
Yup, that did the trick. Thanks!

kRogue
07-30-2010, 04:23 AM
Just one thing to watch out for, usually reading the depth value directly from a depth texture often gives wonky results for lighting calculations (the case is much less so using a Float32 buffer as you are).. when doing differed shading, I'd recommend storing eyePos_z (i.e. store linear z), and you can extract eyePos_x and eyePos_y from it. The wonkiness comes from the perspective divide.