I want to unproject the gl_FragCoord to get the 3D coordinats in camera space. This is my code in fragment shader,but it doesn’t work.The input is gl_FragCoord.

vec4 getcoord (vec4 a)

{

vec4 d=vec4(a.x*2/Size-1,a.y*2/Size-1,a.z*2-1,1);*

vec4 c=gl_ProjectionMatrixInversed;

return c/c.w;

}

And,I want to calculate the coordinats in camera space using a depth buffer.So,as I know the depth of a pixel,how do I get the coordinats in camera space?I do it like this in fragment shader.Does it work?

vec4 getcoord (sampler2D depth,vec2 a)//a is the pixel’s 2D screen coordinate

{

float de=texelFetch2D(depth,ivec2(a),0);

vec4 b=vec4(a,de,1.0);

vec4 c=vec4(b.x*2/Size-1,b.y*2/Size-1,b.z*2-1,1);*

vec4 e=gl_ProjectionMatrixInversec;

return e/e.w;

}

Thanks!

This is my code in fragment shader,but it doesn’t work.

The perspective divide happens after the projection matrix when transforming to camera space to clip space. Therefore, when reversing the transformation, it must happen before. And the division needs to be done with gl_FragCoord.w.

You can find functioning code to do this here.

The second part is going to be more difficult, since you don’t have gl_FragCoord.w. So you’re going to have to compute it.

Thanks.

But I still have some confusion with the webpage you give me.

Does “clipToCameraMatrix” equal to gl_ProjectionMatrixInverse?

And I think the factor “1/gl_FragCoord.w” doesn’t influence the result of “clipToCameraMatrix * clipPos”,for this is a homogeneous coordinate,and I can divide the result’s w after multiplying.

Does “clipToCameraMatrix” equal to gl_ProjectionMatrixInverse?

Yes.

And I think the factor “1/gl_FragCoord.w” doesn’t influence the result of “clipToCameraMatrix * clipPos”,for this is a homogeneous coordinate,and I can divide the result’s w after multiplying.

But applying 1/gl_FragCoord.w to “ndcPos” is how you get “clipPos.” Until you do this division, you’re not in homogeneous space, and your matrix multiplication will most certainly not come out wrong.

When you invert a series of steps, you must do the inverse in reverse order.