compositor.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. .. _doc_compositor:
  2. The Compositor
  3. ==============
  4. The compositor is a new feature in Godot 4 that allows control over
  5. the rendering pipeline when rendering the contents of a :ref:`Viewport <class_Viewport>`.
  6. It can be configured on a :ref:`WorldEnvironment <class_WorldEnvironment>`
  7. node where it applies to all Viewports, or it can be configured on
  8. a :ref:`Camera3D <class_Camera3D>` and apply only to
  9. the Viewport using that camera.
  10. The :ref:`Compositor <class_Compositor>` resource is used to configure
  11. the compositor. To get started, simply create a new compositor on
  12. the appropriate node:
  13. .. image:: img/new_compositor.webp
  14. .. note::
  15. The compositor is currently a feature that is only supported by
  16. the Mobile and Forward+ renderers.
  17. Compositor effects
  18. ------------------
  19. Compositor effects allow you to insert additional logic into the rendering
  20. pipeline at various stages. This is an advanced feature that requires
  21. a high level of understanding of the rendering pipeline to use to
  22. its best advantage.
  23. As the core logic of the compositor effect is called from the rendering
  24. pipeline it is important to note that this logic will thus run within
  25. the thread on which rendering takes place.
  26. Care needs to be taken to ensure we don't run into threading issues.
  27. To illustrate how to use compositor effects we'll create a simple
  28. post processing effect that allows you to write your own shader code
  29. and apply this full screen through a compute shader.
  30. You can find the finished demo project `here <https://github.com/godotengine/godot-demo-projects/tree/master/compute/post_shader>`_.
  31. We start by creating a new script called ``post_process_shader.gd``.
  32. We'll make this a tool script so we can see the compositor effect work in the editor.
  33. We need to extend our node from :ref:`CompositorEffect <class_CompositorEffect>`.
  34. We must also give our script a class name.
  35. .. code-block:: gdscript
  36. :caption: post_process_shader.gd
  37. @tool
  38. extends CompositorEffect
  39. class_name PostProcessShader
  40. Next we're going to define a constant for our shader template code.
  41. This is the boilerplate code that makes our compute shader work.
  42. .. code-block:: gdscript
  43. const template_shader : String = "#version 450
  44. // Invocations in the (x, y, z) dimension
  45. layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
  46. layout(rgba16f, set = 0, binding = 0) uniform image2D color_image;
  47. // Our push constant
  48. layout(push_constant, std430) uniform Params {
  49. vec2 raster_size;
  50. vec2 reserved;
  51. } params;
  52. // The code we want to execute in each invocation
  53. void main() {
  54. ivec2 uv = ivec2(gl_GlobalInvocationID.xy);
  55. ivec2 size = ivec2(params.raster_size);
  56. if (uv.x >= size.x || uv.y >= size.y) {
  57. return;
  58. }
  59. vec4 color = imageLoad(color_image, uv);
  60. #COMPUTE_CODE
  61. imageStore(color_image, uv, color);
  62. }"
  63. For more information on how compute shaders work,
  64. please check :ref:`Using compute shaders <doc_compute_shaders>`.
  65. The important bit here is that for every pixel on our screen,
  66. our ``main`` function is executed and inside of this we load
  67. the current color value of our pixel, execute our user code,
  68. and write our modified color back to our color image.
  69. ``#COMPUTE_CODE`` gets replaced by our user code.
  70. In order to set our user code, we need an export variable.
  71. We'll also define a few script variables we'll be using:
  72. .. code-block:: gdscript
  73. @export_multiline var shader_code : String = "":
  74. set(value):
  75. mutex.lock()
  76. shader_code = value
  77. shader_is_dirty = true
  78. mutex.unlock()
  79. var rd : RenderingDevice
  80. var shader : RID
  81. var pipeline : RID
  82. var mutex : Mutex = Mutex.new()
  83. var shader_is_dirty : bool = true
  84. Note the use of a :ref:`Mutex <class_Mutex>` in our code.
  85. Most of our implementation gets called from the rendering engine
  86. and thus runs within our rendering thread.
  87. We need to ensure that we set our new shader code, and mark our
  88. shader code as dirty, without our render thread accessing this
  89. data at the same time.
  90. Next we initialize our effect.
  91. .. code-block:: gdscript
  92. # Called when this resource is constructed.
  93. func _init():
  94. effect_callback_type = EFFECT_CALLBACK_TYPE_POST_TRANSPARENT
  95. rd = RenderingServer.get_rendering_device()
  96. The main thing here is setting our ``effect_callback_type`` which tells
  97. the rendering engine at what stage of the render pipeline to call our code.
  98. .. note::
  99. Currently we only have access to the stages of the 3D rendering pipeline!
  100. We also get a reference to our rendering device, which will come in very handy.
  101. We also need to clean up after ourselves, for this we react to the
  102. ``NOTIFICATION_PREDELETE`` notification:
  103. .. code-block:: gdscript
  104. # System notifications, we want to react on the notification that
  105. # alerts us we are about to be destroyed.
  106. func _notification(what):
  107. if what == NOTIFICATION_PREDELETE:
  108. if shader.is_valid():
  109. # Freeing our shader will also free any dependents such as the pipeline!
  110. rd.free_rid(shader)
  111. Note that we do not use our mutex here even though we create our shader inside
  112. of our render thread.
  113. The methods on our rendering server are thread safe and ``free_rid`` will
  114. be postponed cleaning up the shader until after any frames currently being
  115. rendered are finished.
  116. Also note that we are not freeing our pipeline. The rendering device does
  117. dependency tracking and as the pipeline is dependent on the shader, it will
  118. be automatically freed when the shader is destructed.
  119. From this point onwards our code will run on the rendering thread.
  120. Our next step is a helper function that will recompile the shader if the user
  121. code was changed.
  122. .. code-block:: gdscript
  123. # Check if our shader has changed and needs to be recompiled.
  124. func _check_shader() -> bool:
  125. if not rd:
  126. return false
  127. var new_shader_code : String = ""
  128. # Check if our shader is dirty.
  129. mutex.lock()
  130. if shader_is_dirty:
  131. new_shader_code = shader_code
  132. shader_is_dirty = false
  133. mutex.unlock()
  134. # We don't have a (new) shader?
  135. if new_shader_code.is_empty():
  136. return pipeline.is_valid()
  137. # Apply template.
  138. new_shader_code = template_shader.replace("#COMPUTE_CODE", new_shader_code);
  139. # Out with the old.
  140. if shader.is_valid():
  141. rd.free_rid(shader)
  142. shader = RID()
  143. pipeline = RID()
  144. # In with the new.
  145. var shader_source : RDShaderSource = RDShaderSource.new()
  146. shader_source.language = RenderingDevice.SHADER_LANGUAGE_GLSL
  147. shader_source.source_compute = new_shader_code
  148. var shader_spirv : RDShaderSPIRV = rd.shader_compile_spirv_from_source(shader_source)
  149. if shader_spirv.compile_error_compute != "":
  150. push_error(shader_spirv.compile_error_compute)
  151. push_error("In: " + new_shader_code)
  152. return false
  153. shader = rd.shader_create_from_spirv(shader_spirv)
  154. if not shader.is_valid():
  155. return false
  156. pipeline = rd.compute_pipeline_create(shader)
  157. return pipeline.is_valid()
  158. At the top of this method we again use our mutex to protect accessing our
  159. user shader code and our is dirty flag.
  160. We make a local copy of the user shader code if our user shader code is dirty.
  161. If we don't have a new code fragment, we return true if we already have a
  162. valid pipeline.
  163. If we do have a new code fragment we embed it in our template code and then
  164. compile it.
  165. .. warning::
  166. The code shown here compiles our new code in runtime.
  167. This is great for prototyping as we can immediately see the effect
  168. of the changed shader.
  169. This prevents precompiling and caching this shader which may be an issues
  170. on some platforms such as consoles.
  171. Note that the demo project comes with an alternative example where
  172. a ``glsl`` file contains the entire compute shader and this is used.
  173. Godot is able to precompile and cache the shader with this approach.
  174. Finally we need to implement our effect callback, the rendering engine will call
  175. this at the right stage of rendering.
  176. .. code-block:: gdscript
  177. # Called by the rendering thread every frame.
  178. func _render_callback(p_effect_callback_type, p_render_data):
  179. if rd and p_effect_callback_type == EFFECT_CALLBACK_TYPE_POST_TRANSPARENT and _check_shader():
  180. # Get our render scene buffers object, this gives us access to our render buffers.
  181. # Note that implementation differs per renderer hence the need for the cast.
  182. var render_scene_buffers : RenderSceneBuffersRD = p_render_data.get_render_scene_buffers()
  183. if render_scene_buffers:
  184. # Get our render size, this is the 3D render resolution!
  185. var size = render_scene_buffers.get_internal_size()
  186. if size.x == 0 and size.y == 0:
  187. return
  188. # We can use a compute shader here
  189. var x_groups = (size.x - 1) / 8 + 1
  190. var y_groups = (size.y - 1) / 8 + 1
  191. var z_groups = 1
  192. # Push constant
  193. var push_constant : PackedFloat32Array = PackedFloat32Array()
  194. push_constant.push_back(size.x)
  195. push_constant.push_back(size.y)
  196. push_constant.push_back(0.0)
  197. push_constant.push_back(0.0)
  198. # Loop through views just in case we're doing stereo rendering. No extra cost if this is mono.
  199. var view_count = render_scene_buffers.get_view_count()
  200. for view in range(view_count):
  201. # Get the RID for our color image, we will be reading from and writing to it.
  202. var input_image = render_scene_buffers.get_color_layer(view)
  203. # Create a uniform set, this will be cached, the cache will be cleared if our viewports configuration is changed.
  204. var uniform : RDUniform = RDUniform.new()
  205. uniform.uniform_type = RenderingDevice.UNIFORM_TYPE_IMAGE
  206. uniform.binding = 0
  207. uniform.add_id(input_image)
  208. var uniform_set = UniformSetCacheRD.get_cache(shader, 0, [ uniform ])
  209. # Run our compute shader.
  210. var compute_list := rd.compute_list_begin()
  211. rd.compute_list_bind_compute_pipeline(compute_list, pipeline)
  212. rd.compute_list_bind_uniform_set(compute_list, uniform_set, 0)
  213. rd.compute_list_set_push_constant(compute_list, push_constant.to_byte_array(), push_constant.size() * 4)
  214. rd.compute_list_dispatch(compute_list, x_groups, y_groups, z_groups)
  215. rd.compute_list_end()
  216. At the start of this method we check if we have a rendering device,
  217. if our callback type is the correct one, and check if we have our shader.
  218. .. note::
  219. The check for the effect type is only a safety mechanism.
  220. We've set this in our ``_init`` function, however it is possible
  221. for the user to change this in the UI.
  222. Our ``p_render_data`` parameter gives us access to an object that holds
  223. data specific to the frame we're currently rendering. We're currently only
  224. interested in our render scene buffers, which provide us access to all the
  225. internal buffers used by the rendering engine.
  226. Note that we cast this to :ref:`RenderSceneBuffersRD <class_RenderSceneBuffersRD>`
  227. to expose the full API to this data.
  228. Next we obtain our ``internal size`` which is the resolution of our 3D render
  229. buffers before they are upscaled (if applicable), upscaling happens after our
  230. post processes have run.
  231. From our internal size we calculate our group size, see our local size in our
  232. template shader.
  233. .. UPDATE: Not supported yet. When structs are supported here, update this
  234. .. paragraph.
  235. We also populate our push constant so our shader knows our size.
  236. Godot does not support structs here **yet** so we use a
  237. ``PackedFloat32Array`` to store this data into. Note that we have
  238. to pad this array with a 16 byte alignment. In other words, the
  239. length of our array needs to be a multiple of 4.
  240. Now we loop through our views, this is in case we're using multiview rendering
  241. which is applicable for stereo rendering (XR). In most cases we will only have
  242. one view.
  243. .. note::
  244. There is no performance benefit to use multiview for post processing
  245. here, handling the views separately like this will still enable the GPU
  246. to use parallelism if beneficial.
  247. Next we obtain the color buffer for this view. This is the buffer into which
  248. our 3D scene has been rendered.
  249. We then prepare a uniform set so we can communicate the color buffer to our
  250. shader.
  251. Note the use of our :ref:`UniformSetCacheRD <class_UniformSetCacheRD>` cache
  252. which ensures we can check for our uniform set each frame.
  253. As our color buffer can change from frame to frame and our uniform cache
  254. will automatically clean up uniform sets when buffers are freed, this is
  255. the safe way to ensure we do not leak memory or use an outdated set.
  256. Finally we build our compute list by binding our pipeline,
  257. binding our uniform set, pushing our push constant data,
  258. and calling dispatch for our groups.
  259. With our compositor effect completed, we now need to add it to our compositor.
  260. On our compositor we expand the compositor effects property
  261. and press ``Add Element``.
  262. Now we can add our compositor effect:
  263. .. image:: img/add_compositor_effect.webp
  264. After selecting our ``PostProcessShader`` we need to set our user shader code:
  265. .. code-block:: glsl
  266. float gray = color.r * 0.2125 + color.g * 0.7154 + color.b * 0.0721;
  267. color.rgb = vec3(gray);
  268. With that all done, our output is in grayscale.
  269. .. image:: img/post_process_shader.webp
  270. .. note::
  271. For a more advanced example of post effects, check out the
  272. `Radial blur based sky rays <https://github.com/BastiaanOlij/RERadialSunRays>`_
  273. example project created by Bastiaan Olij.