What is the role of DEPTH_TEXTURE and VERTEX in the fragment

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ATom 1

I can’t understand the role of DEPTH_TEXTURE, because I always get “1.0”.

float depth = texture(DEPTH_TEXTURE, SCREEN_UV).x;

I want to get the distance between the pixel and the screen in the fragment. I always thought that DEPTH_TEXTURE is what I want. I found VERTEX is what I want ,because It’s the position of the pixel in the camera coordinate space.

Am i wrong about DEPTH_TEXTURE and VERTEX in fragment? I 'm very confused now.
Also, are they similar?

:bust_in_silhouette: Reply From: wombatstampede

You should be able to get the distance by converting VERTEX from (local) ModelView space to view space. The z-coordinate of the resulting Vector3 should be the (negative) “parallel” distance to the view plane. You could also use the length of the Vector if you want the distance to the screen center.

Such a calculation should usually be done in the vertext() part and the result then passed (& automatically interpolated) via a “Varying” to the fragment() shader.
Roughly like this:

shader_type spatial;

varying float z_dist;

void vertex() {
   z_dist = clamp((MODELVIEW_MATRIX * vec4(VERTEX, 1.0)).z * -1.0,0.0,50.0);
}

void fragment() { 
  ALBEDO = vec3(z_dist/50.0,0.1,50.0-(z_dist/50.0));
}

The example varies the color depending on the camera distance. The color in this example is only varied in the z-range of 0-50.

You’ll find examples about the DEPTH_TEXTURE here:

But I’ve read about issues when using it on mobile (Android) targets with the standard settings.

Oh, I just realized that it is even simpler.
VERTEX (by default) is already automatically transformed into view space in the fragment part. (I think this is a bit inconsistent in terms of naming but anyway…)

So the distance to the camera inside the fragment shader simply is VERTEX.z. multiply by -1 if you need a positive value for vertices in view.

Or length(VERTEX) will be the distance from screen center.

One thing about DEPTH_TEXTURE.
To my knowledge that is more useful for i.e. screen reading shaders where no access to the VERTEX is possible. In that case you can calculate from a DEPTH_TEXTURE lookup back to an (approximated) z-depth.
Screen-reading shaders — Godot Engine (latest) documentation in English

wombatstampede | 2020-01-07 14:13

Thank you, this helped me eliminate my confusion

ATom 1 | 2020-01-07 15:30