Skip to content

Commit 4d42b74

Browse files
authored
Merge pull request #9766 from tetrapod00/advanced-postprocessing-example
Add example to advanced_postprocessing.rst
2 parents 5980166 + d49dfae commit 4d42b74

File tree

1 file changed

+36
-7
lines changed

1 file changed

+36
-7
lines changed

tutorials/shaders/advanced_postprocessing.rst

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -136,22 +136,51 @@ the distance to the point.
136136
Because the camera is facing the negative ``z`` direction, the position will have a negative ``z`` value.
137137
In order to get a usable depth value, we have to negate ``view.z``.
138138

139-
The world position can be constructed from the depth buffer using the following code. Note
140-
that the ``INV_VIEW_MATRIX`` is needed to transform the position from view space into world space, so
141-
it needs to be passed to the fragment shader with a varying.
139+
The world position can be constructed from the depth buffer using the following code, using the
140+
``INV_VIEW_MATRIX`` to transform the position from view space into world space.
142141

143142
.. code-block:: glsl
144143
145-
varying mat4 CAMERA;
144+
void fragment() {
145+
...
146+
vec4 world = INV_VIEW_MATRIX * INV_PROJECTION_MATRIX * vec4(ndc, 1.0);
147+
vec3 world_position = world.xyz / world.w;
148+
}
149+
150+
Example shader
151+
--------------
152+
153+
Once we add a line to output to ``ALBEDO``, we have a complete shader that looks something like this.
154+
This shader lets you visualize the linear depth or world space coordinates, depending on which
155+
line is commented out.
156+
157+
.. code-block:: glsl
158+
159+
shader_type spatial;
160+
// Prevent the quad from being affected by lighting and fog. This also improves performance.
161+
render_mode unshaded, fog_disabled;
162+
163+
uniform sampler2D depth_texture : source_color, hint_depth_texture;
146164
147165
void vertex() {
148-
CAMERA = INV_VIEW_MATRIX;
166+
POSITION = vec4(VERTEX.xy, 1.0, 1.0);
149167
}
150168
151169
void fragment() {
152-
...
153-
vec4 world = CAMERA * INV_PROJECTION_MATRIX * vec4(ndc, 1.0);
170+
float depth = texture(depth_texture, SCREEN_UV).x;
171+
vec3 ndc = vec3(SCREEN_UV * 2.0 - 1.0, depth);
172+
vec4 view = INV_PROJECTION_MATRIX * vec4(ndc, 1.0);
173+
view.xyz /= view.w;
174+
float linear_depth = -view.z;
175+
176+
vec4 world = INV_VIEW_MATRIX * INV_PROJECTION_MATRIX * vec4(ndc, 1.0);
154177
vec3 world_position = world.xyz / world.w;
178+
179+
// Visualize linear depth
180+
ALBEDO.rgb = vec3(fract(linear_depth));
181+
182+
// Visualize world coordinates
183+
//ALBEDO.rgb = fract(world_position).xyz;
155184
}
156185
157186
An optimization

0 commit comments

Comments
 (0)