advanced_postprocessing.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. .. _doc_advanced_postprocessing:
  2. Advanced post-processing
  3. ========================
  4. Introduction
  5. ------------
  6. This tutorial describes an advanced method for post-processing in Godot.
  7. In particular, it will explain how to write a post-processing shader that
  8. uses the depth buffer. You should already be familiar with post-processing
  9. generally and, in particular, with the methods outlined in the :ref:`custom post-processing tutorial <doc_custom_postprocessing>`.
  10. Full screen quad
  11. ----------------
  12. One way to make custom post-processing effects is by using a viewport. However,
  13. there are two main drawbacks of using a Viewport:
  14. 1. The depth buffer cannot be accessed
  15. 2. The effect of the post-processing shader is not visible in the editor
  16. To get around the limitation on using the depth buffer, use a :ref:`MeshInstance3D <class_MeshInstance3D>`
  17. with a :ref:`QuadMesh <class_QuadMesh>` primitive. This allows us to use a
  18. shader and to access the depth texture of the scene. Next, use a vertex shader
  19. to make the quad cover the screen at all times so that the post-processing
  20. effect will be applied at all times, including in the editor.
  21. First, create a new MeshInstance3D and set its mesh to a QuadMesh. This creates
  22. a quad centered at position ``(0, 0, 0)`` with a width and height of ``1``. Set
  23. the width and height to ``2`` and enable **Flip Faces**. Right now, the quad
  24. occupies a position in world space at the origin. However, we want it to move
  25. with the camera so that it always covers the entire screen. To do this, we will
  26. bypass the coordinate transforms that translate the vertex positions through the
  27. difference coordinate spaces and treat the vertices as if they were already in
  28. clip space.
  29. The vertex shader expects coordinates to be output in clip space, which are coordinates
  30. ranging from ``-1`` at the left and bottom of the screen to ``1`` at the top and right
  31. of the screen. This is why the QuadMesh needs to have height and width of ``2``.
  32. Godot handles the transform from model to view space to clip space behind the scenes,
  33. so we need to nullify the effects of Godot's transformations. We do this by setting the
  34. ``POSITION`` built-in to our desired position. ``POSITION`` bypasses the built-in transformations
  35. and sets the vertex position in clip space directly.
  36. .. code-block:: glsl
  37. shader_type spatial;
  38. // Prevent the quad from being affected by lighting and fog. This also improves performance.
  39. render_mode unshaded, fog_disabled;
  40. void vertex() {
  41. POSITION = vec4(VERTEX.xy, 1.0, 1.0);
  42. }
  43. .. note:: In versions of Godot earlier than 4.3, this code recommended using ``POSITION = vec4(VERTEX, 1.0);``
  44. which implicitly assumed the clip-space near plane was at ``0.0``.
  45. That code is now incorrect and will not work in versions 4.3+ as we
  46. use a "reversed-z" depth buffer now where the near plane is at ``1.0``.
  47. Even with this vertex shader, the quad keeps disappearing. This is due to frustum
  48. culling, which is done on the CPU. Frustum culling uses the camera matrix and the
  49. AABBs of Meshes to determine if the Mesh will be visible *before* passing it to the GPU.
  50. The CPU has no knowledge of what we are doing with the vertices, so it assumes the
  51. coordinates specified refer to world positions, not clip space positions, which results
  52. in Godot culling the quad when we turn away from the center of the scene. In
  53. order to keep the quad from being culled, there are a few options:
  54. 1. Add the QuadMesh as a child to the camera, so the camera is always pointed at it
  55. 2. Set the Geometry property ``extra_cull_margin`` as large as possible in the QuadMesh
  56. The second option ensures that the quad is visible in the editor, while the first
  57. option guarantees that it will still be visible even if the camera moves outside the cull margin.
  58. You can also use both options.
  59. Depth texture
  60. -------------
  61. To read from the depth texture, we first need to create a texture uniform set to the depth buffer
  62. by using ``hint_depth_texture``.
  63. .. code-block:: glsl
  64. uniform sampler2D depth_texture : hint_depth_texture;
  65. Once defined, the depth texture can be read with the ``texture()`` function.
  66. .. code-block:: glsl
  67. float depth = texture(depth_texture, SCREEN_UV).x;
  68. .. note:: Similar to accessing the screen texture, accessing the depth texture is only
  69. possible when reading from the current viewport. The depth texture cannot be
  70. accessed from another viewport to which you have rendered.
  71. The values returned by ``depth_texture`` are between ``1.0`` and ``0.0`` (corresponding to
  72. the near and far plane, respectively, because of using a "reverse-z" depth buffer) and are nonlinear.
  73. When displaying depth directly from the ``depth_texture``, everything will look almost
  74. black unless it is very close due to that nonlinearity. In order to make the depth value align with world or
  75. model coordinates, we need to linearize the value. When we apply the projection matrix to the
  76. vertex position, the z value is made nonlinear, so to linearize it, we multiply it by the
  77. inverse of the projection matrix, which in Godot, is accessible with the variable
  78. ``INV_PROJECTION_MATRIX``.
  79. Firstly, take the screen space coordinates and transform them into normalized device
  80. coordinates (NDC). NDC run ``-1.0`` to ``1.0`` in ``x`` and ``y`` directions and
  81. from ``0.0`` to ``1.0`` in the ``z`` direction when using the Vulkan backend.
  82. Reconstruct the NDC using ``SCREEN_UV`` for the ``x`` and ``y`` axis, and
  83. the depth value for ``z``.
  84. .. code-block:: glsl
  85. void fragment() {
  86. float depth = texture(depth_texture, SCREEN_UV).x;
  87. vec3 ndc = vec3(SCREEN_UV * 2.0 - 1.0, depth);
  88. }
  89. .. note::
  90. This tutorial assumes the use of the Forward+ or Mobile renderers, which both
  91. use Vulkan NDCs with a Z-range of ``[0.0, 1.0]``. In contrast, the Compatibility
  92. renderer uses OpenGL NDCs with a Z-range of ``[-1.0, 1.0]``. For the Compatibility
  93. renderer, replace the NDC calculation with this instead:
  94. .. code-block:: glsl
  95. vec3 ndc = vec3(SCREEN_UV, depth) * 2.0 - 1.0;
  96. You can also use the ``CURRENT_RENDERER`` and ``RENDERER_COMPATIBILITY``
  97. built-in defines for a shader that will work in all renderers:
  98. .. code-block:: glsl
  99. #if CURRENT_RENDERER == RENDERER_COMPATIBILITY
  100. vec3 ndc = vec3(SCREEN_UV, depth) * 2.0 - 1.0;
  101. #else
  102. vec3 ndc = vec3(SCREEN_UV * 2.0 - 1.0, depth);
  103. #endif
  104. Convert NDC to view space by multiplying the NDC by ``INV_PROJECTION_MATRIX``.
  105. Recall that view space gives positions relative to the camera, so the ``z`` value will give us
  106. the distance to the point.
  107. .. code-block:: glsl
  108. void fragment() {
  109. ...
  110. vec4 view = INV_PROJECTION_MATRIX * vec4(ndc, 1.0);
  111. view.xyz /= view.w;
  112. float linear_depth = -view.z;
  113. }
  114. Because the camera is facing the negative ``z`` direction, the position will have a negative ``z`` value.
  115. In order to get a usable depth value, we have to negate ``view.z``.
  116. The world position can be constructed from the depth buffer using the following code, using the
  117. ``INV_VIEW_MATRIX`` to transform the position from view space into world space.
  118. .. code-block:: glsl
  119. void fragment() {
  120. ...
  121. vec4 world = INV_VIEW_MATRIX * INV_PROJECTION_MATRIX * vec4(ndc, 1.0);
  122. vec3 world_position = world.xyz / world.w;
  123. }
  124. Example shader
  125. --------------
  126. Once we add a line to output to ``ALBEDO``, we have a complete shader that looks something like this.
  127. This shader lets you visualize the linear depth or world space coordinates, depending on which
  128. line is commented out.
  129. .. code-block:: glsl
  130. shader_type spatial;
  131. // Prevent the quad from being affected by lighting and fog. This also improves performance.
  132. render_mode unshaded, fog_disabled;
  133. uniform sampler2D depth_texture : hint_depth_texture;
  134. void vertex() {
  135. POSITION = vec4(VERTEX.xy, 1.0, 1.0);
  136. }
  137. void fragment() {
  138. float depth = texture(depth_texture, SCREEN_UV).x;
  139. vec3 ndc = vec3(SCREEN_UV * 2.0 - 1.0, depth);
  140. vec4 view = INV_PROJECTION_MATRIX * vec4(ndc, 1.0);
  141. view.xyz /= view.w;
  142. float linear_depth = -view.z;
  143. vec4 world = INV_VIEW_MATRIX * INV_PROJECTION_MATRIX * vec4(ndc, 1.0);
  144. vec3 world_position = world.xyz / world.w;
  145. // Visualize linear depth
  146. ALBEDO.rgb = vec3(fract(linear_depth));
  147. // Visualize world coordinates
  148. //ALBEDO.rgb = fract(world_position).xyz;
  149. }
  150. An optimization
  151. ---------------
  152. You can benefit from using a single large triangle rather than using a full
  153. screen quad. The reason for this is explained `here <https://michaldrobot.com/2014/04/01/gcn-execution-patterns-in-full-screen-passes>`_.
  154. However, the benefit is quite small and only beneficial when running especially
  155. complex fragment shaders.
  156. Set the Mesh in the MeshInstance3D to an :ref:`ArrayMesh <class_ArrayMesh>`. An
  157. ArrayMesh is a tool that allows you to easily construct a Mesh from Arrays for
  158. vertices, normals, colors, etc.
  159. Now, attach a script to the MeshInstance3D and use the following code:
  160. ::
  161. extends MeshInstance3D
  162. func _ready():
  163. # Create a single triangle out of vertices:
  164. var verts = PackedVector3Array()
  165. verts.append(Vector3(-1.0, -1.0, 0.0))
  166. verts.append(Vector3(-1.0, 3.0, 0.0))
  167. verts.append(Vector3(3.0, -1.0, 0.0))
  168. # Create an array of arrays.
  169. # This could contain normals, colors, UVs, etc.
  170. var mesh_array = []
  171. mesh_array.resize(Mesh.ARRAY_MAX) #required size for ArrayMesh Array
  172. mesh_array[Mesh.ARRAY_VERTEX] = verts #position of vertex array in ArrayMesh Array
  173. # Create mesh from mesh_array:
  174. mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, mesh_array)
  175. .. note:: The triangle is specified in normalized device coordinates.
  176. Recall, NDC run from ``-1.0`` to ``1.0`` in both the ``x`` and ``y``
  177. directions. This makes the screen ``2`` units wide and ``2`` units
  178. tall. In order to cover the entire screen with a single triangle, use
  179. a triangle that is ``4`` units wide and ``4`` units tall, double its
  180. height and width.
  181. Assign the same vertex shader from above and everything should look exactly the same.
  182. The one drawback to using an ArrayMesh over using a QuadMesh is that the ArrayMesh
  183. is not visible in the editor because the triangle is not constructed until the scene
  184. is run. To get around that, construct a single triangle Mesh in a modeling program
  185. and use that in the MeshInstance3D instead.