Shader to get view-space position from depth texture; INV_PROJECTION_MATRIX?

Godot Version

4.3

Context

I have a pair of spatial shaders, shader A and shader B, which render from their own respective cameras onto their respective viewports. Shader A records the nonlinear depth of the scene (i.e. FRAGCOORD.z) from camera A to a texture. Shader B reads from this texture, and also receives as uniforms the inverses of the view and projection matrices of camera A, in order to ultimately get the world-space position of a point rasterized by camera A.

I have three questions about this snippet to get the view-space position from a depth texture, as it appears in the documentation:

uniform sampler2D depth_texture : hint_depth_texture, repeat_disable, filter_nearest;

void fragment() {
    float depth = textureLod(depth_texture, SCREEN_UV, 0.0).r;
    vec4 upos = INV_PROJECTION_MATRIX * vec4(SCREEN_UV * 2.0 - 1.0, depth, 1.0);
    vec3 pixel_position = upos.xyz / upos.w;
}

Question

  1. What does hint_depth_texture do? Does it affect the result of texelFetch?
  2. How is INV_PROJECTION_MATRIX defined? Is it different from get_camera_projection.inverse()? How can I get a camera’s projection’s INV_PROJECTION_MATRIX in GDScript?
  3. Is pixel_position the view-space position? Will adding on a unit w-component and multiplying it by INV_VIEW_MATRIX get me to world space?

hint_depth_texture is how you tell Godot to give you the depth texture if you want to read from it

1 Like