PDA

View Full Version : Easiest way to reconstruct eye space position



Karmux
02-24-2012, 01:14 PM
Hi,

I'm tring to reconstruct eye space position from depth buffer, but my result doesn't look correct.

This is my current and one of the shortest implementations i found:


float depth = texture2D(depthBuffer, texCoord).r;
vec2 xy = texCoord * 2.0 - 1.0;
vec4 clipPos = vec4(xy, depth, 1.0);
// I pass inverseProjectionMatrix as uniform
vec4 homo = inverseProjectionMatrix * clipPos;
vec3 position = homo.xyz / homo.w;
gl_FragColor = vec4(position, 1.0);
(from: http://www.gamedev.net/topic/577382-calculate-eye-space-position-from-depth/)

This gives me only green-yellow-red colors and no visible 3D objects:
http://www.upload.ee/image/2106871/positions.png

But the correct result should look like this (top right)?
http://mynameismjp.files.wordpress.com/2010/03/position16f.png

I have tried out many examples. Some of them were too difficult and others gave also artifacts etc. If i visualize depth texture, then everything looks correct.

Can anybody see mistake in above code?

Kopelrativ
02-24-2012, 02:13 PM
Why do you want to do it?

Seems it is easier and faster to provide it using a uniform?

Karmux
02-24-2012, 02:26 PM
Why do you want to do it?

Seems it is easier and faster to provide it using a uniform?
The code above is a lighting pass fragment shader in deferred renderer.

GLSL version is 4.1.

Alfonse Reinheart
02-24-2012, 03:51 PM
I actually bookmarked a post of mine on this forum (http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=295698#Post2956 98) to remind myself of how the math works.

I really ought to make a GL Wiki page out of that.

Karmux
02-24-2012, 04:29 PM
I actually bookmarked a post of mine on this forum (http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=295698#Post2956 98) to remind myself of how the math works.

I really ought to make a GL Wiki page out of that.
Amazing! Everything is working perfectly now! Thank you so much! :)

Alfonse Reinheart
02-24-2012, 05:22 PM
Can you post your code, so that others can benefit?

Karmux
02-24-2012, 06:00 PM
Can you post your code, so that others can benefit?
Sure ;)



in vec2 texCoord;
uniform float nearPlane;
uniform float farPlane;
uniform sampler2D depthBuffer;
uniform mat4 inverseProjectionMatrix;

#define ZNEAR nearPlane
#define ZFAR farPlane
#define A (ZNEAR + ZFAR)
#define B (ZNEAR - ZFAR)
#define C (2.0 * ZNEAR * ZFAR)
#define D (ndcPos.z * B)
#define ZEYE (-C / (A + D))

void main() {
float depth = texture2D(depthBuffer, texCoord).r;
vec3 ndcPos = (vec3 (texCoord, depth) - 0.5) * 2.0;
vec4 clipPos;
clipPos.w = -ZEYE;
clipPos.xyz = ndcPos * clipPos.w;
vec4 eyePos = inverseProjectionMatrix * clipPos;
gl_FragColor = vec4(eyePos);
}