Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion build_manual.bat
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ docfx\docfx.exe build
xcopy /Y favicon.ico _site
xcopy /Y logo.svg _site
xcopy /Y logo.png _site

pause
echo Done!
67 changes: 67 additions & 0 deletions manual/graphics/shaders/compute-shader.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Compute Shader

Compute shaders are GPU programs that don't use classical GPU pipeline such as vertex transformations,fragment shading or MSAA.<br>
Dispatch submits GPU work; it does not wait for completion. Asynchronous compute on a separate GPU queue is a different feature and is not implied by using a compute shader.<br>
They can be used for massively parallel computational algorithms, or to accelerate parts of game rendering.<br>
Compute shaders don't need vertex/index buffers and don't write to output render target directly but instead can read and write to arbitrary buffers and textures provided by the user.


## About the Ways to run compute shaders
compute shaders can be run in multiple ways in Flax

| using | usage |
|--------------------------|--------------------------------------------------------------------------------------------------------------------------------|
| Post processing effect | running effects with can't be done with normal full screen shader's |
| Rendering task | submitting compute from an enabled render task callback, with explicit task ordering |
| main GPUContext | the context used to record GPU commands; use it from an engine rendering callback, not an arbitrary worker |

> [!IMPORTANT]
> Use the GPUContext supplied to a rendering callback. Do not move main-context commands to Task.Run. Dispatch returning does not mean the GPU has finished.

## Create Compute new shader source

First, folders in **Source** and **Content** named **Shaders**<br>

![New Shader Folders](media/ShaderFolders.png)

Then go to **Source/Shaders** Folder and *right-click* in Content window shaders source folder **New -> Source Shader**.<br>

![New Shader Source](media/CreateMyComputeShader.png)

and name it for example. `MyComputeShader.shader`.

If you're working with Visual Studio then use **File -> Generate project file** option to ensure new file was added to VS project.<br>
Then you can **double-click** to open shader in code editor.

you should see the shader under `Game/Shaders/MyComputeShader.shader`

![New Shader Source](media/NewShaderSourceCode.png)

By default flax new shader source generates code for Fullscreen Shader
we need to change it

```hlsl
#include "./Flax/Common.hlsl"

META_CB_BEGIN(0, Data)
float4 Color;
META_CB_END

META_CS(true, FEATURE_LEVEL_SM5)
[numthreads(1, 1, 1)]
void CS_Main(uint3 dispatchThreadID : SV_DispatchThreadID, uint3 groupID : SV_GroupID, uint3 groupThreadID : SV_GroupThreadID)
{

}
```
### About the parameters
*what is the SV_DispatchThreadID,SV_GroupID,SV_GroupThreadID ?*<br>
information about the parameters can be found in microsoft documentation<br>
1. [SV_GroupID](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-groupid)
2. [SV_GroupThreadID](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-groupthreadid)
3. [SV_DispatchThreadID](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-dispatchthreadid)


# API's
* [Low Level API](compute/ll-api.md)
* [High Level API](compute/hl-api.md)
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Main GPU context

The main GPUContext records commands for the engine's rendering work. It is not a separate execution mode that waits for each shader to finish.

Use the context supplied to a [render task](Running-compute-with-Render-Task.md) or [post-processing callback](Running-compute-with-Post-Proccesing-efect.md). Merely obtaining the main context does not make it safe to use from an arbitrary update callback or worker thread.

`Dispatch` returning means commands were recorded/submitted through the backend; it does not mean CPU-readable results are ready. Mapping or downloading data may wait. Keep GPU command submission in the rendering callback and use the documented readback path for CPU results.
Original file line number Diff line number Diff line change
@@ -1,25 +1,11 @@
# Custom Compute Shader
## Running compute with in Post Proccesing efect

In this tutorial you will learn how to create and use a simple **blur effect** that will use a Compute Shader in two-pass to blur the input image.
This example requires compute shaders and draw-indirect support from GPU which might not be available on low-end GPUs.
Let's start with simple blur effect<br>

Compute shaders are GPU programs that don't use classical GPU pipeline such as vertex transformations, fragment shading or MSAA. They are fully configurable code that can run on GPU in async. They can be used for massively parallel computational algorithms, or to accelerate parts of game rendering. Compute shaders don't need vertex/index buffers and don't write to output render target directly but instead can read and write to arbitrary buffers and textures provided by the user.
In this example we use two functions: one will blur the input image horizontally (`CS_BlurH`), second one will perform a vertical blur (`CS_BlurV`). The blur will use a configurable radius (in range 0-10) and blending intensity.

## 1. Create new shader

Firstly, create empty file in folder **Source/Shaders** and name it in a proper way, eg. `BlurComputeShader.shader`. You can do it manually or use Editor and *right-click* in Content window shaders source folder **New -> Shader**.

![New Shader Source](media/new-shader-source.png)

If you're working with Visual Studio then use **File -> Generate project file** option to ensure new file was added to VS project. Then you can **double-click** to open shader in code editor.

![Editing Shader Source](media/shader-editing.png)

## 2. Writing compute shader

Now, let's write the compute shader. In this example we use two functions: one will blur the input image horizotnally (`CS_BlurH`), second one will perform a vertical blur (`CS_BlurV`). The blur will use a configurable radius (in range 0-10) and blending intensity.

Here is an example code used in this tutorial. Follow code comments to better understand how it works.
> [!NOTE]
> Follow code comments to better understand how it works.

```hlsl
#include "./Flax/Common.hlsl"
Expand Down Expand Up @@ -51,7 +37,7 @@ void CS_BlurH(uint3 groupID : SV_GroupID, uint3 groupThreadID : SV_GroupThreadID
{
// These positions are relative to the "grid", AKA the horizontal group of pixels that this thread group is writing to
const int2 gridStartXY = groupID.xy * BLUR_GRID_SIZE;
const int2 gridXY = groupThreadID.xy - BLUR_APRON_SIZE;
const int2 gridXY = int2(groupThreadID.xy) - BLUR_APRON_SIZE;

// These positions are relative to the pixel coordinates
const int sampleX = gridStartXY.x + gridXY.x;
Expand Down Expand Up @@ -104,7 +90,7 @@ void CS_BlurV(uint3 groupID : SV_GroupID, uint3 groupThreadID : SV_GroupThreadID
{
// These positions are relative to the "grid", AKA the horizontal group of pixels that this thread group is writing to
const int2 gridStartXY = groupID.xy * BLUR_GRID_SIZE;
const int2 gridXY = groupThreadID.xy - BLUR_APRON_SIZE;
const int2 gridXY = int2(groupThreadID.xy) - BLUR_APRON_SIZE;

// These positions are relative to the pixel coordinates
const int sampleX = groupID.x;
Expand Down Expand Up @@ -152,11 +138,11 @@ void CS_BlurV(uint3 groupID : SV_GroupID, uint3 groupThreadID : SV_GroupThreadID

```

## 3. Dispatching compute
## Dispatching compute

Next step is to write a script that will invoke the compute shader execution on a GPU. To do so we will use a C# script that implements **PostProcessEffect** class which is used to inject custom rendering code into the in-built graphics pipeline. You can also override the *Order* and *Location* properties to have even more control over rendering.

Create C# script and add it to the any actor on the scene. You can use [this tutorial](../../scripting/new-script.md) to learn how to do it. Then, write the following code:
Create C# script and add it to the any actor on the scene. You can use [this tutorial](../../../scripting/new-script.md) to learn how to do it. Then, write the following code:

```cs
using System;
Expand All @@ -183,6 +169,7 @@ public class BlurComputeShader : PostProcessEffect
public float BlurRadius = 10.0f;

private bool _isComputeSupported;
private MainRenderTask _task;

public Shader Shader;

Expand All @@ -191,13 +178,15 @@ public class BlurComputeShader : PostProcessEffect
_isComputeSupported = GPUDevice.Instance.Limits.HasCompute;

// Register postFx to game view
MainRenderTask.Instance.AddCustomPostFx(this);
_task = MainRenderTask.Instance;
_task?.AddCustomPostFx(this);
}

public override void OnDisable()
{
// Remember to unregister from drawing
MainRenderTask.Instance?.RemoveCustomPostFx(this);
_task?.RemoveCustomPostFx(this);
_task = null;
}

public override bool CanRender()
Expand All @@ -215,8 +204,8 @@ public class BlurComputeShader : PostProcessEffect
{
var data = new Data
{
BlurStrength = BlurStrength,
BlurRadius = BlurRadius,
BlurStrength = Mathf.Clamp(BlurStrength, 0.0f, 1.0f),
BlurRadius = Mathf.Clamp(BlurRadius, 0.0f, 10.0f),
};
context.UpdateCB(cb, new IntPtr(&data));
}
Expand Down Expand Up @@ -265,8 +254,11 @@ public class BlurComputeShader : PostProcessEffect
}
```

## 4. See results
> [!NOTE]
> This blur sample still needs format-capability checks and exception-safe release of pooled targets before production use. Do not assume the input format supports UAV writes. The two dispatches are separate passes; binding resets are not CPU/GPU completion fences. The constant-buffer data occupies 16 bytes.

## See results

The final step is to **add script** to actor on scene and **assign Shader** property to the auto-imported shader source from `Content/Shaders`. When changing **Blur Radius** property from 0 to 10 you can see the effect in action real-time. In case of problems see *Output Log* window in Editor as it may contain any compilation errors (for both C# script and shader code).

![Compute Shader Blur](media/compute-blur.gif)
![Compute Shader Blur](../media/compute-blur.gif)
Loading
Loading