# Easiest way to reconstruct eye space position

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);

``````

This gives me only green-yellow-red colors and no visible 3D objects:

But the correct result should look like this (top right)?

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?

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.

I actually bookmarked a post of mine on this forum 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!

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);
}

``````