diff --git a/README.md b/README.md index 08fb7c30..7bf6e144 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,8 @@ If the shader in C# is capturing some local variable, those will be automaticall ✅ `Func`s, local methods or delegates with no captured variables +✅ `static` fields and properties with a supported delegate type + ## Advanced usage **ComputeSharp** lets you dispatch compute shaders over thread groups from 1 to 3 dimensions, includes supports for constant and readonly buffers, and more. The shader body can both be declared inline, as a separate `Action` or as a local method. Additionally, most of the [HLSL intrinsic functions](https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-intrinsic-functions) are available through the `Hlsl` class. Here is a more advanced sample showcasing all these features. @@ -71,11 +73,14 @@ float[] y = new float[height * width]; // Result array (assume both had some val using ReadOnlyBuffer xBuffer = Gpu.Default.AllocateReadOnlyBuffer(x); using ReadWriteBuffer yBuffer = Gpu.Default.AllocateReadWriteBuffer(y); +static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x)); + // Shader body void Kernel(ThreadIds id) { int offset = id.X + id.Y * width; - yBuffer[offset] = Hlsl.Pow(xBuffer[offset], 2); + float pow = Hlsl.Pow(xBuffer[offset], 2); + yBuffer[offset] = Sigmoid(pow); } // Run the shader diff --git a/tests/ComputeSharp.Tests/StaticFunctionsTests.cs b/tests/ComputeSharp.Tests/StaticFunctionsTests.cs index df10a105..ce7ccb7c 100644 --- a/tests/ComputeSharp.Tests/StaticFunctionsTests.cs +++ b/tests/ComputeSharp.Tests/StaticFunctionsTests.cs @@ -175,5 +175,27 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); } + + [TestMethod] + public void ReadmeSample() + { + float[] buffer = { 3 }; + using ReadWriteBuffer xBuffer = Gpu.Default.AllocateReadWriteBuffer(buffer); + + static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x)); + + void Kernel(ThreadIds id) + { + int offset = id.X + id.Y * 1; + float pow = Hlsl.Pow(xBuffer[offset], 2); // 9 + xBuffer[offset] = Sigmoid(pow); // 0.9998766 + } + + Gpu.Default.For(1, Kernel); + + float[] result = xBuffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - 0.9998766f) < 0.0001f); + } } }