The Compositor

The compositor is a new feature in Godot 4 that allows control over the rendering pipeline when rendering the contents of a Viewport.

It can be configured on a WorldEnvironment node where it applies to all Viewports, or it can be configured on a Camera3D and apply only to the Viewport using that camera.

The Compositor resource is used to configure the compositor. To get started, simply create a new compositor on the appropriate node:

../../_images/new_compositor.webp

备注

The compositor is currently a feature that is only supported by the Mobile and Forward+ renderers.

Compositor effects

Compositor effects allow you to insert additional logic into the rendering pipeline at various stages. This is an advanced feature that requires a high level of understanding of the rendering pipeline to use to its best advantage.

As the core logic of the compositor effect is called from the rendering pipeline it is important to note that this logic will thus run within the thread on which rendering takes place. Care needs to be taken to ensure we don’t run into threading issues.

To illustrate how to use compositor effects we’ll create a simple post processing effect that allows you to write your own shader code and apply this full screen through a compute shader. You can find the finished demo project here.

We start by creating a new script called post_process_shader.gd. We’ll make this a tool script so we can see the compositor effect work in the editor. We need to extend our node from CompositorEffect. We must also give our script a class name.

  1. @tool
  2. extends CompositorEffect
  3. class_name PostProcessShader

Next we’re going to define a constant for our shader template code. This is the boilerplate code that makes our compute shader work.

  1. const template_shader : String = "#version 450
  2. // Invocations in the (x, y, z) dimension
  3. layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
  4. layout(rgba16f, set = 0, binding = 0) uniform image2D color_image;
  5. // Our push constant
  6. layout(push_constant, std430) uniform Params {
  7. vec2 raster_size;
  8. vec2 reserved;
  9. } params;
  10. // The code we want to execute in each invocation
  11. void main() {
  12. ivec2 uv = ivec2(gl_GlobalInvocationID.xy);
  13. ivec2 size = ivec2(params.raster_size);
  14. if (uv.x >= size.x || uv.y >= size.y) {
  15. return;
  16. }
  17. vec4 color = imageLoad(color_image, uv);
  18. #COMPUTE_CODE
  19. imageStore(color_image, uv, color);
  20. }"

For more information on how compute shaders work, please check Using compute shaders.

The important bit here is that for every pixel on our screen, our main function is executed and inside of this we load the current color value of our pixel, execute our user code, and write our modified color back to our color image.

#COMPUTE_CODE gets replaced by our user code.

In order to set our user code, we need an export variable. We’ll also define a few script variables we’ll be using:

  1. @export_multiline var shader_code : String = "":
  2. set(value):
  3. mutex.lock()
  4. shader_code = value
  5. shader_is_dirty = true
  6. mutex.unlock()
  7. var rd : RenderingDevice
  8. var shader : RID
  9. var pipeline : RID
  10. var mutex : Mutex = Mutex.new()
  11. var shader_is_dirty : bool = true

Note the use of a Mutex in our code. Most of our implementation gets called from the rendering engine and thus runs within our rendering thread.

We need to ensure that we set our new shader code, and mark our shader code as dirty, without our render thread accessing this data at the same time.

Next we initialize our effect.

  1. # Called when this resource is constructed.
  2. func _init():
  3. effect_callback_type = EFFECT_CALLBACK_TYPE_POST_TRANSPARENT
  4. rd = RenderingServer.get_rendering_device()

The main thing here is setting our effect_callback_type which tells the rendering engine at what stage of the render pipeline to call our code.

备注

Currently we only have access to the stages of the 3D rendering pipeline!

We also get a reference to our rendering device, which will come in very handy.

We also need to clean up after ourselves, for this we react to the NOTIFICATION_PREDELETE notification:

  1. # System notifications, we want to react on the notification that
  2. # alerts us we are about to be destroyed.
  3. func _notification(what):
  4. if what == NOTIFICATION_PREDELETE:
  5. if shader.is_valid():
  6. # Freeing our shader will also free any dependents such as the pipeline!
  7. RenderingServer.free_rid(shader)

Note that we do not use our mutex here even though we create our shader inside of our render thread. The methods on our rendering server are thread safe and free_rid will be postponed cleaning up the shader until after any frames currently being rendered are finished.

Also note that we are not freeing our pipeline. The rendering device does dependency tracking and as the pipeline is dependent on the shader, it will be automatically freed when the shader is destructed.

From this point onwards our code will run on the rendering thread.

Our next step is a helper function that will recompile the shader if the user code was changed.

  1. # Check if our shader has changed and needs to be recompiled.
  2. func _check_shader() -> bool:
  3. if not rd:
  4. return false
  5. var new_shader_code : String = ""
  6. # Check if our shader is dirty.
  7. mutex.lock()
  8. if shader_is_dirty:
  9. new_shader_code = shader_code
  10. shader_is_dirty = false
  11. mutex.unlock()
  12. # We don't have a (new) shader?
  13. if new_shader_code.is_empty():
  14. return pipeline.is_valid()
  15. # Apply template.
  16. new_shader_code = template_shader.replace("#COMPUTE_CODE", new_shader_code);
  17. # Out with the old.
  18. if shader.is_valid():
  19. rd.free_rid(shader)
  20. shader = RID()
  21. pipeline = RID()
  22. # In with the new.
  23. var shader_source : RDShaderSource = RDShaderSource.new()
  24. shader_source.language = RenderingDevice.SHADER_LANGUAGE_GLSL
  25. shader_source.source_compute = new_shader_code
  26. var shader_spirv : RDShaderSPIRV = rd.shader_compile_spirv_from_source(shader_source)
  27. if shader_spirv.compile_error_compute != "":
  28. push_error(shader_spirv.compile_error_compute)
  29. push_error("In: " + new_shader_code)
  30. return false
  31. shader = rd.shader_create_from_spirv(shader_spirv)
  32. if not shader.is_valid():
  33. return false
  34. pipeline = rd.compute_pipeline_create(shader)
  35. return pipeline.is_valid()

At the top of this method we again use our mutex to protect accessing our user shader code and our is dirty flag. We make a local copy of the user shader code if our user shader code is dirty.

If we don’t have a new code fragment, we return true if we already have a valid pipeline.

If we do have a new code fragment we embed it in our template code and then compile it.

警告

The code shown here compiles our new code in runtime. This is great for prototyping as we can immediately see the effect of the changed shader.

This prevents precompiling and caching this shader which may be an issues on some platforms such as consoles. Note that the demo project comes with an alternative example where a glsl file contains the entire compute shader and this is used. Godot is able to precompile and cache the shader with this approach.

Finally we need to implement our effect callback, the rendering engine will call this at the right stage of rendering.

  1. # Called by the rendering thread every frame.
  2. func _render_callback(p_effect_callback_type, p_render_data):
  3. if rd and p_effect_callback_type == EFFECT_CALLBACK_TYPE_POST_TRANSPARENT and _check_shader():
  4. # Get our render scene buffers object, this gives us access to our render buffers.
  5. # Note that implementation differs per renderer hence the need for the cast.
  6. var render_scene_buffers : RenderSceneBuffersRD = p_render_data.get_render_scene_buffers()
  7. if render_scene_buffers:
  8. # Get our render size, this is the 3D render resolution!
  9. var size = render_scene_buffers.get_internal_size()
  10. if size.x == 0 and size.y == 0:
  11. return
  12. # We can use a compute shader here
  13. var x_groups = (size.x - 1) / 8 + 1
  14. var y_groups = (size.y - 1) / 8 + 1
  15. var z_groups = 1
  16. # Push constant
  17. var push_constant : PackedFloat32Array = PackedFloat32Array()
  18. push_constant.push_back(size.x)
  19. push_constant.push_back(size.y)
  20. push_constant.push_back(0.0)
  21. push_constant.push_back(0.0)
  22. # Loop through views just in case we're doing stereo rendering. No extra cost if this is mono.
  23. var view_count = render_scene_buffers.get_view_count()
  24. for view in range(view_count):
  25. # Get the RID for our color image, we will be reading from and writing to it.
  26. var input_image = render_scene_buffers.get_color_layer(view)
  27. # Create a uniform set, this will be cached, the cache will be cleared if our viewports configuration is changed.
  28. var uniform : RDUniform = RDUniform.new()
  29. uniform.uniform_type = RenderingDevice.UNIFORM_TYPE_IMAGE
  30. uniform.binding = 0
  31. uniform.add_id(input_image)
  32. var uniform_set = UniformSetCacheRD.get_cache(shader, 0, [ uniform ])
  33. # Run our compute shader.
  34. var compute_list := rd.compute_list_begin()
  35. rd.compute_list_bind_compute_pipeline(compute_list, pipeline)
  36. rd.compute_list_bind_uniform_set(compute_list, uniform_set, 0)
  37. rd.compute_list_set_push_constant(compute_list, push_constant.to_byte_array(), push_constant.size() * 4)
  38. rd.compute_list_dispatch(compute_list, x_groups, y_groups, z_groups)
  39. rd.compute_list_end()

At the start of this method we check if we have a rendering device, if our callback type is the correct one, and check if we have our shader.

备注

The check for the effect type is only a safety mechanism. We’ve set this in our _init function, however it is possible for the user to change this in the UI.

Our p_render_data parameter gives us access to an object that holds data specific to the frame we’re currently rendering. We’re currently only interested in our render scene buffers, which provide us access to all the internal buffers used by the rendering engine. Note that we cast this to RenderSceneBuffersRD to expose the full API to this data.

Next we obtain our internal size which is the resolution of our 3D render buffers before they are upscaled (if applicable), upscaling happens after our post processes have run.

From our internal size we calculate our group size, see our local size in our template shader.

We also populate our push constant so our shader knows our size. Godot does not support structs here yet so we use a PackedFloat32Array to store this data into. Note that we have to pad this array with a 16 byte alignment. In other words, the length of our array needs to be a multiple of 4.

Now we loop through our views, this is in case we’re using multiview rendering which is applicable for stereo rendering (XR). In most cases we will only have one view.

备注

There is no performance benefit to use multiview for post processing here, handling the views separately like this will still enable the GPU to use parallelism if beneficial.

Next we obtain the color buffer for this view. This is the buffer into which our 3D scene has been rendered.

We then prepare a uniform set so we can communicate the color buffer to our shader.

Note the use of our UniformSetCacheRD cache which ensures we can check for our uniform set each frame. As our color buffer can change from frame to frame and our uniform cache will automatically clean up uniform sets when buffers are freed, this is the safe way to ensure we do not leak memory or use an outdated set.

Finally we build our compute list by binding our pipeline, binding our uniform set, pushing our push constant data, and calling dispatch for our groups.

With our compositor effect completed, we now need to add it to our compositor.

On our compositor we expand the compositor effects property and press Add Element.

Now we can add our compositor effect:

../../_images/add_compositor_effect.webp

After selecting our PostProcessShader we need to set our user shader code:

  1. float gray = color.r * 0.2125 + color.g * 0.7154 + color.b * 0.0721;
  2. color.rgb = vec3(gray);

With that all done, our output is in grayscale.

../../_images/post_process_shader.webp

备注

For a more advanced example of post effects, check out the Radial blur based sky rays example project created by Bastiaan Olij.