Advertisement

Reconstruct world position from depth

Started by June 21, 2019 02:30 PM
2 comments, last by congard 5 years, 7 months ago

I am trying to restore the position from the depths. I separately created a position map in view space, which I use as a basis for tests. But I can not get the same result when I try to reconstruct the position from the depth. Here's how I'm trying to do this:


#define getPosition(texCoord) texture(positionMap, texCoord).xyz

vec3 posFromDepth(float depth) {
    float z = depth * 2.0 - 1.0;

    vec4 clipSpacePosition = vec4(texCoord * 2.0 - 1.0, z, 1.0);
    vec4 viewSpacePosition = inverse(projection) * clipSpacePosition;

    // Perspective division
    viewSpacePosition /= viewSpacePosition.w;

    return viewSpacePosition.xyz;
}

void main() {
    float d = -(projection * vec4(getPosition(texCoord), 1.0)).z; // get depth
    fragColor = posFromDepth(d);
    //fragColor = getPosition(texCoord);
    fragColor = clamp(fragColor, 0, 1);
}

Here is the correct position map:

scr_screenspace___.thumb.png.528f1b92a4790b768bcf457b18889440.png

But reconstructed looks like this:

scr_screenspace_.thumb.png.db1042ff3b0a26584506c0789fe61da4.png

What am I doing wrong?

The "wrong" image looks like a view space position map. You have to transform the depth by the inverse of viewProjection matrix to get to world space, but now you are just transforming by the inverse projection.

Advertisement
10 hours ago, turanszkij said:

The "wrong" image looks like a view space position map. You have to transform the depth by the inverse of viewProjection matrix to get to world space, but now you are just transforming by the inverse projection.

On the correct image there is view space position map, I forgot to clarify

This topic is closed to new replies.

Advertisement