diff --git a/README.md b/README.md index dbaa172f..7510bfc1 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ More details available [here](https://www.nuget.org/packages/ComputeSharp/). # Quick start -**ComputeSharp** exposes a `Gpu` class that acts as the entry point for all public APIs. It exposes the `Gpu.Default` property that let you access the main GPU device on the current machine, which can be used to allocate buffers and perform operations. +**ComputeSharp** exposes a `Gpu` class that acts entry point for all public APIs. It exposes the `Gpu.Default` property that let you access the main GPU device on the current machine, which can be used to allocate buffers and perform operations. The following sample shows how to allocate a writeable buffer, populate it with a compute shader, and read it back. @@ -34,11 +34,8 @@ The following sample shows how to allocate a writeable buffer, populate it with // Allocate a writeable buffer on the GPU, with the contents of the array using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1000); -// Shader body -Action action = id => buffer[id.X] = id.X; - // Run the shader -Gpu.Default.For(1000, action); +Gpu.Default.For(1000, id => buffer[id.X] = id.X); // Get the data back float[] array = buffer.GetData(); @@ -50,7 +47,7 @@ If the shader in C# is capturing some local variable, those will be automaticall ## Advanced usage -**ComputeSharp** lets you dispatch compute shaders over thread groups from 1 to 3 dimensions, includes supports for readonly buffers, and more. Here is a more advanced sample showcasing both these two features. +**ComputeSharp** lets you dispatch compute shaders over thread groups from 1 to 3 dimensions, includes supports for readonly buffers, and more. The shader body can both be declared inline, as a separate `Action` or as a local method. Here is a more advanced sample showcasing all these features. ```C# int height = 10, width = 10; @@ -61,14 +58,14 @@ using ReadOnlyBuffer xBuffer = Gpu.Default.AllocateConstantBuffer(x); using ReadWriteBuffer yBuffer = Gpu.Default.AllocateReadWriteBuffer(y); // Shader body -Action action = id => +void Main(ThreadIds id) { uint offset = id.X + id.Y * (uint)width; yBuffer[offset] += xBuffer[offset]; -}; +} // Run the shader -Gpu.Default.For(width, height, action); +Gpu.Default.For(width, height, Main); // Get the data back and write it to the y array yBuffer.GetData(y); diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs index bde98d3e..c344e728 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs @@ -39,6 +39,12 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// The input to write data to public abstract void GetData(Span span); + /// + /// Writes the contents of a given array to the current instance + /// + /// The input array to read data from + public void SetData(T[] array) => SetData(array.AsSpan()); + /// /// Writes the contents of a given to the current instance /// diff --git a/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs b/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs new file mode 100644 index 00000000..842ba39c --- /dev/null +++ b/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Reflection; +using ComputeSharp.Graphics.Buffers.Abstract; + +namespace ComputeSharp.Graphics.Buffers.Extensions +{ + /// + /// A with extension methods for the type to allocate generic resources + /// + internal static class GraphicsResourceExtensions + { + /// + /// Allocates a new constant buffer with the specified generic value + /// + /// The instance to use to allocate the buffer + /// The input to copy to the allocated buffer + /// A constant instance (as a ) with the input data + [Pure] + public static GraphicsResource AllocateReadOnlyBufferFromReflectedSingleValue(this GraphicsDevice device, object data) + { + // Create the generic constant buffer + Type + dataType = data.GetType(), + bufferType = typeof(ReadOnlyBuffer<>).MakeGenericType(dataType); + ConstructorInfo constructor = bufferType.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).First(); + GraphicsResource buffer = (GraphicsResource)constructor.Invoke(new object[] { device, 1 }); + + // Create the array with the input value + Type arrayType = dataType.MakeArrayType(); + ConstructorInfo[] arrayConstructors = arrayType.GetConstructors(BindingFlags.CreateInstance + | BindingFlags.Public + | BindingFlags.Instance + | BindingFlags.OptionalParamBinding); + Array array = (Array)arrayConstructors[0].Invoke(new object[] { 1 }); + + // Use the IList indexer to set the generic object + IList ilist = array; + ilist[0] = data; + + // Set the input data to the new buffer + MethodInfo setDataMethod = bufferType.GetMethod(nameof(HlslBuffer.SetData), new[] { arrayType }); + setDataMethod.Invoke(buffer, new object[] { array }); + + return buffer; + } + } +} diff --git a/src/ComputeSharp.Graphics/Properties/AssemblyInfo.cs b/src/ComputeSharp.Graphics/Properties/AssemblyInfo.cs index 8fb2fba6..2ccbb996 100644 --- a/src/ComputeSharp.Graphics/Properties/AssemblyInfo.cs +++ b/src/ComputeSharp.Graphics/Properties/AssemblyInfo.cs @@ -1,3 +1,4 @@ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("ComputeSharp.Shaders")] +[assembly: InternalsVisibleTo("ComputeSharp.NetCore.Tests")] diff --git a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache index 70165909..ef061a4b 100644 --- a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache +++ b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache @@ -7,7 +7,7 @@ static {{&FieldType}} {{FieldName}} = {{FieldValue}}; {{#IsConstantBuffer}} cbuffer {{FieldName}}Buffer : register(b{{ConstantBufferIndex}}) { -{{&FieldType}} {{FieldName}}{{^IsSingleValue}}[2]{{/IsSingleValue}}; + {{&FieldType}} {{FieldName}}{{^IsSingleValue}}[2]{{/IsSingleValue}}; } {{/IsConstantBuffer}} {{!Read write buffer}} diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs index b32694e2..b59b6ffe 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner.cs @@ -1,6 +1,8 @@ using System; -using System.Linq; +using System.Collections.Generic; using ComputeSharp.Graphics; +using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Graphics.Buffers.Extensions; using ComputeSharp.Shaders.Renderer; using ComputeSharp.Shaders.Renderer.Models; using ComputeSharp.Shaders.Translation; @@ -65,14 +67,29 @@ namespace ComputeSharp.Shaders commandList.SetPipelineState(pipelineState); // Load the captured buffers - foreach (var buffer in shaderLoader.Buffers.Select((r, i) => (Resource: r, Index: i))) + foreach (var buffer in shaderLoader.Buffers) { commandList.SetComputeRootDescriptorTable(buffer.Index, buffer.Resource); } + // Load the captured variables + List buffers = new List(); + foreach (var variable in shaderLoader.CapturedConstantBufferValues) + { + GraphicsResource resource = device.AllocateReadOnlyBufferFromReflectedSingleValue(variable.Value); + commandList.SetComputeRootDescriptorTable(variable.Index, resource); + buffers.Add(resource); + } + // Dispatch and wait for completion commandList.Dispatch(groupsX, groupsY, groupsZ); commandList.Flush(); + + // Free the allocated resources + foreach (GraphicsResource resource in buffers) + { + resource.Dispose(); + } } } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index b58a597b..26bcf29a 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -61,7 +61,12 @@ namespace ComputeSharp.Shaders.Translation /// /// Gets the ordered collection of buffers used as fields in the current shader /// - public IReadOnlyList Buffers { get; private set; } + public IReadOnlyList<(int Index, GraphicsResource Resource)> Buffers { get; private set; } + + /// + /// Gets the ordered collection of captured variables that need to be assigned to constant buffers + /// + public IReadOnlyList<(int Index, object Value)> CapturedConstantBufferValues { get; private set; } private readonly List _FieldsInfo = new List(); @@ -106,7 +111,8 @@ namespace ComputeSharp.Shaders.Translation if (ShaderFields.Any(fieldInfo => fieldInfo.IsStatic)) throw new InvalidOperationException("Empty shader body"); List descriptorRanges = new List(); - List buffers = new List(); + List<(int, GraphicsResource)> buffers = new List<(int, GraphicsResource)>(); + List<(int, object)> variables = new List<(int, object)>(); int readWriteBuffersCount = 0; int readOnlyBuffersCount = 0; @@ -125,7 +131,7 @@ namespace ComputeSharp.Shaders.Translation descriptorRanges.Add(range); // Reference to the underlying buffer - buffers.Add((GraphicsResource)fieldValue); + buffers.Add((descriptorRanges.Count - 1, (GraphicsResource)fieldValue)); string typeName = HlslKnownTypes.GetMappedName(fieldType); processedFieldInfo = new ReadWriteBufferFieldInfo(typeName, fieldName, readWriteBuffersCount++); @@ -137,16 +143,23 @@ namespace ComputeSharp.Shaders.Translation descriptorRanges.Add(range); // Reference to the underlying buffer - buffers.Add((GraphicsResource)fieldValue); + buffers.Add((descriptorRanges.Count - 1, (GraphicsResource)fieldValue)); string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); processedFieldInfo = new ConstantBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++, false); } else if (HlslKnownTypes.IsKnownScalarType(fieldType)) { - // Static scalar field + // Read only buffer + DescriptorRange range = new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, readOnlyBuffersCount); + descriptorRanges.Add(range); + + // Register the captured value + variables.Add((descriptorRanges.Count - 1, fieldValue)); + + // Constant buffer field string typeName = HlslKnownTypes.GetMappedName(fieldType); - processedFieldInfo = new StaticScalarFieldInfo(typeName, fieldName, fieldValue); + processedFieldInfo = new ConstantBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++, true); } else throw new NotSupportedException($"Unsupported field of type {fieldType.FullName}"); @@ -155,6 +168,7 @@ namespace ComputeSharp.Shaders.Translation RootParameters = descriptorRanges.Select(range => new RootParameter(ShaderVisibility.All, range)).ToArray(); Buffers = buffers; + CapturedConstantBufferValues = variables; } /// @@ -177,6 +191,7 @@ namespace ComputeSharp.Shaders.Translation // Additional preprocessing MethodBody = Regex.Replace(MethodBody, @"\d+[fFdD]", m => m.Value.Replace("f", "")); MethodBody = MethodBody.TrimEnd('\n', '\r', ' '); + MethodBody = $" {MethodBody.Replace(Environment.NewLine, $"{Environment.NewLine} ")}"; } } } diff --git a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs index 5040ea07..e2d4c621 100644 --- a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs +++ b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs @@ -1,6 +1,8 @@ using System; using System.Linq; using ComputeSharp.Graphics.Buffers; +using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Graphics.Buffers.Extensions; using ComputeSharp.NetCore.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -10,6 +12,30 @@ namespace ComputeSharp.NetCore.Tests [TestCategory("Buffers")] public class BufferTests { + [TestMethod] + public void ReadWriteBufferGetSetDataFromSingleValueInt() + { + object value = 77; + + using ReadOnlyBuffer buffer = (ReadOnlyBuffer)Gpu.Default.AllocateReadOnlyBufferFromReflectedSingleValue(value); + int[] result = buffer.GetData(); + + Assert.IsTrue(result.Length == 1); + Assert.IsTrue((int)value == result[0]); + } + + [TestMethod] + public void ReadWriteBufferGetSetDataFromSingleValueFloat() + { + object value = 3.14f; + + using ReadOnlyBuffer buffer = (ReadOnlyBuffer)Gpu.Default.AllocateReadOnlyBufferFromReflectedSingleValue(value); + float[] result = buffer.GetData(); + + Assert.IsTrue(result.Length == 1); + Assert.IsTrue(MathF.Abs(result[0] - (float)value) < 0.0001f); + } + [TestMethod] public void ReadWriteBufferGetSetDataFromArray() { diff --git a/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs b/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs index 18bad3b9..abda8eb8 100644 --- a/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs +++ b/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs @@ -23,7 +23,7 @@ namespace ComputeSharp.NetCore.Tests float[] result = buffer.GetData(); - Assert.IsTrue((int)result[0] == (int)value); + Assert.IsTrue(MathF.Abs(result[0] - value) < 0.0001f); } [TestMethod]