diff --git a/build_manual.bat b/build_manual.bat
index dd28d014..776fe72d 100644
--- a/build_manual.bat
+++ b/build_manual.bat
@@ -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!
diff --git a/manual/graphics/shaders/compute-shader.md b/manual/graphics/shaders/compute-shader.md
new file mode 100644
index 00000000..44d2697e
--- /dev/null
+++ b/manual/graphics/shaders/compute-shader.md
@@ -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.
+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.
+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.
+
+
+## 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**
+
+
+
+Then go to **Source/Shaders** Folder and *right-click* in Content window shaders source folder **New -> Source Shader**.
+
+
+
+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.
+Then you can **double-click** to open shader in code editor.
+
+you should see the shader under `Game/Shaders/MyComputeShader.shader`
+
+
+
+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 ?*
+information about the parameters can be found in microsoft documentation
+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)
diff --git a/manual/graphics/shaders/compute/Running-compute-with-MainContext.md b/manual/graphics/shaders/compute/Running-compute-with-MainContext.md
new file mode 100644
index 00000000..cadcc96b
--- /dev/null
+++ b/manual/graphics/shaders/compute/Running-compute-with-MainContext.md
@@ -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.
diff --git a/manual/graphics/shaders/custom-compute-shader.md b/manual/graphics/shaders/compute/Running-compute-with-Post-Proccesing-efect.md
similarity index 78%
rename from manual/graphics/shaders/custom-compute-shader.md
rename to manual/graphics/shaders/compute/Running-compute-with-Post-Proccesing-efect.md
index e859501b..5f76244d 100644
--- a/manual/graphics/shaders/custom-compute-shader.md
+++ b/manual/graphics/shaders/compute/Running-compute-with-Post-Proccesing-efect.md
@@ -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
-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**.
-
-
-
-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.
-
-
-
-## 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"
@@ -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;
@@ -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;
@@ -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;
@@ -183,6 +169,7 @@ public class BlurComputeShader : PostProcessEffect
public float BlurRadius = 10.0f;
private bool _isComputeSupported;
+ private MainRenderTask _task;
public Shader Shader;
@@ -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()
@@ -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));
}
@@ -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).
-
+
\ No newline at end of file
diff --git a/manual/graphics/shaders/compute/Running-compute-with-Render-Task.md b/manual/graphics/shaders/compute/Running-compute-with-Render-Task.md
new file mode 100644
index 00000000..57452dcf
--- /dev/null
+++ b/manual/graphics/shaders/compute/Running-compute-with-Render-Task.md
@@ -0,0 +1,753 @@
+# Running compute with Render Task
+
+As introduced in [Compute Shader](../compute-shader.md), a render task lets us submit compute work from the engine render loop. Here we will use one to generate terrain from a height map, read the results back, and build a visible mesh and a physics collider.
+
+## About render task
+A RenderTask provides Begin, Render and End callbacks in the render loop. We will use them in this order:
+
+1. **Begin:** update constants and bind the height map and output buffers.
+2. **Render:** pick the compute program and dispatch it.
+3. **End:** clear bindings, read the results and update the mesh.
+
+These callbacks describe CPU-side command submission. End does not mean the GPU has finished; mapping the readback buffers below can wait for it.
+
+### Creating Render Task
+
+We will build one `MyComputeShaderWithRenderTask` class in stages. The initial code creates and subscribes the task; later sections add its callbacks and helper methods. Blocks containing `...` show additions to the same class, not separate scripts. The class is complete only after all stages have been added.
+
+## Compute Example
+Let’s roll the wheel of fortune… a texture example? We can do more than that :D We will generate a grid mesh from a height map, then use the generated data for rendering and collision.
+
+The shader uses a **constant buffer** for grid dimensions, a **`Texture2D`** for heights, **`RWStructuredBuffer`** outputs for positions and normals, and an **`RWBuffer`** for triangle indices.
+
+> [!IMPORTANT]
+> Before we start i need to clarify something
+> we will do something stupid in this example it is not optimal
+> reading large amount data back to CPU is expensive
+
+> [!IMPORTANT]
+> we will not get in to resizing the buffers and the data
+> the buffer size will be constant
+
+Choose a grayscale height map. You can paint your own or use either image below. Start with the 32×32 image to check the setup before trying the island.
+
+### Some random island (size of 1872x1872)
+
+### small texture (size of 32x32)
+
+
+
+## Before we start this is IMPORTANT !!
+This example generates a dense mesh: **one vertex per image pixel**. The island example was tested on:
+
+- AMD Ryzen 7 8700G
+- NVIDIA GeForce RTX 3050, 8 GB VRAM
+- 32 GB RAM
+
+Rendering the generated mesh dropped performance from roughly 400 FPS to 60 FPS on that setup.
+Start with a small texture, especially on slower hardware. it is not a “1 way to crash PC” doc :|
+
+A 32-by-32 group contains 1024 threads.
+Verify device limits, or change both shader group dimensions and C# dispatch division.
+The example readback below maps staging buffers immediately after copying; this can stall CPU submission while the GPU completes.
+It is a synchronous correctness example, not streaming or asynchronous readback.
+
+
+This example reads the generated mesh back to the CPU and updates a StaticModel and collision data, StaticModel’s use normal rendering path,
+including occlusion culling and shadow rendering.
+Direct GPU drawing does not automatically participate in those systems, so we leave that integration outside this example.
+
+This example follows that Model/StaticModel path throughout. Direct custom drawing is a separate topic; see [Custom Geometry Drawing](../custom-geometry-drawing.md).
+
+Mesh size is limited by available memory, buffer sizes and index format.
+A dense height map grows quickly: width × height vertices and (width − 1) × (height − 1) × 6 indices.
+This example uses 32-bit indices
+
+
+## Let’s do it slowly so the setup makes sense
+Because Flax doesn’t have a [high-level compute API](../compute/hl-api.md) yet, brace yourself, there’s a fair bit of code ahead.
+
+Each output needs a buffer pair: one writable GPU buffer and one CPU-readable staging buffer.
+We need three pairs, for positions, normals and triangle indices.
+The staging buffers let us read the results without trying to map the shader outputs directly.
+
+The two helpers below belong inside the script class. `CreateBufferPair` returns true on success; the underlying `GPUBuffer.Init` uses the opposite convention, returning true on failure. `ReleaseBuffer` destroys an owned buffer and clears its reference.
+```csharp
+...
+public class MyComputeShaderWithRenderTask : Script
+{
+ ...
+
+ private bool CreateBufferPair(
+ GPUBufferDescription gpuDescription,
+ out GPUBuffer gpuBuffer,
+ out GPUBuffer readbackBuffer)
+ {
+ gpuBuffer = new GPUBuffer();
+ readbackBuffer = null;
+
+ if (gpuBuffer.Init(ref gpuDescription))
+ {
+ Debug.LogError("Failed to create GPU output buffer.");
+ FlaxEngine.Object.Destroy(gpuBuffer);
+ gpuBuffer = null;
+ return false;
+ }
+
+ // The helper configures a CPU-readable staging buffer.
+ GPUBufferDescription stagingDescription =
+ gpuDescription.ToStagingReadback();
+
+ // Do not assign InitData to a staging readback buffer.
+ readbackBuffer = new GPUBuffer();
+
+ if (readbackBuffer.Init(ref stagingDescription))
+ {
+ Debug.LogError("Failed to create staging readback buffer.");
+
+ FlaxEngine.Object.Destroy(readbackBuffer);
+ readbackBuffer = null;
+ FlaxEngine.Object.Destroy(gpuBuffer);
+ gpuBuffer = null;
+ return false;
+ }
+
+ return true;
+ }
+ private void ReleaseBuffers()
+ {
+ ReleaseBuffer(ref TrianglesReadback);
+ ReleaseBuffer(ref TrianglesGPUBuffer);
+ ReleaseBuffer(ref VertexesReadback);
+ ReleaseBuffer(ref VertexesGPUBuffer);
+ ReleaseBuffer(ref NormalsReadback);
+ ReleaseBuffer(ref NormalsGPUBuffer);
+ }
+
+ private static void ReleaseBuffer(ref GPUBuffer buffer)
+ {
+ if (buffer == null)
+ return;
+
+ FlaxEngine.Object.Destroy(buffer);
+ buffer = null;
+ }
+
+ ...
+}
+```
+
+
+### Creation and destruction of buffers
+
+GPU buffers must be released when they are no longer needed, when their owner is destroyed, or when they are replaced during resizing.
+Make **sure** pending GPU work has finished using them before releasing them.
+
+Before we dig into the code, check whether the active graphics device supports compute shaders. Some devices or graphics backends don’t support them, and servers may run without a GPU at all.
+
+Check compute support before creating resources or dispatching work. If it is unavailable, disable the feature, use a CPU fallback, or stop startup with a clear error if compute is required. Avoid forcing the whole application to close for an optional feature.
+
+```csharp
+if (GPUDevice.Instance == null || !GPUDevice.Instance.Limits.HasCompute)
+{
+ Debug.LogError("This feature requires GPU compute support.");
+ return; // Skip initialization, or select a CPU fallback here.
+}
+```
+
+#### Initial C# code
+
+Start with the fields, initialization and destruction code below, and add the buffer helpers above inside the class. `OnBegin`, `OnRender` and `OnEnd` are supplied in the following chapters.
+
+The input assets must already be loaded when this example starts.
+The script reports an error rather than waiting for them. Use the same world transform for the script’s host actor and the assigned StaticModel: the generated collider is a child of the host, while the visible mesh belongs to StaticModel.
+
+```csharp
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using FlaxEngine;
+
+public class MyComputeShaderWithRenderTask : Script
+{
+ public Shader shader;
+ public Texture HeightMap;
+ public StaticModel staticModel;
+ private MeshCollider collider;
+ private RenderTask MyComputeRenderTask;
+
+ private Int2 Size;
+
+ private GPUBuffer TrianglesGPUBuffer;
+ private GPUBuffer TrianglesReadback;
+
+ private GPUBuffer VertexesGPUBuffer;
+ private GPUBuffer VertexesReadback;
+
+ private GPUBuffer NormalsGPUBuffer;
+ private GPUBuffer NormalsReadback;
+
+ Float3[] VertexesBuffer;
+ Float3[] NormalsBuffer;
+ int[] TrianglesBuffer;
+
+ public bool computeDispatched;
+ public bool computeCompleted;
+ public bool initialized;
+
+ public bool RunCompute
+ {
+ get => MyComputeRenderTask != null && MyComputeRenderTask.Enabled;
+ set
+ {
+ if (value && MyComputeRenderTask != null && computeCompleted)
+ {
+ computeDispatched = false;
+ computeCompleted = false;
+ MyComputeRenderTask.Enabled = true;
+ }
+ }
+ }
+
+ public override void OnStart()
+ {
+ if (GPUDevice.Instance == null || !GPUDevice.Instance.Limits.HasCompute)
+ {
+ Debug.LogError("GPU compute shaders are not supported.");
+ return;
+ }
+
+ if (shader == null || HeightMap == null || staticModel == null)
+ {
+ Debug.LogError(
+ "Assign Shader, HeightMap, and StaticModel in the Inspector.");
+ return;
+ }
+
+ if (!shader.IsLoaded || !HeightMap.IsLoaded)
+ {
+ Debug.LogError("Wait for Shader and HeightMap to load before starting this example.");
+ return;
+ }
+
+ if (HeightMap.Width < 2 || HeightMap.Height < 2)
+ {
+ Debug.LogError("Heightmap must be at least 2x2 pixels.");
+ return;
+ }
+
+ // Size represents the number of grid cells, not vertices.
+ Size = new Int2(HeightMap.Width - 1, HeightMap.Height - 1);
+
+ int vertexCount = checked((Size.X + 1) * (Size.Y + 1));
+ int triangleIndexCount = checked(Size.X * Size.Y * 6);
+
+ VertexesBuffer = new Float3[vertexCount];
+ NormalsBuffer = new Float3[vertexCount];
+ TrianglesBuffer = new int[triangleIndexCount];
+
+ // Create a virtual model for the generated mesh.
+ Model model = Content.CreateVirtualAsset();
+ // create collider
+ collider = Actor.AddChild();
+ collider.CollisionData = Content.CreateVirtualAsset();
+ model.SetupLODs([1]);
+ staticModel.Model = model;
+
+ uint vertexStride = (uint)Unsafe.SizeOf();
+
+ GPUBufferDescription vertexDescription = new GPUBufferDescription
+ {
+ Format = PixelFormat.Unknown,
+ Usage = GPUResourceUsage.Default,
+ Flags = GPUBufferFlags.UnorderedAccess |
+ GPUBufferFlags.Structured,
+ Stride = vertexStride,
+ Size = (uint)vertexCount * vertexStride,
+ InitData = IntPtr.Zero
+ };
+
+ GPUBufferDescription triangleDescription = new GPUBufferDescription
+ {
+ Format = PixelFormat.R32_SInt,
+ Usage = GPUResourceUsage.Default,
+ Flags = GPUBufferFlags.UnorderedAccess,
+ Stride = sizeof(int),
+ Size = (uint)triangleIndexCount * sizeof(int),
+ InitData = IntPtr.Zero
+ };
+
+ if (!CreateBufferPair(
+ vertexDescription,
+ out VertexesGPUBuffer,
+ out VertexesReadback))
+ {
+ ReleaseBuffers();
+ return;
+ }
+
+ if (!CreateBufferPair(
+ vertexDescription,
+ out NormalsGPUBuffer,
+ out NormalsReadback))
+ {
+ ReleaseBuffers();
+ return;
+ }
+
+ if (!CreateBufferPair(
+ triangleDescription,
+ out TrianglesGPUBuffer,
+ out TrianglesReadback))
+ {
+ ReleaseBuffers();
+ return;
+ }
+
+ MyComputeRenderTask = new RenderTask();
+ MyComputeRenderTask.Begin += OnBegin;
+ MyComputeRenderTask.Render += OnRender;
+ MyComputeRenderTask.End += OnEnd;
+
+ initialized = true;
+
+ Debug.Log(
+ $"Terrain compute initialized: {HeightMap.Width}x{HeightMap.Height}, " +
+ $"{vertexCount} vertices, {triangleIndexCount / 3} triangles.");
+ }
+
+ ... // Buffer helpers and render callbacks are shown in their own sections.
+
+ public override void OnDestroy()
+ {
+ if (MyComputeRenderTask != null)
+ {
+ MyComputeRenderTask.Begin -= OnBegin;
+ MyComputeRenderTask.Render -= OnRender;
+ MyComputeRenderTask.End -= OnEnd;
+
+ DestroyNow(MyComputeRenderTask);
+ MyComputeRenderTask = null;
+ }
+
+ ReleaseBuffer(ref TrianglesReadback);
+ ReleaseBuffer(ref TrianglesGPUBuffer);
+
+ ReleaseBuffer(ref VertexesReadback);
+ ReleaseBuffer(ref VertexesGPUBuffer);
+
+ ReleaseBuffer(ref NormalsReadback);
+ ReleaseBuffer(ref NormalsGPUBuffer);
+ initialized = false;
+ }
+}
+```
+
+The shader must provide CS_Main with `[numthreads(32, 32, 1)]`, a 16-byte constant buffer at b0 beginning with `int2 Size`, the height-map SRV at t0, and output UAVs at u0 (R32_SInt indices), u1 (structured float3 positions) and u2 (structured float3 normals).
+Size counts cells; there are width-by-height vertices and `(width-1)*(height-1)*6` indices. Extra threads must bounds-check before any resource access.
+
+#### Full shader
+
+Save this as a shader source under `Source/Shaders`.
+Each thread writes one vertex and its normal, plus six indices when there is a grid cell at that position.
+The height correction blends the centre sample with its four diagonal neighbor's, normals are calculated from the same corrected surface.
+No thread reads another thread’s output, so this kernel needs no group barrier.
+
+```hlsl
+#include "./Flax/Common.hlsl"
+
+META_CB_BEGIN(0, Data)
+int2 Size; // Cell count: height-map dimensions minus one
+META_CB_END
+
+Texture2D HeightMap : register(t0);
+RWBuffer triangles : register(u0);
+RWStructuredBuffer vertexes : register(u1);
+RWStructuredBuffer normals : register(u2);
+
+float GetHeight(int2 pixel)
+{
+ pixel = clamp(pixel, int2(0, 0), Size);
+ return HeightMap.Load(int3(pixel, 0)).r * 255.0;
+}
+
+float GetCorrectedHeight(int2 pixel)
+{
+ // A B C
+ // D E F
+ // G H I
+ float a = GetHeight(pixel + int2(-1, -1));
+ float c = GetHeight(pixel + int2( 1, -1));
+ float g = GetHeight(pixel + int2(-1, 1));
+ float i = GetHeight(pixel + int2( 1, 1));
+ float e = GetHeight(pixel);
+
+ float surfaceHeight = (a + c + g + i) * 0.25;
+ return lerp(e, surfaceHeight, 0.75);
+}
+
+float3 GetPosition(int2 pixel)
+{
+ return float3(pixel.x, GetCorrectedHeight(pixel), pixel.y);
+}
+
+META_CS(true, FEATURE_LEVEL_SM5)
+[numthreads(32, 32, 1)]
+void CS_Main(uint3 dispatchThreadID : SV_DispatchThreadID)
+{
+ int2 pixel = int2(dispatchThreadID.xy);
+ if (any(pixel > Size))
+ return;
+
+ int width = Size.x + 1;
+ int vertexID = pixel.y * width + pixel.x;
+
+ vertexes[vertexID] = GetPosition(pixel);
+
+ // Derive normals from the same corrected height surface.
+ // No reads from other threads' output buffers are needed.
+ int2 left = int2(max(pixel.x - 1, 0), pixel.y);
+ int2 right = int2(min(pixel.x + 1, Size.x), pixel.y);
+ int2 back = int2(pixel.x, max(pixel.y - 1, 0));
+ int2 front = int2(pixel.x, min(pixel.y + 1, Size.y));
+
+ float3 tangentX = GetPosition(right) - GetPosition(left);
+ float3 tangentZ = GetPosition(front) - GetPosition(back);
+
+ normals[vertexID] = normalize(cross(tangentZ, tangentX));
+
+ // Boundary vertices have no cell starting at their position.
+ if (any(pixel >= Size))
+ return;
+
+ int triangleID = (pixel.y * Size.x + pixel.x) * 6;
+
+ int topLeft = vertexID;
+ int topRight = vertexID + 1;
+ int bottomLeft = vertexID + width;
+ int bottomRight = vertexID + width + 1;
+
+ triangles[triangleID + 0] = topLeft;
+ triangles[triangleID + 1] = bottomLeft;
+ triangles[triangleID + 2] = topRight;
+
+ triangles[triangleID + 3] = topRight;
+ triangles[triangleID + 4] = bottomLeft;
+ triangles[triangleID + 5] = bottomRight;
+}
+```
+
+Once the shader is imported, assign these script fields:
+
+- **shader:** the imported Shader asset.
+- **staticModel:** the StaticModel actor that will display the generated model.
+- **HeightMap:** the height-map Texture asset.
+
+#### Important
+Import the height map as linear data, without sRGB conversion or lossy compression.
+Otherwise the sampled heights can have stepping artifacts.
+
+Import settings:
+
+
+
+Colour-texture defaults such as sRGB conversion and compression are not desired for height data.
+
+### Task control
+
+A render task is an owned engine object, not a callback that disappears when the script is disabled. Add these methods to pause it when the script is disabled and resume unfinished work when enabled. `OnDestroy` in the initial code unsubscribes and destroys the task. Setting `RunCompute` to true requests another run after successful completion.
+
+```csharp
+...
+public class MyComputeShaderWithRenderTask : Script
+{
+ ...
+ public override void OnEnable()
+ {
+ if (MyComputeRenderTask != null)
+ MyComputeRenderTask.Enabled = !computeCompleted;
+ }
+
+ public override void OnDisable()
+ {
+ if (MyComputeRenderTask != null)
+ MyComputeRenderTask.Enabled = false;
+ }
+ ...
+}
+```
+
+### Shader Resources and Unordered Access buffers bindings
+
+`context.BindSR` binds a shader resource view (SRV) to a `t` register. HLSL resources such as `Texture2D`, `Buffer`, `StructuredBuffer` and `ByteAddressBuffer` use these bindings.
+
+For example, `context.BindSR(0, resource.View())` supplies the resource declared at `register(t0)`.
+
+See Microsoft’s [HLSL resource binding documentation](https://learn.microsoft.com/en-us/windows/win32/direct3d12/resource-binding-in-hlsl).
+
+`context.BindUA` binds an unordered access view (UAV) to a `u` register.
+Writable HLSL resources such as `RWTexture2D`, `RWBuffer`, `RWStructuredBuffer` and `RWByteAddressBuffer` use these bindings.
+
+For example, `context.BindUA(0, resource.View())` supplies the resource declared at `register(u0)`.
+
+See Microsoft’s [HLSL resource binding documentation](https://learn.microsoft.com/en-us/windows/win32/direct3d12/resource-binding-in-hlsl).
+
+Here the height map is **t0**, triangle indices are **u0**, positions are **u1**, and normals are **u2**. `ComputeData` supplies **b0**.
+Its 16-byte storage matches constant-buffer alignment, the unused bytes are initialized to zero.
+The stack-local data remains valid for `UpdateCB` to copy during the call.
+
+Add this structure and the Begin callback inside the class:
+
+```csharp
+...
+public class MyComputeShaderWithRenderTask : Script
+{
+ ...
+ [StructLayout(LayoutKind.Sequential, Size = 16)]
+ private struct ComputeData
+ {
+ public Int2 Size;
+ }
+
+ private unsafe void OnBegin(RenderTask task, GPUContext context)
+ {
+ if (computeCompleted)
+ return;
+ if (shader.GPU.GetCB(0) == IntPtr.Zero)
+ {
+ task.Enabled = false;
+ return;
+ }
+
+ // Bind the heightmap and output UAVs.
+ context.BindSR(0, HeightMap.Texture.View());
+
+ context.BindUA(0, TrianglesGPUBuffer.View());
+ context.BindUA(1, VertexesGPUBuffer.View());
+ context.BindUA(2, NormalsGPUBuffer.View());
+
+ // Update the shader's Size constant buffer.
+ IntPtr constantBuffer = shader.GPU.GetCB(0);
+
+ if (constantBuffer != IntPtr.Zero)
+ {
+ var data = new ComputeData { Size = Size };
+ context.UpdateCB(constantBuffer, (IntPtr)(&data));
+ }
+
+ context.BindCB(0, constantBuffer);
+ }
+ ...
+}
+```
+
+### Dispatch compute and program picker
+
+This example uses one `context.Dispatch` and one entry point, `CS_Main`. `GetCS` selects that program from the loaded shader, a zero result means it was not found.
+
+Dispatch dimensions count **thread groups**, not vertices.
+Dividing the texture dimensions by 32 and rounding up covers every vertex.
+The shader checks bounds for extra threads in the last groups.
+
+Dispatches can be chained, but dependent passes must run in order, with the required resource synchronization between writes and reads.
+Resetting bindings alone does not prove completion, the graphics backend must handle the necessary barriers.
+
+A larger terrain generator could use separate programs for:
+
+- Basic mesh generation.
+- Erosion.
+- Populating terrain based on slope.
+
+Here we only dispatch the first stage. Keep `32` in the C# group calculation synchronized with `[numthreads(32, 32, 1)]` in HLSL.
+
+```csharp
+...
+public class MyComputeShaderWithRenderTask : Script
+{
+ ...
+ private void OnRender(RenderTask task, GPUContext context)
+ {
+ if (computeDispatched || computeCompleted)
+ return;
+
+ IntPtr kernel = shader.GPU.GetCS("CS_Main");
+
+ if (kernel == IntPtr.Zero)
+ {
+ Debug.LogError("Compute kernel CS_Main was not found.");
+ task.Enabled = false;
+ return;
+ }
+
+ // The shader uses [numthreads(32, 32, 1)].
+ // Ceiling division covers dimensions not divisible by 32.
+ uint groupsX = (uint)((HeightMap.Width + 31) / 32);
+ uint groupsY = (uint)((HeightMap.Height + 31) / 32);
+
+ context.Dispatch(kernel, groupsX, groupsY, 1);
+
+ computeDispatched = true;
+
+ Debug.Log(
+ $"Terrain compute dispatched: {groupsX}x{groupsY} thread groups.");
+ }
+ ...
+}
+```
+
+### Reading results and clearing resource bindings
+
+Before copying the compute outputs, clear the unordered access, shader resource and constant-buffer bindings with `ResetUA()`, `ResetSR()` and `ResetCB()`. These calls clear binding state, they do not free the buffers or wait for GPU completion.
+
+`PullData` copies each GPU output into its CPU-readable staging buffer. It then maps the staging buffers, copies their contents into managed arrays and unmaps them. Always call `Unmap()` in a `finally` block after a successful map.
+
+> [!IMPORTANT]
+> Mapping staging buffers immediately after copying can block while the GPU finishes its work. This example uses synchronous readback for simplicity.
+
+Finally, `UpdateMesh` uploads the managed arrays into the Model’s mesh, and `CookCollision` builds triangle-mesh collision from those same positions and indices. Collision cooking is extra CPU work; this is not a GPU-only physics path. Once these steps finish, the render task is disabled so the example does not repeat the work every frame.
+
+Add `OnEnd` and `PullData` inside the same class. Together with the earlier sections, these complete the script.
+
+```csharp
+...
+public class MyComputeShaderWithRenderTask : Script
+{
+ ...
+
+ private void OnEnd(RenderTask task, GPUContext context)
+ {
+ context.ResetUA();
+ context.ResetSR();
+ context.ResetCB();
+ if (!computeDispatched || computeCompleted)
+ return;
+
+ if (!PullData(context))
+ {
+ Debug.LogError("Terrain compute readback failed.");
+ task.Enabled = false;
+ return;
+ }
+
+ computeCompleted = true;
+ task.Enabled = false;
+
+ Debug.Log("Terrain compute completed and mesh updated.");
+ }
+
+
+ private bool PullData(GPUContext context)
+ {
+ uint triangleBytes = checked((uint)TrianglesBuffer.Length * sizeof(int));
+ uint vertexBytes = checked((uint)VertexesBuffer.Length * (uint)Unsafe.SizeOf());
+ uint normalBytes = checked((uint)NormalsBuffer.Length * (uint)Unsafe.SizeOf());
+
+ // Copy all outputs using the callback's context.
+ context.CopyBuffer(
+ TrianglesReadback,
+ TrianglesGPUBuffer,
+ triangleBytes);
+
+ context.CopyBuffer(
+ VertexesReadback,
+ VertexesGPUBuffer,
+ vertexBytes);
+
+ context.CopyBuffer(
+ NormalsReadback,
+ NormalsGPUBuffer,
+ normalBytes);
+
+ // Read triangle indices.
+ IntPtr pointer = TrianglesReadback.Map(GPUResourceMapMode.Read);
+
+ if (pointer == IntPtr.Zero)
+ {
+ Debug.LogError("Failed to map triangle readback buffer.");
+ return false;
+ }
+
+ try
+ {
+ Marshal.Copy(
+ pointer,
+ TrianglesBuffer,
+ 0,
+ TrianglesBuffer.Length);
+ }
+ finally
+ {
+ TrianglesReadback.Unmap();
+ }
+
+ // Read vertex positions.
+ pointer = VertexesReadback.Map(GPUResourceMapMode.Read);
+
+ if (pointer == IntPtr.Zero)
+ {
+ Debug.LogError("Failed to map vertex readback buffer.");
+ return false;
+ }
+
+ try
+ {
+ byte[] bytes = new byte[checked((int)vertexBytes)];
+
+ Marshal.Copy(pointer, bytes, 0, bytes.Length);
+
+ MemoryMarshal.Cast(bytes)
+ .CopyTo(VertexesBuffer);
+ }
+ finally
+ {
+ VertexesReadback.Unmap();
+ }
+
+ // Read vertex normals.
+ pointer = NormalsReadback.Map(GPUResourceMapMode.Read);
+
+ if (pointer == IntPtr.Zero)
+ {
+ Debug.LogError("Failed to map normal readback buffer.");
+ return false;
+ }
+
+ try
+ {
+ byte[] bytes = new byte[checked((int)normalBytes)];
+
+ Marshal.Copy(pointer, bytes, 0, bytes.Length);
+
+ MemoryMarshal.Cast(bytes)
+ .CopyTo(NormalsBuffer);
+ }
+ finally
+ {
+ NormalsReadback.Unmap();
+ }
+
+ // Update the mesh using the CPU-side arrays.
+ staticModel.Model.LODs[0].Meshes[0].UpdateMesh(
+ VertexesBuffer,
+ TrianglesBuffer,
+ NormalsBuffer,
+ null);
+ collider.CollisionData.CookCollision(CollisionDataType.TriangleMesh, VertexesBuffer, TrianglesBuffer, ConvexMeshGenerationFlags.FastCook);
+
+ Debug.Log(
+ $"Readback successful: {VertexesBuffer.Length} vertices, " +
+ $"{TrianglesBuffer.Length / 3} triangles.");
+
+ return true;
+ }
+ ...
+}
+```
+
+The final result, shown in wireframe, physics debug view and shaded view:
+
+
+> [!NOTE]
+> Generated results can also be saved as assets and streamed instead of regenerated at runtime. Asset saving is outside this tutorial’s scope.
+
+Happy shading have fun, and remember sky is the limit (and VRAM :D).
diff --git a/manual/graphics/shaders/compute/hl-api.md b/manual/graphics/shaders/compute/hl-api.md
new file mode 100644
index 00000000..5476a8a7
--- /dev/null
+++ b/manual/graphics/shaders/compute/hl-api.md
@@ -0,0 +1 @@
+The High Level API in under very slow development and planing :| available soonTM
\ No newline at end of file
diff --git a/manual/graphics/shaders/compute/ll-api.md b/manual/graphics/shaders/compute/ll-api.md
new file mode 100644
index 00000000..f11448c5
--- /dev/null
+++ b/manual/graphics/shaders/compute/ll-api.md
@@ -0,0 +1,109 @@
+# Low-level compute resources
+
+Compute shaders read and write GPU resources through views. Resource creation, command submission and CPU readback are separate operations.
+
+## Memory and ownership
+
+An unmanaged pointer into a managed array must remain pinned for the entire native call that reads it. Keeping the array in a field or keeping its length unchanged does not pin it. Never keep an `Unsafe.AsPointer` result across calls without a matching lifetime and pinning contract.
+
+`InitData` is consumed during buffer initialization; it is not a permanent association with the array. Later CPU changes require another upload. Buffer sizes and strides are byte counts.
+
+Keep resources alive while queued GPU work or downloads use them. Destroy GPU objects you create when their work is finished. `ReleaseGPU()` releases their GPU allocation but does not destroy the owning engine object. Do not destroy borrowed assets or a texture owned by an assigned asset. Return pooled targets with `RenderTargetPool.Release`.
+
+## Typed buffers
+
+`Buffer` and `RWBuffer` use a typed format. Match the HLSL element type and the supported view format; scalar 32-bit types are examples, not the only possible typed formats. Backend format capabilities still apply.
+
+| HLSL element | Example format |
+|---|---|
+| `float` | `PixelFormat.R32_Float` |
+| `int` | `PixelFormat.R32_SInt` |
+| `uint` | `PixelFormat.R32_UInt` |
+
+This helper initializes a writable typed buffer with pinned input and checks the failure result:
+
+```csharp
+using System;
+using FlaxEngine;
+
+public static class ComputeBuffers
+{
+ public static unsafe GPUBuffer Create(float[] values)
+ {
+ if (values == null || values.Length == 0)
+ throw new ArgumentException("Provide at least one element.", nameof(values));
+ checked { _ = values.Length * sizeof(float); }
+
+ var buffer = new GPUBuffer();
+ fixed (float* pointer = values)
+ {
+ var description = GPUBufferDescription.Typed(
+ (IntPtr)pointer, values.Length, PixelFormat.R32_Float, true);
+ if (buffer.Init(ref description)) // true means failure
+ {
+ FlaxEngine.Object.Destroy(buffer);
+ throw new InvalidOperationException("GPU buffer initialization failed.");
+ }
+ }
+ return buffer;
+ }
+}
+```
+
+`GPUResourceUsage.Default` does not mean immutable. Use the appropriate usage for your update strategy.
+
+## Structured buffers
+
+Use `GPUBufferDescription.Structured(elementCount, elementSize, isUnorderedAccess)` for `StructuredBuffer` or `RWStructuredBuffer`. It sets `PixelFormat.Unknown` and the Structured flag. Put GPUBufferFlags in `Flags`, not in `Usage`.
+
+For an HLSL `float3` element, the structured stride is 12 bytes. This is different from HLSL constant-buffer packing. Establish the complete CPU/HLSL layout before uploading a structure; a C# bool or managed reference is not a portable raw GPU field.
+
+## Binding resources
+
+Creation flags allow views; the shader declaration determines which view to bind:
+
+| HLSL declaration | Binding |
+|---|---|
+| `Buffer`, `StructuredBuffer`, `Texture2D` at `t0` | `context.BindSR(0, resource.View())` |
+| `RWBuffer`, `RWStructuredBuffer`, `RWTexture2D` at `u0` | `context.BindUA(0, resource.View())` |
+| constant buffer at `b0` | `context.BindCB(0, shader.GPU.GetCB(0))` |
+
+A buffer with both ShaderResource and UnorderedAccess flags can be read through an SRV in one pass and written through a UAV in another. The flags do not require UAV binding for every use. Avoid overlapping read/write bindings to the same subresource.
+
+Constant-buffer data must match HLSL layout and byte size, including padding. A sequential C# layout alone does not prove a match. Take the address of an unmanaged stack local, or pin managed storage, while calling UpdateCB. Initialize padding too.
+
+## Textures
+
+For an `RWTexture2D`, choose a concrete UAV-capable format supported by the device, for example R16G16B16A16_Float where supported. Use `GPUTextureFlags.ShaderResource | GPUTextureFlags.UnorderedAccess`, not GPUBufferFlags. Check the result of `GPUTexture.Init`.
+
+A typeless format is not a substitute for a correctly typed view. CPU uploads use the texture upload API with valid row/slice pitches; ShaderResource does not mean an uploaded texture cannot exist. A Texture asset owns its GPU texture, whereas a standalone GPUTexture is a rendering resource, not automatically a saved content asset.
+
+## Dispatch
+
+Check compute support, shader loading and a nonzero kernel returned by `GetCS("CS_Main")`. Dispatch dimensions count thread groups, not individual threads. For a group width of 64, use `(elementCount + 63) / 64` groups and check `id.x < elementCount` in HLSL. Skip empty workloads rather than forcing one group.
+
+Submit from the provided rendering callback context. Reset UAV/SRV slots in a finally block after use. Resetting bindings is state cleanup, not a GPU completion fence. Use separate dispatches for dependencies requiring all groups to finish; a group barrier synchronizes only its own group.
+
+## Upload and readback
+
+The buffer-description helpers create staging descriptions:
+
+- `ToStagingUpload()`: CPU-write staging storage.
+- `ToStagingReadback()`: CPU-read staging storage.
+- `ToStaging()`: CPU read/write staging storage where supported.
+
+They clear shader binding flags and InitData. Initialize a separate staging GPUBuffer and check its Init result. A staging buffer is copied to/from a GPU buffer; it is not the UAV used by the shader.
+
+For a manual readback, record `CopyBuffer(staging, source, byteCount)` before mapping staging for reading. Mapping may wait for GPU work; it is not a free asynchronous operation. Check for a null map result, copy into pinned destination storage within its bounds, and always Unmap in finally after a successful map. Upload follows the reverse direction: map CPU-write staging, fill it, unmap, then copy to the GPU destination.
+
+`GPUBuffer.DownloadData(out byte[])` provides a blocking convenience path. For a default GPU buffer the native implementation rejects main-thread use, queues copy/download tasks and waits on the calling worker. Keep the buffer alive, keep engine rendering progressing, and consume the result only after completion. Do not wait synchronously from an engine update/render callback. Calling DownloadData on a worker does not permit arbitrary GPUContext commands on that worker.
+
+Do not assume a fixed number of frames proves completion. A streaming service needs bounded pending requests and a shutdown/drain policy before releasing resources.
+
+## Further examples
+
+- [Post-processing blur](Running-compute-with-Post-Proccesing-efect.md)
+- [Render task](Running-compute-with-Render-Task.md)
+- [Main context usage](Running-compute-with-MainContext.md)
+
+Byte-address buffers, append/consume counters and a complete streaming readback service are not covered here yet.
diff --git a/manual/graphics/shaders/compute/media/32x32ComputeDebugTerrainGenerationHeightMap.png b/manual/graphics/shaders/compute/media/32x32ComputeDebugTerrainGenerationHeightMap.png
new file mode 100644
index 00000000..c7a2709c
Binary files /dev/null and b/manual/graphics/shaders/compute/media/32x32ComputeDebugTerrainGenerationHeightMap.png differ
diff --git a/manual/graphics/shaders/compute/media/RandomIslandHM.png b/manual/graphics/shaders/compute/media/RandomIslandHM.png
new file mode 100644
index 00000000..8724e5f0
Binary files /dev/null and b/manual/graphics/shaders/compute/media/RandomIslandHM.png differ
diff --git a/manual/graphics/shaders/compute/media/RandomIslandHMImportSettings.png b/manual/graphics/shaders/compute/media/RandomIslandHMImportSettings.png
new file mode 100644
index 00000000..e2dc6eba
Binary files /dev/null and b/manual/graphics/shaders/compute/media/RandomIslandHMImportSettings.png differ
diff --git a/manual/graphics/shaders/compute/media/ResultShow.png b/manual/graphics/shaders/compute/media/ResultShow.png
new file mode 100644
index 00000000..fb726e91
Binary files /dev/null and b/manual/graphics/shaders/compute/media/ResultShow.png differ
diff --git a/manual/graphics/shaders/custom-geometry-drawing.md b/manual/graphics/shaders/custom-geometry-drawing.md
index 5f378ab7..32a5a09f 100644
--- a/manual/graphics/shaders/custom-geometry-drawing.md
+++ b/manual/graphics/shaders/custom-geometry-drawing.md
@@ -2,6 +2,9 @@
In this tutorial you will learn how to implement custom geometry drawing. This technique allows to create custom geometry data, process it and display on a screen. It can be used to implement custom rendering for a game.
+### Extra important information
+Drawing GPU buffers directly bypasses some sub systems/submission path, so those draws do not automatically participate in occlusion culling, shadow passes or editor selection.
+
## 1. Create new shader
Firstly, create empty file in folder **Source/Shaders** and name it in a proper way, eg. `CustomGeometryDrawing.shader`. You can do it manually or use Editor and *right-click* in Content window shaders source folder **New -> Shader**.
@@ -215,8 +218,12 @@ public class CustomGeometryDrawing : PostProcessEffect
if (cb != IntPtr.Zero)
{
var data = new Data();
- Matrix.Multiply(ref renderContext.View.View, ref renderContext.View.Projection, out var viewProjection);
Actor.GetLocalToWorldMatrix(out var world);
+ //with large worlds offset is needed to render it correctly
+ world.M41 -= (float)renderContext.View.Origin.X;
+ world.M42 -= (float)renderContext.View.Origin.Y;
+ world.M43 -= (float)renderContext.View.Origin.Z;
+ Matrix.Multiply(ref renderContext.View.View, ref renderContext.View.Projection, out var viewProjection);
Matrix.Transpose(ref world, out data.WorldMatrix);
Matrix.Transpose(ref viewProjection, out data.ViewProjectionMatrix);
context.UpdateCB(cb, new IntPtr(&data));
@@ -243,3 +250,254 @@ Then **add script** to actor on scene and **assign Shader** property to the auto
Once you setup shader, script and add it to the scene you should be able to see in both Editor and Game viewports the rendered custom model. In case of problems see *Output Log* window in Editor as it may contain any compilation errors (for both C# script and shader code).

+
+# Expanded example
+some shading and shadow receiver example
+how to interact with flax lighting system
+
+
+```csharp
+using System;
+using System.Runtime.InteropServices;
+using FlaxEngine;
+
+public class FullVertexCube : PostProcessEffect
+{
+ public Shader Shader;
+ // All modes are albedo inputs to Flax deferred lighting.
+ [Limit(0, 4)] public int DebugMode;
+ [Limit(0.04f, 1.0f)] public float Roughness = 0.6f;
+ [Limit(0.0f, 1.0f)] public float Metalness;
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct Vertex
+ {
+ public Float3 Position;
+ public Float3 Normal;
+ public Float4 Tangent;
+ public Float2 UV;
+ public Float4 Color;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct Data
+ {
+ public Matrix World;
+ public Matrix ViewProjection;
+ public Float4 Options;
+ }
+
+ private GPUBuffer _vertices, _indices;
+ private GPUPipelineState _pipeline;
+ private Shader _pipelineShader;
+
+ public override unsafe void OnEnable()
+ {
+ //this.Actor.BoundingBox
+
+ UseSingleTarget = true;
+ Location = PostProcessEffectLocation.AfterGBufferPass;
+ var vertices = new Vertex[24];
+ var indices = new uint[36];
+ // Each face has its own vertices: hard normals and independent UV seams.
+ Face(vertices, indices, 0, new Float3(1, 0, 0), new Float3(0, 0, -1), new Float3(0, 1, 0));
+ Face(vertices, indices, 1, new Float3(-1, 0, 0), new Float3(0, 0, 1), new Float3(0, 1, 0));
+ Face(vertices, indices, 2, new Float3(0, 1, 0), new Float3(1, 0, 0), new Float3(0, 0, -1));
+ Face(vertices, indices, 3, new Float3(0, -1, 0), new Float3(1, 0, 0), new Float3(0, 0, 1));
+ Face(vertices, indices, 4, new Float3(0, 0, 1), new Float3(1, 0, 0), new Float3(0, 1, 0));
+ Face(vertices, indices, 5, new Float3(0, 0, -1), new Float3(-1, 0, 0), new Float3(0, 1, 0));
+ try
+ {
+ var layout = GPUVertexLayout.Get(new[]
+ {
+ new VertexElement(VertexElement.Types.Position, 0, 0, false, PixelFormat.R32G32B32_Float),
+ new VertexElement(VertexElement.Types.Normal, 0, 12, false, PixelFormat.R32G32B32_Float),
+ new VertexElement(VertexElement.Types.Tangent, 0, 24, false, PixelFormat.R32G32B32A32_Float),
+ new VertexElement(VertexElement.Types.TexCoord0, 0, 40, false, PixelFormat.R32G32_Float),
+ new VertexElement(VertexElement.Types.Color, 0, 48, false, PixelFormat.R32G32B32A32_Float),
+ });
+ _vertices = new GPUBuffer();
+ fixed (Vertex* ptr = vertices)
+ {
+ var desc = GPUBufferDescription.Vertex(layout, sizeof(Vertex), vertices.Length, (IntPtr)ptr);
+ if (_vertices.Init(ref desc)) throw new InvalidOperationException("Vertex buffer Init failed.");
+ }
+ _indices = new GPUBuffer();
+ fixed (uint* ptr = indices)
+ {
+ var desc = GPUBufferDescription.Index(sizeof(uint), indices.Length, (IntPtr)ptr);
+ if (_indices.Init(ref desc)) throw new InvalidOperationException("Index buffer Init failed.");
+ }
+ Content.AssetReloading += OnReload;
+ SceneRenderTask.AddGlobalCustomPostFx(this);
+ }
+ catch
+ {
+ Destroy(ref _vertices);
+ Destroy(ref _indices);
+ throw;
+ }
+ }
+
+ private static void Face(Vertex[] vertices, uint[] indices, int face, Float3 normal, Float3 u, Float3 v)
+ {
+ for (int corner = 0; corner < 4; corner++)
+ {
+ float x = corner == 1 || corner == 2 ? 1 : 0;
+ float y = corner >= 2 ? 1 : 0;
+ vertices[face * 4 + corner] = new Vertex
+ {
+ Position = (normal + u * (x * 2 - 1) + v * (y * 2 - 1)) * 50,
+ Normal = normal,
+ Tangent = new Float4(u.X, u.Y, u.Z, 1),
+ UV = new Float2(x, y),
+ Color = new Float4(normal.X * .5f + .5f, normal.Y * .5f + .5f, normal.Z * .5f + .5f, 1)
+ };
+ }
+ uint b = (uint)(face * 4);
+ int i = face * 6;
+ indices[i] = b; indices[i + 1] = b + 1; indices[i + 2] = b + 2;
+ indices[i + 3] = b; indices[i + 4] = b + 2; indices[i + 5] = b + 3;
+ }
+
+ private void OnReload(Asset asset)
+ {
+ if (asset == Shader) Destroy(ref _pipeline);
+ }
+
+ public override bool CanRender() => base.CanRender() && Shader != null && Shader.IsLoaded && _vertices != null && _indices != null;
+
+ public override unsafe void Render(GPUContext context, ref RenderContext renderContext, GPUTexture input, GPUTexture output)
+ {
+ if (_pipelineShader != Shader)
+ {
+ Destroy(ref _pipeline);
+ _pipelineShader = Shader;
+ }
+ if (_pipeline == null)
+ {
+ var desc = GPUPipelineState.Description.Default;
+ desc.VS = Shader.GPU.GetVS("VS_Custom");
+ desc.PS = Shader.GPU.GetPS("PS_Custom");
+ desc.CullMode = CullMode.TwoSided; // Inspect both sides during attribute tests.
+ if (desc.VS == IntPtr.Zero || desc.PS == IntPtr.Zero) return;
+ _pipeline = new GPUPipelineState();
+ if (_pipeline.Init(ref desc))
+ {
+ Destroy(ref _pipeline);
+ throw new InvalidOperationException("Graphics pipeline Init failed.");
+ }
+ }
+ var cb = Shader.GPU.GetCB(0);
+ if (cb == IntPtr.Zero) return;
+ Actor.GetLocalToWorldMatrix(out var world);
+ //with large worlds offset is needed to render it correctly
+ world.M41 -= (float)renderContext.View.Origin.X;
+ world.M42 -= (float)renderContext.View.Origin.Y;
+ world.M43 -= (float)renderContext.View.Origin.Z;
+ Matrix.Multiply(ref renderContext.View.View, ref renderContext.View.Projection, out var vp);
+ var data = new Data { Options = new Float4(DebugMode, Mathf.Clamp(Roughness, 0.04f, 1.0f), Mathf.Clamp(Metalness, 0.0f, 1.0f), 0.5f) };
+ Matrix.Transpose(ref world, out data.World);
+ Matrix.Transpose(ref vp, out data.ViewProjection);
+ context.UpdateCB(cb, (IntPtr)(&data));
+ context.BindCB(0, cb);
+ context.BindVB(new[] { _vertices });
+ context.BindIB(_indices);
+ context.SetState(_pipeline);
+ // MRT order must match GBufferPass::Fill and the pixel shader outputs.
+ context.SetRenderTarget(renderContext.Buffers.DepthBuffer.View(), new[]
+ {
+ input.View(), // scene light/emission target, not final post-process output
+ renderContext.Buffers.GBuffer0.View(),
+ renderContext.Buffers.GBuffer1.View(),
+ renderContext.Buffers.GBuffer2.View(),
+ renderContext.Buffers.GBuffer3.View(),
+ });
+ context.DrawIndexed(36);
+ }
+
+ public override void OnDisable()
+ {
+ SceneRenderTask.RemoveGlobalCustomPostFx(this);
+ Content.AssetReloading -= OnReload;
+ Destroy(ref _pipeline);
+ Destroy(ref _vertices);
+ Destroy(ref _indices);
+ _pipelineShader = null;
+ }
+}
+
+```
+
+Shader Code
+
+```hlsl
+#include "./Flax/Common.hlsl"
+META_CB_BEGIN(0, Data)
+float4x4 World;
+float4x4 ViewProjection;
+float4 Options;
+META_CB_END
+
+struct VertexInput
+{
+ float3 Position : POSITION;
+ float3 Normal : NORMAL;
+ float4 Tangent : TANGENT;
+ float2 UV : TEXCOORD0;
+ float4 Color : COLOR0;
+};
+struct Interpolants
+{
+ float4 Position : SV_Position;
+ float3 Normal : TEXCOORD0;
+ float3 Tangent : TEXCOORD1;
+ float2 UV : TEXCOORD2;
+ float4 Color : COLOR0;
+};
+META_VS(true, FEATURE_LEVEL_SM5)
+Interpolants VS_Custom(VertexInput input)
+{
+ Interpolants output;
+ float3 position = mul(float4(input.Position, 1), World).xyz;
+ output.Position = mul(float4(position, 1), ViewProjection);
+ float3 tangent = mul(float4(input.Tangent.xyz, 0), World).xyz;
+ float3 bitangent = mul(float4(cross(input.Normal, input.Tangent.xyz) * input.Tangent.w, 0), World).xyz;
+ // Tangent-plane cross product handles positive nonuniform scale too.
+ output.Normal = normalize(cross(tangent, bitangent) * input.Tangent.w);
+ output.Tangent = normalize(tangent);
+ output.UV = input.UV;
+ output.Color = input.Color;
+ return output;
+}
+// This is a minimal opaque lit-material GBuffer writer, not a generated material.
+struct GBufferOutput
+{
+ float4 Light : SV_Target0;
+ float4 RT0 : SV_Target1;
+ float4 RT1 : SV_Target2;
+ float4 RT2 : SV_Target3;
+ float4 RT3 : SV_Target4;
+};
+META_PS(true, FEATURE_LEVEL_SM5)
+GBufferOutput PS_Custom(Interpolants input)
+{
+ float3 normal = normalize(input.Normal);
+ float checker = fmod(floor(input.UV.x * 8) + floor(input.UV.y * 8), 2);
+ float3 albedo = lerp(float3(.08,.15,.25), float3(.9,.7,.3), checker);
+ if (Options.x > 3.5) albedo = input.Color.rgb;
+ else if (Options.x > 2.5) albedo = normalize(input.Tangent) * .5 + .5;
+ else if (Options.x > 1.5) albedo = float3(input.UV, 0);
+ else if (Options.x > .5) albedo = normal * .5 + .5;
+ GBufferOutput output;
+ output.Light = float4(0, 0, 0, 1);
+ output.RT0 = float4(albedo, 1); // linear base colour, AO
+ output.RT1 = float4(normal * .5 + .5, SHADING_MODEL_LIT / 3.0);
+ output.RT2 = float4(Options.y, Options.z, Options.w, 0); // roughness, metalness, specular
+ output.RT3 = 0; // no subsurface/custom payload
+ return output;
+}
+```
+result
+
+
\ No newline at end of file
diff --git a/manual/graphics/shaders/index.md b/manual/graphics/shaders/index.md
index 7572f2b0..cc520c9a 100644
--- a/manual/graphics/shaders/index.md
+++ b/manual/graphics/shaders/index.md
@@ -109,6 +109,6 @@ To learn how to use shaders in your projects follow the documentation and tutori
* [Custom Fullscreen Shader](custom-fullscreen-shader.md)
* [Custom Geometry Drawing](custom-geometry-drawing.md)
-* [Custom Compute Shader](custom-compute-shader.md)
+* [Compute Shader](compute-shader.md)
* [Cel Shading](cel-shading.md)
* [Graphics API](graphics-api.md)
diff --git a/manual/graphics/shaders/media/CreateMyComputeShader.png b/manual/graphics/shaders/media/CreateMyComputeShader.png
new file mode 100644
index 00000000..ba062a12
Binary files /dev/null and b/manual/graphics/shaders/media/CreateMyComputeShader.png differ
diff --git a/manual/graphics/shaders/media/NewShaderSourceCode.png b/manual/graphics/shaders/media/NewShaderSourceCode.png
new file mode 100644
index 00000000..d522b56e
Binary files /dev/null and b/manual/graphics/shaders/media/NewShaderSourceCode.png differ
diff --git a/manual/graphics/shaders/media/Shaded-custom-geometry.png b/manual/graphics/shaders/media/Shaded-custom-geometry.png
new file mode 100644
index 00000000..555bd076
Binary files /dev/null and b/manual/graphics/shaders/media/Shaded-custom-geometry.png differ
diff --git a/manual/graphics/shaders/media/ShaderFolders.png b/manual/graphics/shaders/media/ShaderFolders.png
new file mode 100644
index 00000000..176139ef
Binary files /dev/null and b/manual/graphics/shaders/media/ShaderFolders.png differ
diff --git a/manual/toc.md b/manual/toc.md
index 0c537a4f..304ed2b1 100644
--- a/manual/toc.md
+++ b/manual/toc.md
@@ -159,7 +159,12 @@
## [Shaders](graphics/shaders/index.md)
### [Custom Fullscreen Shader](graphics/shaders/custom-fullscreen-shader.md)
### [Custom Geometry Drawing](graphics/shaders/custom-geometry-drawing.md)
-### [Custom Compute Shader](graphics/shaders/custom-compute-shader.md)
+### [Compute Shader](graphics/shaders/compute-shader.md)
+#### [High level API](graphics/shaders/compute/hl-api.md)
+#### [Low level API](graphics/shaders/compute/ll-api.md)
+##### [Running compute with Post Processing Effect](graphics/shaders/compute/Running-compute-with-Post-Proccesing-efect.md)
+##### [Running compute with Render Task](graphics/shaders/compute/Running-compute-with-Render-Task.md)
+##### [Running compute with Main GPU Context](graphics/shaders/compute/Running-compute-with-MainContext.md)
### [Cel Shading](graphics/shaders/cel-shading.md)
### [Graphics API](graphics/shaders/graphics-api.md)
## [Video](graphics/video/index.md)