From 46ea7e476fe050b1041306c54553d62ae62f4bb1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 00:48:53 +0200 Subject: [PATCH 01/38] NuGet package setup --- src/ComputeSharp/ComputeSharp.csproj | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj index 57aeb7e6..fea65bb6 100644 --- a/src/ComputeSharp/ComputeSharp.csproj +++ b/src/ComputeSharp/ComputeSharp.csproj @@ -4,6 +4,16 @@ netstandard2.0 8.0 enable + 1.0.0-alpha+85bfe4f636407cb9f41ce1c8856c662b634399f0 + Sergio Pedri + true + true + A .NET Standard 2.0 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders + Copyright (c) 2019 Sergio Pedri + LICENSE + https://github.com/Sergio0694/ComputeSharp + https://github.com/Sergio0694/ComputeSharp + dotnet net netcore netstandard csharp library graphics shader hlsl compute gpu @@ -17,4 +27,11 @@ + + + True + + + + From 60d5114298c2d9c44b827e64dc1f2692529271ed Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 00:58:15 +0200 Subject: [PATCH 02/38] Switched from nustache to Stubble lib --- src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj | 2 +- src/ComputeSharp.Shaders/Renderer/ShaderRenderer.cs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj index 086f0e66..cc3f7086 100644 --- a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj +++ b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj @@ -13,8 +13,8 @@ - + diff --git a/src/ComputeSharp.Shaders/Renderer/ShaderRenderer.cs b/src/ComputeSharp.Shaders/Renderer/ShaderRenderer.cs index f9aeb680..c9161fba 100644 --- a/src/ComputeSharp.Shaders/Renderer/ShaderRenderer.cs +++ b/src/ComputeSharp.Shaders/Renderer/ShaderRenderer.cs @@ -3,6 +3,7 @@ using System.Diagnostics.Contracts; using System.IO; using System.Reflection; using ComputeSharp.Shaders.Renderer.Models; +using Stubble.Core; namespace ComputeSharp.Shaders.Renderer { @@ -39,6 +40,6 @@ namespace ComputeSharp.Shaders.Renderer /// The input instance with the shader information /// The source code for the new HLSL shader [Pure] - public string Render(ShaderInfo info) => Nustache.Core.Render.StringToString(Template, info); + public string Render(ShaderInfo info) => StaticStubbleRenderer.Render(Template, info); } } From 27898b0878ff03178c1a2576433322ee46fc6da5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 01:36:24 +0200 Subject: [PATCH 03/38] Added unit test project --- src/ComputeSharp.sln | 13 +++++++++++++ .../ComputeSharp.NetCore.Tests.csproj | 19 +++++++++++++++++++ tests/ComputeSharp.NetCore.Tests/UnitTest1.cs | 13 +++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 tests/ComputeSharp.NetCore.Tests/ComputeSharp.NetCore.Tests.csproj create mode 100644 tests/ComputeSharp.NetCore.Tests/UnitTest1.cs diff --git a/src/ComputeSharp.sln b/src/ComputeSharp.sln index 56d82d29..daaf3fd2 100644 --- a/src/ComputeSharp.sln +++ b/src/ComputeSharp.sln @@ -18,6 +18,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_SolutionItems", "_Solution EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.NetCore.Tests", "..\tests\ComputeSharp.NetCore.Tests\ComputeSharp.NetCore.Tests.csproj", "{E91F4D24-922A-4921-A8D7-9C45A143C45D}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -58,12 +62,21 @@ Global {7A48A85D-8866-4DED-A404-653ED09BF396}.Release|Any CPU.Build.0 = Release|Any CPU {7A48A85D-8866-4DED-A404-653ED09BF396}.Release|x64.ActiveCfg = Release|Any CPU {7A48A85D-8866-4DED-A404-653ED09BF396}.Release|x64.Build.0 = Release|Any CPU + {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Debug|x64.ActiveCfg = Debug|Any CPU + {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Debug|x64.Build.0 = Debug|Any CPU + {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Release|Any CPU.Build.0 = Release|Any CPU + {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Release|x64.ActiveCfg = Release|Any CPU + {E91F4D24-922A-4921-A8D7-9C45A143C45D}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {7A48A85D-8866-4DED-A404-653ED09BF396} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} + {E91F4D24-922A-4921-A8D7-9C45A143C45D} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC} diff --git a/tests/ComputeSharp.NetCore.Tests/ComputeSharp.NetCore.Tests.csproj b/tests/ComputeSharp.NetCore.Tests/ComputeSharp.NetCore.Tests.csproj new file mode 100644 index 00000000..32d0c982 --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/ComputeSharp.NetCore.Tests.csproj @@ -0,0 +1,19 @@ + + + + netcoreapp3.0 + + false + + + + + + + + + + + + + diff --git a/tests/ComputeSharp.NetCore.Tests/UnitTest1.cs b/tests/ComputeSharp.NetCore.Tests/UnitTest1.cs new file mode 100644 index 00000000..7bcdcfaa --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/UnitTest1.cs @@ -0,0 +1,13 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.NetCore.Sample +{ + [TestClass] + public class UnitTest1 + { + [TestMethod] + public void TestMethod1() + { + } + } +} From dd41c90937aac64d909955eaab37158ed0d7ddf8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 01:51:06 +0200 Subject: [PATCH 04/38] Added some helper methods to the test project --- .../Extensions/SpanExtensions.cs | 54 +++++++++++++++++++ .../Extensions/Types/ConcurrentRandom.cs | 28 ++++++++++ 2 files changed, 82 insertions(+) create mode 100644 tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs create mode 100644 tests/ComputeSharp.NetCore.Tests/Extensions/Types/ConcurrentRandom.cs diff --git a/tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs b/tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs new file mode 100644 index 00000000..bb52f8be --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs @@ -0,0 +1,54 @@ +using System; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; + +namespace ComputeSharp.NetCore.Tests.Extensions +{ + /// + /// An helper with methods to process fixed-size buffers + /// + public static class SpanExtensions + { + /// + /// Fills an input instance with random values + /// + /// The target to fill + public static void FillRandom(this Span span) + { + if (span.Length == 0) return; + + var l = span.Length; + ref var rspan = ref span.GetPinnableReference(); + + for (var i = 0; i < l; i++) + Unsafe.Add(ref rspan, i) = (float)ConcurrentRandom.Instance.NextDouble(); + } + + /// + /// The maximum threshold to validate two values as being equal + /// + private const float FloatThreshold = 0.00001f; + + /// + /// Checks whether or not the two input instances have the same content + /// + /// The first to check + /// The second to check + [Pure] + public static bool ContentEquals(this Span a, Span b) + { + if (a.Length != b.Length) return false; + if (a.Length == 0) return true; + + var l = a.Length; + ref var ra = ref a.GetPinnableReference(); + ref var rb = ref b.GetPinnableReference(); + + for (var i = 0; i < l; i++) + if (Math.Abs(Unsafe.Add(ref ra, i) - Unsafe.Add(ref rb, i)) > FloatThreshold) + return false; + + return true; + } + } +} diff --git a/tests/ComputeSharp.NetCore.Tests/Extensions/Types/ConcurrentRandom.cs b/tests/ComputeSharp.NetCore.Tests/Extensions/Types/ConcurrentRandom.cs new file mode 100644 index 00000000..5cbd72c0 --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/Extensions/Types/ConcurrentRandom.cs @@ -0,0 +1,28 @@ +using System.Runtime.CompilerServices; +using System.Threading; + +namespace System +{ + /// + /// A thread-safe wrapper class + /// + public static class ConcurrentRandom + { + // Shared seed + private static int _Seed = Environment.TickCount; + + /// + /// The object that provides the instances + /// + private static readonly ThreadLocal _Instance = new ThreadLocal(() => new Random(Interlocked.Increment(ref _Seed))); + + /// + /// Gets a thread-safe instance + /// + public static Random Instance + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _Instance.Value; + } + } +} \ No newline at end of file From bde4f28857ba1fc34b9215a2236c50ac0dbbdd55 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 01:51:59 +0200 Subject: [PATCH 05/38] Added buffer tests --- .../ComputeSharp.NetCore.Tests/BufferTests.cs | 36 +++++++++++++++++++ tests/ComputeSharp.NetCore.Tests/UnitTest1.cs | 13 ------- 2 files changed, 36 insertions(+), 13 deletions(-) create mode 100644 tests/ComputeSharp.NetCore.Tests/BufferTests.cs delete mode 100644 tests/ComputeSharp.NetCore.Tests/UnitTest1.cs diff --git a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs new file mode 100644 index 00000000..e59204b3 --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs @@ -0,0 +1,36 @@ +using System; +using ComputeSharp.Graphics.Buffers; +using ComputeSharp.NetCore.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.NetCore.Sample +{ + [TestClass] + [TestCategory("Buffers")] + public class BufferTests + { + [TestMethod] + public void ReadWriteBufferGetSetData() + { + float[] array = new float[4096]; + array.AsSpan().FillRandom(); + + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(array); + float[] result = buffer.GetData(); + + Assert.IsTrue(array.AsSpan().ContentEquals(result)); + } + + [TestMethod] + public void ReadOnlyBufferGetSetData() + { + float[] array = new float[4096]; + array.AsSpan().FillRandom(); + + using ReadOnlyBuffer buffer = Gpu.Default.AllocateConstantBuffer(array); + float[] result = buffer.GetData(); + + Assert.IsTrue(array.AsSpan().ContentEquals(result)); + } + } +} diff --git a/tests/ComputeSharp.NetCore.Tests/UnitTest1.cs b/tests/ComputeSharp.NetCore.Tests/UnitTest1.cs deleted file mode 100644 index 7bcdcfaa..00000000 --- a/tests/ComputeSharp.NetCore.Tests/UnitTest1.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace ComputeSharp.NetCore.Sample -{ - [TestClass] - public class UnitTest1 - { - [TestMethod] - public void TestMethod1() - { - } - } -} From 00d1c9ef5bbe09b2c9fd071fe23f50de4a9a757a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 02:13:40 +0200 Subject: [PATCH 06/38] Added exception when trying to compile an empty shader --- .../Translation/ShaderLoader.cs | 2 ++ .../ComputeSharp.NetCore.Tests/BufferTests.cs | 2 +- .../ShaderCompileTests.cs | 18 ++++++++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 tests/ComputeSharp.NetCore.Tests/ShaderCompileTests.cs diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index acdeac27..40859c0d 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -103,6 +103,8 @@ namespace ComputeSharp.Shaders.Translation { if (FieldsInfo.Count > 0) throw new InvalidOperationException("Shader fields already loaded"); + if (ShaderFields.Any(fieldInfo => fieldInfo.IsStatic)) throw new InvalidOperationException("Empty shader body"); + List descriptorRanges = new List(); List readWriteBuffers = new List(); int readWriteBuffersCount = 0; diff --git a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs index e59204b3..fea3f1ed 100644 --- a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs +++ b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs @@ -3,7 +3,7 @@ using ComputeSharp.Graphics.Buffers; using ComputeSharp.NetCore.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; -namespace ComputeSharp.NetCore.Sample +namespace ComputeSharp.NetCore.Tests { [TestClass] [TestCategory("Buffers")] diff --git a/tests/ComputeSharp.NetCore.Tests/ShaderCompileTests.cs b/tests/ComputeSharp.NetCore.Tests/ShaderCompileTests.cs new file mode 100644 index 00000000..0043d9f4 --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/ShaderCompileTests.cs @@ -0,0 +1,18 @@ +using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.NetCore.Tests +{ + [TestClass] + [TestCategory("ShaderCompile")] + public class ShaderTests + { + [TestMethod] + public void EmptyShaderCompileError() + { + Action action = id => { }; + + Assert.ThrowsException(() => Gpu.Default.For(10, action)); + } + } +} From fb7b7bcd3d8c7bc2ab51ad6d2bec840968878af6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 02:44:22 +0200 Subject: [PATCH 07/38] More unit tests added (3D dispatch failing) --- ...rCompileTests.cs => InvalidShaderTests.cs} | 5 +- .../ShaderDispatchTests.cs | 58 +++++++++++++++++++ 2 files changed, 61 insertions(+), 2 deletions(-) rename tests/ComputeSharp.NetCore.Tests/{ShaderCompileTests.cs => InvalidShaderTests.cs} (83%) create mode 100644 tests/ComputeSharp.NetCore.Tests/ShaderDispatchTests.cs diff --git a/tests/ComputeSharp.NetCore.Tests/ShaderCompileTests.cs b/tests/ComputeSharp.NetCore.Tests/InvalidShaderTests.cs similarity index 83% rename from tests/ComputeSharp.NetCore.Tests/ShaderCompileTests.cs rename to tests/ComputeSharp.NetCore.Tests/InvalidShaderTests.cs index 0043d9f4..a0693718 100644 --- a/tests/ComputeSharp.NetCore.Tests/ShaderCompileTests.cs +++ b/tests/ComputeSharp.NetCore.Tests/InvalidShaderTests.cs @@ -4,8 +4,8 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComputeSharp.NetCore.Tests { [TestClass] - [TestCategory("ShaderCompile")] - public class ShaderTests + [TestCategory("InvalidShader")] + public class InvalidShaderTests { [TestMethod] public void EmptyShaderCompileError() @@ -16,3 +16,4 @@ namespace ComputeSharp.NetCore.Tests } } } + diff --git a/tests/ComputeSharp.NetCore.Tests/ShaderDispatchTests.cs b/tests/ComputeSharp.NetCore.Tests/ShaderDispatchTests.cs new file mode 100644 index 00000000..7e912983 --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/ShaderDispatchTests.cs @@ -0,0 +1,58 @@ +using System; +using System.Linq; +using ComputeSharp.Graphics.Buffers; +using ComputeSharp.NetCore.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.NetCore.Tests +{ + [TestClass] + [TestCategory("ShaderDispatch")] + public class ShaderDispatch + { + [TestMethod] + public void WriteToReadWriteBufferDispatch1D() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(100); + + Action action = id => buffer[id.X] = id.X; + + Gpu.Default.For(100, action); + + float[] array = buffer.GetData(); + float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); + + Assert.IsTrue(array.AsSpan().ContentEquals(expected)); + } + + [TestMethod] + public void WriteToReadWriteBufferDispatch2D() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(100); + + Action action = id => buffer[id.X + id.Y * 10] = id.X + id.Y * 10; + + Gpu.Default.For(10, 10, action); + + float[] array = buffer.GetData(); + float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); + + Assert.IsTrue(array.AsSpan().ContentEquals(expected)); + } + + [TestMethod] + public void WriteToReadWriteBufferDispatch3D() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1000); + + Action action = id => buffer[id.X + id.Y * 10 + id.Z * 100] = id.X + id.Y * 10 + id.Z * 100; + + Gpu.Default.For(10, 10, 10, action); + + float[] array = buffer.GetData(); + float[] expected = Enumerable.Range(0, 1000).Select(i => (float)i).ToArray(); + + Assert.IsTrue(array.AsSpan().ContentEquals(expected)); + } + } +} From af8af0a1026ae13dc669473de90f329036402fa7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 03:19:21 +0200 Subject: [PATCH 08/38] Create README.md --- README.md | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 00000000..5ab5c062 --- /dev/null +++ b/README.md @@ -0,0 +1,83 @@ +![](https://i.imgur.com/ufWcoO6.png) +[![NuGet](https://img.shields.io/nuget/v/ComputeSharp.svg)](https://www.nuget.org/packages/ComputeSharp/) [![NuGet](https://img.shields.io/nuget/dt/ComputeSharp.svg)](https://www.nuget.org/stats/packages/ComputeSharp?groupby=Version) [![Twitter Follow](https://img.shields.io/twitter/follow/Sergio0694.svg?style=flat&label=Follow)](https://twitter.com/SergioPedri) + +# What is it? + +**ComputeSharp** is a .NET Standard 2.0 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders. The available APIs let you allocate GPU buffers and write compute shaders as simple lambda expressions or local methods, with all the captured variables being handled automatically and passed to the running shader. + +# Table of Contents + +- [Installing from NuGet](#installing-from-nuget) +- [Quick start](#quick-start) + - [Capturing variables](#capturing-variables) + - [Advanced usage](#advanced-usage) +- [Requirements](#requirements) + +# Installing from NuGet + +To install **ComputeSharp**, run the following command in the **Package Manager Console** + +``` +Install-Package ComputeSharp +``` + +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. + +The following sample shows how to allocate a writeable buffer, populate it with a compute shader, and read it back. + +```C# +// 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); + +// Get the data back +float[] array = buffer.GetData(); +``` + +## Capturing variables + +If the shader in C# is capturing some local variable, those will be automatically copied over to the GPU, so that the HLSL shader will be able to access them just like you'd expect. Just make sure to only capture valid HLSL types: either scalar types (`int`, `uint`, `float`, etc.), known HLSL structs (eg. `Vector3`) or unmanaged custom structs. + +## 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. + +```C# +int height = 10, width = 10; +float[] x = new float[height * width]; // Array to sum to y +float[] y = new float[height * width]; // Result array (assume both had some values) + +using ReadOnlyBuffer xBuffer = Gpu.Default.AllocateConstantBuffer(x); +using ReadWriteBuffer yBuffer = Gpu.Default.AllocateReadWriteBuffer(y); + +// Shader body +Action action = id => +{ + uint offset = id.X + id.Y * (uint)width; + yBuffer[offset] += xBuffer[offset]; +}; + +// Run the shader +Gpu.Default.For(width, height, action); + +// Get the data back and write it to the y array +yBuffer.GetData(y); +``` + +# Requirements + +The **ComputeSharp** library requires .NET Standard 2.0 support, and it is available for applications targeting: +- .NET Framework >= 4.6.1 +- .NET Core >= 2.0 +- UWP (from SDK 10.0.16299, and only in `Debug` mode for now) + +Additionally, you need an IDE with .NET Core 3.0 and C# 8.0 support to compile the library on your PC. From 8f9a23152bfe3b16e8011b6c60b621646efd8d5e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 03:22:52 +0200 Subject: [PATCH 09/38] Added icon URL to package info --- src/ComputeSharp/ComputeSharp.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj index fea65bb6..9cb9e6f1 100644 --- a/src/ComputeSharp/ComputeSharp.csproj +++ b/src/ComputeSharp/ComputeSharp.csproj @@ -14,6 +14,7 @@ https://github.com/Sergio0694/ComputeSharp https://github.com/Sergio0694/ComputeSharp dotnet net netcore netstandard csharp library graphics shader hlsl compute gpu + https://i.imgur.com/oo8dA0q.png From b2e64b8e69f430629a2fbb968f5178ac6c775cf5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 10:48:56 +0200 Subject: [PATCH 10/38] Added shader closure tests (2 failing) --- .../ShaderClosureTests.cs | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs diff --git a/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs b/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs new file mode 100644 index 00000000..3220a518 --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs @@ -0,0 +1,85 @@ +using System; +using System.Linq; +using System.Numerics; +using ComputeSharp.Graphics.Buffers; +using ComputeSharp.NetCore.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.NetCore.Tests +{ + [TestClass] + [TestCategory("ShaderClosure")] + public class ShaderClosureTests + { + [TestMethod] + public void LocalScalarAssignToBuffer() + { + float value = 10; + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + Action action = id => buffer[0] = value; + + Gpu.Default.For(1, action); + + float[] result = buffer.GetData(); + + Assert.IsTrue((int)result[0] == (int)value); + } + + [TestMethod] + public void LocalKnownVectorAssignToBuffer() + { + Vector4 vector4 = new Vector4(1, 2, 3, 4); + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(4); + + Action action = id => + { + if (id.X == 0) buffer[0] = vector4.X; + else if (id.X == 1) buffer[1] = vector4.Y; + else if (id.X == 2) buffer[2] = vector4.Z; + else if (id.X == 3) buffer[3] = vector4.W; + }; + + Gpu.Default.For(1, action); + + float[] result = buffer.GetData(); + float[] expected = { 1, 2, 3, 4 }; + + Assert.IsTrue(result.AsSpan().ContentEquals(expected)); + } + + [TestMethod] + public void CopyBetweenWriteableBuffers() + { + float[] source = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); + + using ReadWriteBuffer input = Gpu.Default.AllocateReadWriteBuffer(source); + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(source.Length); + + Action action = id => buffer[id.X] = input[id.X]; + + Gpu.Default.For(source.Length, action); + + float[] result = buffer.GetData(); + + Assert.IsTrue(result.AsSpan().ContentEquals(source)); + } + + [TestMethod] + public void CopyBetweenReadOnlyAndWriteableBuffers() + { + float[] source = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); + + using ReadOnlyBuffer input = Gpu.Default.AllocateConstantBuffer(source); + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(source.Length); + + Action action = id => buffer[id.X] = input[id.X]; + + Gpu.Default.For(source.Length, action); + + float[] result = buffer.GetData(); + + Assert.IsTrue(result.AsSpan().ContentEquals(source)); + } + } +} From a93bcc807c1e8eb924f1c559b943cf00287d2c84 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 10:51:57 +0200 Subject: [PATCH 11/38] Renamed some public APIs --- .../Buffers/Extensions/BufferExtensions.cs | 10 +++++----- tests/ComputeSharp.NetCore.Tests/BufferTests.cs | 2 +- tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs b/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs index 28dc83ff..33e0fe69 100644 --- a/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs +++ b/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs @@ -83,9 +83,9 @@ namespace ComputeSharp /// A constant instance with the contents of the input array [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlyBuffer AllocateConstantBuffer(this GraphicsDevice device, T[] array) where T : unmanaged + public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, T[] array) where T : unmanaged { - return device.AllocateConstantBuffer(array.AsSpan()); + return device.AllocateReadOnlyBuffer(array.AsSpan()); } /// @@ -97,12 +97,12 @@ namespace ComputeSharp /// A constant instance with the contents of the input 2D array [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe ReadOnlyBuffer AllocateConstantBuffer(this GraphicsDevice device, T[,] array) where T : unmanaged + public static unsafe ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, T[,] array) where T : unmanaged { fixed (T* p = array) { Span span = new Span(p, array.Length); - return device.AllocateConstantBuffer(span); + return device.AllocateReadOnlyBuffer(span); } } @@ -115,7 +115,7 @@ namespace ComputeSharp /// A constant instance with the contents of the input [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlyBuffer AllocateConstantBuffer(this GraphicsDevice device, Span span) where T : unmanaged + public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, Span span) where T : unmanaged { ReadOnlyBuffer buffer = new ReadOnlyBuffer(device, span.Length); buffer.SetData(span); diff --git a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs index fea3f1ed..90300354 100644 --- a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs +++ b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs @@ -27,7 +27,7 @@ namespace ComputeSharp.NetCore.Tests float[] array = new float[4096]; array.AsSpan().FillRandom(); - using ReadOnlyBuffer buffer = Gpu.Default.AllocateConstantBuffer(array); + using ReadOnlyBuffer buffer = Gpu.Default.AllocateReadOnlyBuffer(array); float[] result = buffer.GetData(); Assert.IsTrue(array.AsSpan().ContentEquals(result)); diff --git a/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs b/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs index 3220a518..8cc81f59 100644 --- a/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs +++ b/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs @@ -70,7 +70,7 @@ namespace ComputeSharp.NetCore.Tests { float[] source = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); - using ReadOnlyBuffer input = Gpu.Default.AllocateConstantBuffer(source); + using ReadOnlyBuffer input = Gpu.Default.AllocateReadOnlyBuffer(source); using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(source.Length); Action action = id => buffer[id.X] = input[id.X]; From ee96c29f83445680f38fb9dfd0c1c3dde22d5bdd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 11:07:23 +0200 Subject: [PATCH 12/38] Updated mustache template for readonly buffers --- .../Renderer/Models/Fields/ConstantBufferFieldInfo.cs | 11 +++++++++-- .../Renderer/Templates/ShaderTemplate.mustache | 2 +- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs index 1f8c3160..4dbeeb51 100644 --- a/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs +++ b/src/ComputeSharp.Shaders/Renderer/Models/Fields/ConstantBufferFieldInfo.cs @@ -12,10 +12,15 @@ namespace ComputeSharp.Shaders.Renderer.Models.Fields /// public bool IsConstantBuffer { get; } = true; + /// + /// Gets whether or not this constant buffer actually contains a single, explicit variable + /// + public bool IsSingleValue { get; } + /// /// Gets the index of the current constant buffer field /// - public int ConstantBufferIndex { get; set; } + public int ConstantBufferIndex { get; } /// /// Creates a new instance with the specified parameters @@ -23,9 +28,11 @@ namespace ComputeSharp.Shaders.Renderer.Models.Fields /// The type of the current field /// The name of the current field /// The index of the current constant buffer field - public ConstantBufferFieldInfo(string fieldType, string fieldName, int bufferIndex) : base(fieldType, fieldName) + /// Whether or not this constant buffer actually contains a single, explicit variable + public ConstantBufferFieldInfo(string fieldType, string fieldName, int bufferIndex, bool singleValue) : base(fieldType, fieldName) { ConstantBufferIndex = bufferIndex; + IsSingleValue = singleValue; } } } diff --git a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache index eee11e3e..70165909 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}}; +{{&FieldType}} {{FieldName}}{{^IsSingleValue}}[2]{{/IsSingleValue}}; } {{/IsConstantBuffer}} {{!Read write buffer}} From 17e0be458f37513e14a07d45fe41fdc12585c7f1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 11:11:53 +0200 Subject: [PATCH 13/38] Added support for readonly buffers --- .../Mappings/HlslKnownTypes.cs | 9 +++++++++ .../Translation/ShaderLoader.cs | 14 ++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs index 32bf790d..aa25cae0 100644 --- a/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs @@ -62,6 +62,15 @@ namespace ComputeSharp.Shaders.Mappings public static bool IsReadWriteBufferType(Type type) => type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ReadWriteBuffer<>); + /// + /// Checks whether or not the input type is a value + /// + /// The input instance to check + /// A indicating whether the input is in fact a instance + [Pure] + public static bool IsReadOnlyBufferType(Type type) => type.IsGenericType && + type.GetGenericTypeDefinition() == typeof(ReadOnlyBuffer<>); + /// /// Checks whether or not a given is an HLSL known type /// diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index 40859c0d..8039ddfb 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -107,7 +107,9 @@ namespace ComputeSharp.Shaders.Translation List descriptorRanges = new List(); List readWriteBuffers = new List(); + List readOnlyBuffers = new List(); int readWriteBuffersCount = 0; + int readOnlyBuffersCount = 0; foreach (FieldInfo fieldInfo in ShaderFields) { @@ -129,6 +131,18 @@ namespace ComputeSharp.Shaders.Translation string typeName = HlslKnownTypes.GetMappedName(fieldType); processedFieldInfo = new ReadWriteBufferFieldInfo(typeName, fieldName, readWriteBuffersCount++); } + else if (HlslKnownTypes.IsReadOnlyBufferType(fieldType)) + { + // Read only buffer + DescriptorRange range = new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, readOnlyBuffersCount); + descriptorRanges.Add(range); + + // Reference to the underlying buffer + readOnlyBuffers.Add((GraphicsResource)fieldValue); + + string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); + processedFieldInfo = new ConstantBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++, true); + } else if (HlslKnownTypes.IsKnownScalarType(fieldType)) { // Static scalar field From 50b754ac687580401409494ea346761e9b2d82bc Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 11:13:07 +0200 Subject: [PATCH 14/38] Fixed a bug in the constant buffer HLSL field declaration --- src/ComputeSharp.Shaders/Translation/ShaderLoader.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index 8039ddfb..10c94663 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -141,7 +141,7 @@ namespace ComputeSharp.Shaders.Translation readOnlyBuffers.Add((GraphicsResource)fieldValue); string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); - processedFieldInfo = new ConstantBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++, true); + processedFieldInfo = new ConstantBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++, false); } else if (HlslKnownTypes.IsKnownScalarType(fieldType)) { From cbb828033e2faf423c4dbacffa93f63cc1e39269 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 11:22:13 +0200 Subject: [PATCH 15/38] Fixed readonly buffers initialization --- src/ComputeSharp.Shaders/ShaderRunner.cs | 2 +- .../Translation/ShaderLoader.cs | 13 ++++++------- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs index 1b5cbe0e..150a5c2a 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner.cs @@ -65,7 +65,7 @@ namespace ComputeSharp.Shaders commandList.SetPipelineState(pipelineState); // Load the captured buffers - foreach (var buffer in shaderLoader.ReadWriteBuffers.Select((r, i) => (Resource: r, Index: i))) + foreach (var buffer in shaderLoader.Buffers.Select((r, i) => (Resource: r, Index: i))) { commandList.SetComputeRootDescriptorTable(buffer.Index, buffer.Resource); } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index 10c94663..2272dc18 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -59,9 +59,9 @@ namespace ComputeSharp.Shaders.Translation public RootParameter[] RootParameters { get; private set; } /// - /// Gets the ordered collection of read write buffers used as fields in the current shader + /// Gets the ordered collection of buffers used as fields in the current shader /// - public IReadOnlyList ReadWriteBuffers { get; private set; } + public IReadOnlyList Buffers { get; private set; } private readonly List _FieldsInfo = new List(); @@ -106,8 +106,7 @@ namespace ComputeSharp.Shaders.Translation if (ShaderFields.Any(fieldInfo => fieldInfo.IsStatic)) throw new InvalidOperationException("Empty shader body"); List descriptorRanges = new List(); - List readWriteBuffers = new List(); - List readOnlyBuffers = new List(); + List buffers = new List(); int readWriteBuffersCount = 0; int readOnlyBuffersCount = 0; @@ -126,7 +125,7 @@ namespace ComputeSharp.Shaders.Translation descriptorRanges.Add(range); // Reference to the underlying buffer - readWriteBuffers.Add((GraphicsResource)fieldValue); + buffers.Add((GraphicsResource)fieldValue); string typeName = HlslKnownTypes.GetMappedName(fieldType); processedFieldInfo = new ReadWriteBufferFieldInfo(typeName, fieldName, readWriteBuffersCount++); @@ -138,7 +137,7 @@ namespace ComputeSharp.Shaders.Translation descriptorRanges.Add(range); // Reference to the underlying buffer - readOnlyBuffers.Add((GraphicsResource)fieldValue); + buffers.Add((GraphicsResource)fieldValue); string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); processedFieldInfo = new ConstantBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++, false); @@ -155,7 +154,7 @@ namespace ComputeSharp.Shaders.Translation } RootParameters = descriptorRanges.Select(range => new RootParameter(ShaderVisibility.All, range)).ToArray(); - ReadWriteBuffers = readWriteBuffers; + Buffers = buffers; } /// From 8699e037e7d59e61ecaa2a22d3af9dd48f2073f8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 11:34:48 +0200 Subject: [PATCH 16/38] Refactored some tests, removed unnecessary code --- .../ComputeSharp.NetCore.Tests/BufferTests.cs | 7 ++--- .../Extensions/SpanExtensions.cs | 15 ---------- .../Extensions/Types/ConcurrentRandom.cs | 28 ------------------- 3 files changed, 3 insertions(+), 47 deletions(-) delete mode 100644 tests/ComputeSharp.NetCore.Tests/Extensions/Types/ConcurrentRandom.cs diff --git a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs index 90300354..444778cd 100644 --- a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs +++ b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using ComputeSharp.Graphics.Buffers; using ComputeSharp.NetCore.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -12,8 +13,7 @@ namespace ComputeSharp.NetCore.Tests [TestMethod] public void ReadWriteBufferGetSetData() { - float[] array = new float[4096]; - array.AsSpan().FillRandom(); + float[] array = Enumerable.Range(0, 4096).Select(i => (float)i).ToArray(); using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(array); float[] result = buffer.GetData(); @@ -24,8 +24,7 @@ namespace ComputeSharp.NetCore.Tests [TestMethod] public void ReadOnlyBufferGetSetData() { - float[] array = new float[4096]; - array.AsSpan().FillRandom(); + float[] array = Enumerable.Range(0, 4096).Select(i => (float)i).ToArray(); using ReadOnlyBuffer buffer = Gpu.Default.AllocateReadOnlyBuffer(array); float[] result = buffer.GetData(); diff --git a/tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs b/tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs index bb52f8be..11ec9ddf 100644 --- a/tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs +++ b/tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs @@ -9,21 +9,6 @@ namespace ComputeSharp.NetCore.Tests.Extensions /// public static class SpanExtensions { - /// - /// Fills an input instance with random values - /// - /// The target to fill - public static void FillRandom(this Span span) - { - if (span.Length == 0) return; - - var l = span.Length; - ref var rspan = ref span.GetPinnableReference(); - - for (var i = 0; i < l; i++) - Unsafe.Add(ref rspan, i) = (float)ConcurrentRandom.Instance.NextDouble(); - } - /// /// The maximum threshold to validate two values as being equal /// diff --git a/tests/ComputeSharp.NetCore.Tests/Extensions/Types/ConcurrentRandom.cs b/tests/ComputeSharp.NetCore.Tests/Extensions/Types/ConcurrentRandom.cs deleted file mode 100644 index 5cbd72c0..00000000 --- a/tests/ComputeSharp.NetCore.Tests/Extensions/Types/ConcurrentRandom.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Runtime.CompilerServices; -using System.Threading; - -namespace System -{ - /// - /// A thread-safe wrapper class - /// - public static class ConcurrentRandom - { - // Shared seed - private static int _Seed = Environment.TickCount; - - /// - /// The object that provides the instances - /// - private static readonly ThreadLocal _Instance = new ThreadLocal(() => new Random(Interlocked.Increment(ref _Seed))); - - /// - /// Gets a thread-safe instance - /// - public static Random Instance - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => _Instance.Value; - } - } -} \ No newline at end of file From 17ea1a0f71198fdb8e795197b47a2ab91540f58c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 12:13:59 +0200 Subject: [PATCH 17/38] Added Gpu.QueryAll method to list all available GPUs --- src/ComputeSharp.Graphics/GraphicsDevice.cs | 39 +++++++++++++++++++-- src/ComputeSharp/Gpu.cs | 24 +++++++++++-- 2 files changed, 58 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.Graphics/GraphicsDevice.cs b/src/ComputeSharp.Graphics/GraphicsDevice.cs index 8aeb3983..ef34aa7e 100644 --- a/src/ComputeSharp.Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp.Graphics/GraphicsDevice.cs @@ -2,6 +2,8 @@ using System.Threading; using SharpDX.Direct3D; using SharpDX.Direct3D12; +using SharpDX.DXGI; +using Device = SharpDX.Direct3D12.Device; namespace ComputeSharp.Graphics { @@ -9,12 +11,21 @@ namespace ComputeSharp.Graphics { private readonly AutoResetEvent fenceEvent = new AutoResetEvent(false); - public GraphicsDevice(bool enableDebugLayer = false) + /// + /// Creates a new instance for the default GPU on the current machine + /// + public GraphicsDevice() : this(new Device(null, FeatureLevel)) { } + + /// + /// Creates a new instance for the input + /// + /// The to use for the new instance + private GraphicsDevice(Device device) { #if DEBUG - if (enableDebugLayer) DebugInterface.Get().EnableDebugLayer(); + DebugInterface.Get().EnableDebugLayer(); #endif - NativeDevice = new Device(null, FeatureLevel); + NativeDevice = device; WavefrontSize = NativeDevice.D3D12Options1.WaveLaneCountMin; NativeComputeCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Compute)); @@ -41,6 +52,28 @@ namespace ComputeSharp.Graphics CopyCommandList.Close(); } + /// + /// Tries to create a new instance from the input object + /// + /// The input for the current GPU being targeted + /// The resulting value, in case of success + /// A value indicating whether or not the resulting device was created correctly + public static bool TryGetFromAdapter(Adapter adapter, out GraphicsDevice? result) + { + try + { + Device device = new Device(adapter, FeatureLevel); + result = new GraphicsDevice(device); + + return true; + } + catch + { + result = null; + return false; + } + } + /// /// Gets the number of lanes in a SIMD wave on the current device (also known as "wavefront size" or "warp width") /// diff --git a/src/ComputeSharp/Gpu.cs b/src/ComputeSharp/Gpu.cs index 7af82c16..4603fb0a 100644 --- a/src/ComputeSharp/Gpu.cs +++ b/src/ComputeSharp/Gpu.cs @@ -1,4 +1,7 @@ -using ComputeSharp.Graphics; +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using ComputeSharp.Graphics; +using SharpDX.DXGI; namespace ComputeSharp { @@ -12,6 +15,23 @@ namespace ComputeSharp /// /// Gets the default instance for the current machine /// - public static GraphicsDevice Default => _Default ??= new GraphicsDevice(true); + public static GraphicsDevice Default => _Default ??= new GraphicsDevice(); + + /// + /// Gets a collection of all the supported graphics devices on the current machine + /// + /// The collection of objects with support for DX12.1 + [Pure] + public static IReadOnlyList QueryAll() + { + using Factory factory = new Factory1(); + List devices = new List(); + + foreach (Adapter adapter in factory.Adapters) + if (GraphicsDevice.TryGetFromAdapter(adapter, out GraphicsDevice? device)) + devices.Add(device!); + + return devices; + } } } From ac5ed0ed6085cb906af47213c6abdb56b44d3b05 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 12:42:03 +0200 Subject: [PATCH 18/38] Added new APIs to the GPU class --- src/ComputeSharp.Graphics/GraphicsDevice.cs | 7 +-- src/ComputeSharp/Gpu.cs | 52 +++++++++++++++++---- 2 files changed, 45 insertions(+), 14 deletions(-) diff --git a/src/ComputeSharp.Graphics/GraphicsDevice.cs b/src/ComputeSharp.Graphics/GraphicsDevice.cs index ef34aa7e..99a86fb7 100644 --- a/src/ComputeSharp.Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp.Graphics/GraphicsDevice.cs @@ -11,16 +11,11 @@ namespace ComputeSharp.Graphics { private readonly AutoResetEvent fenceEvent = new AutoResetEvent(false); - /// - /// Creates a new instance for the default GPU on the current machine - /// - public GraphicsDevice() : this(new Device(null, FeatureLevel)) { } - /// /// Creates a new instance for the input /// /// The to use for the new instance - private GraphicsDevice(Device device) + public GraphicsDevice(Device device) { #if DEBUG DebugInterface.Get().EnableDebugLayer(); diff --git a/src/ComputeSharp/Gpu.cs b/src/ComputeSharp/Gpu.cs index 4603fb0a..960b115c 100644 --- a/src/ComputeSharp/Gpu.cs +++ b/src/ComputeSharp/Gpu.cs @@ -1,7 +1,10 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Diagnostics.Contracts; +using System.Linq; using ComputeSharp.Graphics; using SharpDX.DXGI; +using Device = SharpDX.Direct3D12.Device; namespace ComputeSharp { @@ -10,26 +13,59 @@ namespace ComputeSharp /// public static class Gpu { + /// + /// Gets whether or not the APIs can be used on the current machine (ie. if there is at least a supported GPU device) + /// + public static bool IsSupported { get; } = (_Devices = QueryAllSupportedDevices()).Any(); + private static GraphicsDevice _Default; /// /// Gets the default instance for the current machine /// - public static GraphicsDevice Default => _Default ??= new GraphicsDevice(); + public static GraphicsDevice Default + { + get + { + if (!IsSupported) throw new NotSupportedException("There isn't a supported GPU device on the current machine"); + + return _Default ??= new GraphicsDevice(_Devices.First()); + } + } /// - /// Gets a collection of all the supported graphics devices on the current machine + /// Enumerates all the available objects on the current machine /// - /// The collection of objects with support for DX12.1 + /// A sequence of supported objects that can be used to run compute shaders [Pure] - public static IReadOnlyList QueryAll() + public static IEnumerable EnumerateDevices() => _Devices.Select(device => new GraphicsDevice(device)); + + // The loaded collection of supported devices + private static IReadOnlyList _Devices; + + /// + /// Gets a collection of all the supported devices on the current machine + /// + /// The collection of objects with support for DX12.1 + [Pure] + private static IReadOnlyList QueryAllSupportedDevices() { using Factory factory = new Factory1(); - List devices = new List(); + List devices = new List(); foreach (Adapter adapter in factory.Adapters) - if (GraphicsDevice.TryGetFromAdapter(adapter, out GraphicsDevice? device)) - devices.Add(device!); + { + if (adapter.Description.DedicatedVideoMemory == 0) continue; + try + { + Device device = new Device(adapter, GraphicsDevice.FeatureLevel); + devices.Add(device); + } + catch + { + // Unsupported device + } + } return devices; } From 46e8fd6b153128f1bf7f9a06c4ec1f9ccba3d639 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 12:44:53 +0200 Subject: [PATCH 19/38] Code refactoring --- .../Helpers/DeviceHelper.cs | 40 +++++++++++++++++++ src/ComputeSharp/Gpu.cs | 31 +------------- 2 files changed, 42 insertions(+), 29 deletions(-) create mode 100644 src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs diff --git a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs new file mode 100644 index 00000000..c7052482 --- /dev/null +++ b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs @@ -0,0 +1,40 @@ +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using SharpDX.DXGI; +using Device = SharpDX.Direct3D12.Device; + +namespace ComputeSharp.Graphics.Helpers +{ + /// + /// A with methods to inspect the available devices on the current machine + /// + public static class DeviceHelper + { + /// + /// Gets a collection of all the supported devices on the current machine + /// + /// The collection of objects with support for DX12.1 + [Pure] + public static IReadOnlyList QueryAllSupportedDevices() + { + using Factory factory = new Factory1(); + List devices = new List(); + + foreach (Adapter adapter in factory.Adapters) + { + if (adapter.Description.DedicatedVideoMemory == 0) continue; + try + { + Device device = new Device(adapter, GraphicsDevice.FeatureLevel); + devices.Add(device); + } + catch + { + // Unsupported device + } + } + + return devices; + } + } +} diff --git a/src/ComputeSharp/Gpu.cs b/src/ComputeSharp/Gpu.cs index 960b115c..ad3e247f 100644 --- a/src/ComputeSharp/Gpu.cs +++ b/src/ComputeSharp/Gpu.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using ComputeSharp.Graphics; -using SharpDX.DXGI; +using ComputeSharp.Graphics.Helpers; using Device = SharpDX.Direct3D12.Device; namespace ComputeSharp @@ -16,7 +16,7 @@ namespace ComputeSharp /// /// Gets whether or not the APIs can be used on the current machine (ie. if there is at least a supported GPU device) /// - public static bool IsSupported { get; } = (_Devices = QueryAllSupportedDevices()).Any(); + public static bool IsSupported { get; } = (_Devices = DeviceHelper.QueryAllSupportedDevices()).Any(); private static GraphicsDevice _Default; @@ -42,32 +42,5 @@ namespace ComputeSharp // The loaded collection of supported devices private static IReadOnlyList _Devices; - - /// - /// Gets a collection of all the supported devices on the current machine - /// - /// The collection of objects with support for DX12.1 - [Pure] - private static IReadOnlyList QueryAllSupportedDevices() - { - using Factory factory = new Factory1(); - List devices = new List(); - - foreach (Adapter adapter in factory.Adapters) - { - if (adapter.Description.DedicatedVideoMemory == 0) continue; - try - { - Device device = new Device(adapter, GraphicsDevice.FeatureLevel); - devices.Add(device); - } - catch - { - // Unsupported device - } - } - - return devices; - } } } From f6f73b9e3f514ccf29063a86a742d2a584cc7f95 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 12:50:06 +0200 Subject: [PATCH 20/38] Added device description to the GraphicsDevice class --- src/ComputeSharp.Graphics/GraphicsDevice.cs | 25 ++++--------------- .../Helpers/DeviceHelper.cs | 6 ++--- src/ComputeSharp/Gpu.cs | 7 +++--- 3 files changed, 12 insertions(+), 26 deletions(-) diff --git a/src/ComputeSharp.Graphics/GraphicsDevice.cs b/src/ComputeSharp.Graphics/GraphicsDevice.cs index 99a86fb7..edb771bd 100644 --- a/src/ComputeSharp.Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp.Graphics/GraphicsDevice.cs @@ -15,12 +15,14 @@ namespace ComputeSharp.Graphics /// Creates a new instance for the input /// /// The to use for the new instance - public GraphicsDevice(Device device) + /// The available info for the new instance + public GraphicsDevice(Device device, AdapterDescription description) { #if DEBUG DebugInterface.Get().EnableDebugLayer(); #endif NativeDevice = device; + Description = description; WavefrontSize = NativeDevice.D3D12Options1.WaveLaneCountMin; NativeComputeCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Compute)); @@ -48,26 +50,9 @@ namespace ComputeSharp.Graphics } /// - /// Tries to create a new instance from the input object + /// Gets the available info for the current instance /// - /// The input for the current GPU being targeted - /// The resulting value, in case of success - /// A value indicating whether or not the resulting device was created correctly - public static bool TryGetFromAdapter(Adapter adapter, out GraphicsDevice? result) - { - try - { - Device device = new Device(adapter, FeatureLevel); - result = new GraphicsDevice(device); - - return true; - } - catch - { - result = null; - return false; - } - } + public AdapterDescription Description { get; } /// /// Gets the number of lanes in a SIMD wave on the current device (also known as "wavefront size" or "warp width") diff --git a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs index c7052482..25547e65 100644 --- a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs @@ -15,10 +15,10 @@ namespace ComputeSharp.Graphics.Helpers /// /// The collection of objects with support for DX12.1 [Pure] - public static IReadOnlyList QueryAllSupportedDevices() + public static IReadOnlyList<(Device, AdapterDescription)> QueryAllSupportedDevices() { using Factory factory = new Factory1(); - List devices = new List(); + List<(Device, AdapterDescription)> devices = new List<(Device, AdapterDescription)>(); foreach (Adapter adapter in factory.Adapters) { @@ -26,7 +26,7 @@ namespace ComputeSharp.Graphics.Helpers try { Device device = new Device(adapter, GraphicsDevice.FeatureLevel); - devices.Add(device); + devices.Add((device, adapter.Description)); } catch { diff --git a/src/ComputeSharp/Gpu.cs b/src/ComputeSharp/Gpu.cs index ad3e247f..0bfe9b60 100644 --- a/src/ComputeSharp/Gpu.cs +++ b/src/ComputeSharp/Gpu.cs @@ -4,6 +4,7 @@ using System.Diagnostics.Contracts; using System.Linq; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Helpers; +using SharpDX.DXGI; using Device = SharpDX.Direct3D12.Device; namespace ComputeSharp @@ -29,7 +30,7 @@ namespace ComputeSharp { if (!IsSupported) throw new NotSupportedException("There isn't a supported GPU device on the current machine"); - return _Default ??= new GraphicsDevice(_Devices.First()); + return _Default ??= new GraphicsDevice(_Devices[0].Device, _Devices[0].Description); } } @@ -38,9 +39,9 @@ namespace ComputeSharp /// /// A sequence of supported objects that can be used to run compute shaders [Pure] - public static IEnumerable EnumerateDevices() => _Devices.Select(device => new GraphicsDevice(device)); + public static IEnumerable EnumerateDevices() => _Devices.Select(device => new GraphicsDevice(device.Device, device.Description)); // The loaded collection of supported devices - private static IReadOnlyList _Devices; + private static IReadOnlyList<(Device Device, AdapterDescription Description)> _Devices; } } From 279d7c372f378b664ba42123782404b07a7f7e4b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 13:10:57 +0200 Subject: [PATCH 21/38] Added GPU initialization tests --- tests/ComputeSharp.NetCore.Tests/MiscTests.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 tests/ComputeSharp.NetCore.Tests/MiscTests.cs diff --git a/tests/ComputeSharp.NetCore.Tests/MiscTests.cs b/tests/ComputeSharp.NetCore.Tests/MiscTests.cs new file mode 100644 index 00000000..76ba23c8 --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/MiscTests.cs @@ -0,0 +1,17 @@ +using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.NetCore.Tests +{ + [TestClass] + [TestCategory("Misc")] + public class MiscTests + { + [TestMethod] + public void CheckIsSupportedAndGetDefaultDevice() + { + if (Gpu.IsSupported) Assert.IsNotNull(Gpu.Default); + else Assert.ThrowsException(() => Gpu.Default); + } + } +} From 666f7e67ded2e6c65346c649c66ed5972eb1f06a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 13:21:03 +0200 Subject: [PATCH 22/38] Fixed a crash when loading a specific GPU device --- src/ComputeSharp.Graphics/GraphicsDevice.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/ComputeSharp.Graphics/GraphicsDevice.cs b/src/ComputeSharp.Graphics/GraphicsDevice.cs index edb771bd..0a6adde2 100644 --- a/src/ComputeSharp.Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp.Graphics/GraphicsDevice.cs @@ -18,9 +18,6 @@ namespace ComputeSharp.Graphics /// The available info for the new instance public GraphicsDevice(Device device, AdapterDescription description) { -#if DEBUG - DebugInterface.Get().EnableDebugLayer(); -#endif NativeDevice = device; Description = description; WavefrontSize = NativeDevice.D3D12Options1.WaveLaneCountMin; From 131bc5fdce71507ec5434eea49c75a5e4c685165 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 13:21:14 +0200 Subject: [PATCH 23/38] Added test for multi GPU --- .../InitializationTests.cs | 42 +++++++++++++++++++ tests/ComputeSharp.NetCore.Tests/MiscTests.cs | 17 -------- 2 files changed, 42 insertions(+), 17 deletions(-) create mode 100644 tests/ComputeSharp.NetCore.Tests/InitializationTests.cs delete mode 100644 tests/ComputeSharp.NetCore.Tests/MiscTests.cs diff --git a/tests/ComputeSharp.NetCore.Tests/InitializationTests.cs b/tests/ComputeSharp.NetCore.Tests/InitializationTests.cs new file mode 100644 index 00000000..4e3b4c0f --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/InitializationTests.cs @@ -0,0 +1,42 @@ +using System; +using System.Linq; +using ComputeSharp.Graphics; +using ComputeSharp.Graphics.Buffers; +using ComputeSharp.NetCore.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.NetCore.Tests +{ + [TestClass] + [TestCategory("Initialization")] + public class InitializationTests + { + [TestMethod] + public void CheckIsSupportedAndGetDefaultDevice() + { + if (Gpu.IsSupported) Assert.IsNotNull(Gpu.Default); + else Assert.ThrowsException(() => Gpu.Default); + } + + [TestMethod] + public void RunShaderOnAllDevices() + { + foreach (GraphicsDevice gpu in Gpu.EnumerateDevices()) + { + using (ReadWriteBuffer buffer = gpu.AllocateReadWriteBuffer(100)) + { + Action action = id => buffer[id.X] = id.X; + + gpu.For(100, action); + + float[] array = buffer.GetData(); + float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); + + Assert.IsTrue(array.AsSpan().ContentEquals(expected)); + } + + gpu.Dispose(); + } + } + } +} diff --git a/tests/ComputeSharp.NetCore.Tests/MiscTests.cs b/tests/ComputeSharp.NetCore.Tests/MiscTests.cs deleted file mode 100644 index 76ba23c8..00000000 --- a/tests/ComputeSharp.NetCore.Tests/MiscTests.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace ComputeSharp.NetCore.Tests -{ - [TestClass] - [TestCategory("Misc")] - public class MiscTests - { - [TestMethod] - public void CheckIsSupportedAndGetDefaultDevice() - { - if (Gpu.IsSupported) Assert.IsNotNull(Gpu.Default); - else Assert.ThrowsException(() => Gpu.Default); - } - } -} From 8783035ad597d946f5b33463e73529b19d411ae5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 15:40:08 +0200 Subject: [PATCH 24/38] Added support for local methods to define shaders --- .../Translation/MethodDecompiler.cs | 13 +++++++++++-- .../Translation/ShaderLoader.cs | 2 +- .../ShaderClosureTests.cs | 15 +++++++++++++++ 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs index 20c2a95a..9a5682c3 100644 --- a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs @@ -6,6 +6,7 @@ using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; +using System.Text.RegularExpressions; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.CSharp; using ICSharpCode.Decompiler.Metadata; @@ -97,6 +98,11 @@ namespace ComputeSharp.Shaders.Translation } } + /// + /// A uused to preprocess the entry point declaration for both lambda expressions and local methods + /// + private static readonly Regex LambdaMethodDeclarationRegex = new Regex(@"^(private|internal) void <\w+>[\w_|]+(?=\()", RegexOptions.Compiled); + /// /// Decompiles a target method and returns its and info /// @@ -117,10 +123,13 @@ namespace ComputeSharp.Shaders.Translation Decompilers.Add(assemblyPath, decompiler); } - string sourceCode = decompiler.DecompileAsString(methodHandle); + // Decompile the method source and fix the method declaration for local methods converted to lambdas + string + sourceCode = decompiler.DecompileAsString(methodHandle), + fixedCode = LambdaMethodDeclarationRegex.Replace(sourceCode, "internal void Main"); // Load the method syntax tree - SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode); + SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(fixedCode); rootNode = syntaxTree.GetRoot(); // Update the incremental compilation and retrieve the syntax tree for the method diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index 40859c0d..8b9e43eb 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -157,7 +157,7 @@ namespace ComputeSharp.Shaders.Translation root = syntaxRewriter.Visit(root); // Get the thread ids identifier name and shader method body - ConstructorDeclarationSyntax methodNode = root.ChildNodes().OfType().First(); + MethodDeclarationSyntax methodNode = root.ChildNodes().OfType().First(); ThreadsIdsVariableName = methodNode.ParameterList.Parameters.First().Identifier.Text; MethodBody = methodNode.Body.ToFullString(); diff --git a/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs b/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs index 8cc81f59..18bad3b9 100644 --- a/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs +++ b/tests/ComputeSharp.NetCore.Tests/ShaderClosureTests.cs @@ -26,6 +26,21 @@ namespace ComputeSharp.NetCore.Tests Assert.IsTrue((int)result[0] == (int)value); } + [TestMethod] + public void LocalScalarAssignToBufferWithinLocalMethod() + { + float value = 10; + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + void Foo(ThreadIds id) => buffer[0] = value; + + Gpu.Default.For(1, Foo); + + float[] result = buffer.GetData(); + + Assert.IsTrue((int)result[0] == (int)value); + } + [TestMethod] public void LocalKnownVectorAssignToBuffer() { From 6b603b61a5860390bde3880f8b689fd1ddf3cd6f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 15:42:47 +0200 Subject: [PATCH 25/38] Added DoNotParallelize attribute to the test assembly --- tests/ComputeSharp.NetCore.Tests/Properties/AssemblyInfo.cs | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 tests/ComputeSharp.NetCore.Tests/Properties/AssemblyInfo.cs diff --git a/tests/ComputeSharp.NetCore.Tests/Properties/AssemblyInfo.cs b/tests/ComputeSharp.NetCore.Tests/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..8ed86d91 --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/Properties/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[assembly: DoNotParallelize] From a68ad249292acd24b268147e6061a39e3f2ea767 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 16:16:51 +0200 Subject: [PATCH 26/38] Added HlslBuffer class --- .../Buffers/Abstract/HlslBuffer{T}.cs | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs new file mode 100644 index 00000000..1d8fa479 --- /dev/null +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs @@ -0,0 +1,47 @@ +using System; +using System.Diagnostics.Contracts; +using SharpDX.Direct3D12; + +namespace ComputeSharp.Graphics.Buffers.Abstract +{ + /// + /// A representing a typed buffer stored on GPU memory, that can be used from an HLSL shader + /// + /// The type of items stored on the buffer + public abstract class HlslBuffer : Buffer where T : unmanaged + { + /// + /// Creates a new instance with the specified parameters + /// + /// The associated with the current instance + /// The number of items to store in the current buffer + /// The size in bytes for the current buffer + /// The heap type for the current buffer + protected internal HlslBuffer(GraphicsDevice device, int size, int sizeInBytes, HeapType heapType) : base(device, size, sizeInBytes, heapType) { } + + /// + /// Reads the contents of the current instance and returns an array + /// + /// A array with the contents of the current buffer + [Pure] + public T[] GetData() + { + T[] data = new T[Size]; + GetData(data); + + return data; + } + + /// + /// Reads the contents of the current instance and writes them into a target + /// + /// The input to write data to + public abstract void GetData(Span span); + + /// + /// Writes the contents of a given to the current instance + /// + /// The input to read data from + public abstract void SetData(Span span); + } +} From 12198f9943e70b6bc77cb7f6e2c80c0cb1f8dcae Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 16:21:50 +0200 Subject: [PATCH 27/38] Updated buffer types to implement the new architecture --- src/ComputeSharp.Graphics/Buffers/Buffer.cs | 103 ++++-------------- .../Buffers/ReadOnlyBuffer{T}.cs | 26 ++++- .../Buffers/ReadWriteBuffer{T}.cs | 21 +++- 3 files changed, 62 insertions(+), 88 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/Buffer.cs b/src/ComputeSharp.Graphics/Buffers/Buffer.cs index 703bc324..557e8428 100644 --- a/src/ComputeSharp.Graphics/Buffers/Buffer.cs +++ b/src/ComputeSharp.Graphics/Buffers/Buffer.cs @@ -1,8 +1,6 @@ -using System; -using System.Diagnostics.Contracts; +using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Helpers; using SharpDX.Direct3D12; namespace ComputeSharp.Graphics.Buffers @@ -18,12 +16,13 @@ namespace ComputeSharp.Graphics.Buffers /// /// The associated with the current instance /// The number of items to store in the current buffer + /// The size in bytes for the current buffer /// The heap type for the current buffer - protected internal Buffer(GraphicsDevice device, int size, HeapType heapType) : base(device) + protected internal Buffer(GraphicsDevice device, int size, int sizeInBytes, HeapType heapType) : base(device) { Size = size; ElementSizeInBytes = Unsafe.SizeOf(); - SizeInBytes = Size * ElementSizeInBytes; + SizeInBytes = sizeInBytes; // Not necessarily a multiple of the element size, as there could be padding HeapType = heapType; ResourceFlags flags = heapType == HeapType.Default ? ResourceFlags.AllowUnorderedAccess : ResourceFlags.None; @@ -45,6 +44,21 @@ namespace ComputeSharp.Graphics.Buffers }; } + /// + /// Gets the size of the current buffer, as in the number of values it contains + /// + public int Size { get; } + + /// + /// Gets the size in bytes of the current buffer + /// + protected int SizeInBytes { get; } + + /// + /// Gets the size in bytes of each value contained in the buffer + /// + protected int ElementSizeInBytes { get; } + /// /// Creates the descriptors for a constant buffer /// @@ -88,88 +102,9 @@ namespace ComputeSharp.Graphics.Buffers return (cpuHandle, gpuHandle); } - /// - /// Gets the size of the current buffer, as in the number of values it contains - /// - public int Size { get; } - - /// - /// Gets the size in bytes of the current buffer - /// - public int SizeInBytes { get; } - - /// - /// Gets the size in bytes of each value contained in the buffer - /// - public int ElementSizeInBytes { get; } - /// /// Gets the heap type being targeted by the current buffer /// public HeapType HeapType { get; } - - /// - /// Reads the contents of the current instance and returns an array - /// - /// A array with the contents of the current buffer - [Pure] - public T[] GetData() - { - T[] data = new T[Size]; - GetData(data); - - return data; - } - - /// - /// Reads the contents of the current instance and writes them into a target - /// - /// The input to write data to - public void GetData(Span span) - { - // Create a temporary readback buffer if the current buffer type is read write (can't be read from directly) - if (HeapType == HeapType.Default) - { - using Buffer readbackBaffer = new Buffer(GraphicsDevice, Size, HeapType.Readback); - using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); - - copyCommandList.CopyBufferRegion(this, 0, readbackBaffer, 0, SizeInBytes); - copyCommandList.Flush(true); - - readbackBaffer.GetData(span); - } - else - { - // Map and read the memory back directly - Map(0); - MemoryHelper.Copy(MappedResource, span); - Unmap(0); - } - } - - /// - /// Writes the contents of a given to the current instance - /// - /// The input to read data from - public void SetData(Span span) - { - // Create a temporary upload buffer if the current buffer type is read write (can't be written to directly) - if (HeapType == HeapType.Default) - { - using Buffer uploadBuffer = new Buffer(GraphicsDevice, Size, HeapType.Upload); - using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); - - uploadBuffer.SetData(span); - copyCommandList.CopyBufferRegion(uploadBuffer, 0, this, 0, SizeInBytes); - copyCommandList.Flush(true); - } - else - { - // Map and copy the memory directly - Map(0); - MemoryHelper.Copy(span, MappedResource); - Unmap(0); - } - } } } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index c86d4084..f0f2a2a0 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -1,4 +1,6 @@ using System; +using System.Runtime.CompilerServices; +using ComputeSharp.Graphics.Buffers.Abstract; using SharpDX.Direct3D12; namespace ComputeSharp.Graphics.Buffers @@ -7,14 +9,22 @@ namespace ComputeSharp.Graphics.Buffers /// A representing a typed read write buffer stored on GPU memory /// /// The type of items stored on the buffer - public sealed class ReadOnlyBuffer : Buffer where T : unmanaged + public sealed class ReadOnlyBuffer : HlslBuffer where T : unmanaged { /// /// Creates a new instance with the specified parameters /// /// The associated with the current instance /// The number of items to store in the current buffer - internal ReadOnlyBuffer(GraphicsDevice device, int size) : base(device, size, HeapType.Upload) { } + internal ReadOnlyBuffer(GraphicsDevice device, int size) : base(device, size, size * (Unsafe.SizeOf() / 16 + 1), HeapType.Upload) + { + PaddedElementSizeInBytes = SizeInBytes / Size; + } + + /// + /// Gets the size in bytes of the current buffer + /// + private int PaddedElementSizeInBytes { get; } /// /// Gets a single value from the current read write buffer @@ -22,5 +32,17 @@ namespace ComputeSharp.Graphics.Buffers /// The index of the value to get /// This API can only be used from a compute shader, and will always throw if used anywhere else public T this[uint i] => throw new InvalidOperationException("The indexer APIs can only be used from a compute shader"); + + /// + public override void GetData(Span span) + { + throw new NotImplementedException(); + } + + /// + public override void SetData(Span span) + { + throw new NotImplementedException(); + } } } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs index ded6d1e9..2a2a4c9e 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs @@ -1,4 +1,6 @@ using System; +using System.Runtime.CompilerServices; +using ComputeSharp.Graphics.Buffers.Abstract; using SharpDX.Direct3D12; namespace ComputeSharp.Graphics.Buffers @@ -7,14 +9,17 @@ namespace ComputeSharp.Graphics.Buffers /// A representing a typed read write buffer stored on GPU memory /// /// The type of items stored on the buffer - public sealed class ReadWriteBuffer : Buffer where T : unmanaged + public sealed class ReadWriteBuffer : HlslBuffer where T : unmanaged { /// /// Creates a new instance with the specified parameters /// /// The associated with the current instance /// The number of items to store in the current buffer - internal ReadWriteBuffer(GraphicsDevice device, int size) : base(device, size, HeapType.Default) { } + internal ReadWriteBuffer(GraphicsDevice device, int size) : base(device, size, size * Unsafe.SizeOf(), HeapType.Default) + { + + } /// /// Gets or sets a single value from the current read write buffer @@ -26,5 +31,17 @@ namespace ComputeSharp.Graphics.Buffers get => throw new InvalidOperationException("The indexer APIs can only be used from a compute shader"); set => throw new InvalidOperationException("The indexer APIs can only be used from a compute shader"); } + + /// + public override void GetData(Span span) + { + throw new NotImplementedException(); + } + + /// + public override void SetData(Span span) + { + throw new NotImplementedException(); + } } } From 1298f1757a75d1c8eac148c6777208549a3da827 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 16:40:49 +0200 Subject: [PATCH 28/38] Reimplemented get and set methods to read write buffer --- .../Buffers/ReadWriteBuffer{T}.cs | 26 ++++++++++++++----- 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs index 2a2a4c9e..446719b5 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs @@ -1,6 +1,7 @@ using System; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Graphics.Helpers; using SharpDX.Direct3D12; namespace ComputeSharp.Graphics.Buffers @@ -16,10 +17,7 @@ namespace ComputeSharp.Graphics.Buffers /// /// The associated with the current instance /// The number of items to store in the current buffer - internal ReadWriteBuffer(GraphicsDevice device, int size) : base(device, size, size * Unsafe.SizeOf(), HeapType.Default) - { - - } + internal ReadWriteBuffer(GraphicsDevice device, int size) : base(device, size, size * Unsafe.SizeOf(), HeapType.Default) { } /// /// Gets or sets a single value from the current read write buffer @@ -35,13 +33,29 @@ namespace ComputeSharp.Graphics.Buffers /// public override void GetData(Span span) { - throw new NotImplementedException(); + using Buffer readbackBaffer = new Buffer(GraphicsDevice, Size, SizeInBytes, HeapType.Readback); + using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + + copyCommandList.CopyBufferRegion(this, 0, readbackBaffer, 0, SizeInBytes); + copyCommandList.Flush(true); + + readbackBaffer.Map(0); + MemoryHelper.Copy(readbackBaffer.MappedResource, span); + readbackBaffer.Unmap(0); } /// public override void SetData(Span span) { - throw new NotImplementedException(); + using Buffer uploadBuffer = new Buffer(GraphicsDevice, Size, SizeInBytes, HeapType.Upload); + using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + + uploadBuffer.Map(0); + MemoryHelper.Copy(span, uploadBuffer.MappedResource); + uploadBuffer.Unmap(0); + + copyCommandList.CopyBufferRegion(uploadBuffer, 0, this, 0, SizeInBytes); + copyCommandList.Flush(true); } } } From d6d1fc2624e362b9627daa2c8088b8f1ad1a7f46 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 16:55:25 +0200 Subject: [PATCH 29/38] Reimplemented get and set methods to readonly buffer --- .../Buffers/ReadOnlyBuffer{T}.cs | 39 ++++++++++++++++++- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index f0f2a2a0..5ede775c 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -1,6 +1,8 @@ using System; +using System.Buffers; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Graphics.Helpers; using SharpDX.Direct3D12; namespace ComputeSharp.Graphics.Buffers @@ -36,13 +38,46 @@ namespace ComputeSharp.Graphics.Buffers /// public override void GetData(Span span) { - throw new NotImplementedException(); + byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); + Span temporarySpan = temporaryArray.AsSpan(); + + Map(0); + MemoryHelper.Copy(MappedResource, temporarySpan); + Unmap(0); + + ref byte tin = ref temporarySpan.GetPinnableReference(); + ref T tout = ref span.GetPinnableReference(); + + for (int i = 0; i < Size; i++) + { + ref byte rsource = ref Unsafe.Add(ref tin, i * PaddedElementSizeInBytes); + Unsafe.Add(ref tout, i) = Unsafe.As(ref rsource); + } + + ArrayPool.Shared.Return(temporaryArray); } /// public override void SetData(Span span) { - throw new NotImplementedException(); + byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); + Span temporarySpan = temporaryArray.AsSpan(); + ref T tin = ref span.GetPinnableReference(); + ref byte tout = ref temporarySpan.GetPinnableReference(); + + temporarySpan.Clear(); + + for (int i = 0; i < Size; i++) + { + ref byte rtarget = ref Unsafe.Add(ref tout, i * PaddedElementSizeInBytes); + Unsafe.As(ref rtarget) = Unsafe.Add(ref tin, i); + } + + Map(0); + MemoryHelper.Copy(temporarySpan, MappedResource); + Unmap(0); + + ArrayPool.Shared.Return(temporaryArray); } } } From 5ff2b2d4e0381ed6eee264d4b4ad1f2042201207 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 19:50:35 +0200 Subject: [PATCH 30/38] Fixed a bug in the read only buffer initialization --- src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index 5ede775c..2ff26f04 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -18,7 +18,7 @@ namespace ComputeSharp.Graphics.Buffers /// /// The associated with the current instance /// The number of items to store in the current buffer - internal ReadOnlyBuffer(GraphicsDevice device, int size) : base(device, size, size * (Unsafe.SizeOf() / 16 + 1), HeapType.Upload) + internal ReadOnlyBuffer(GraphicsDevice device, int size) : base(device, size, size * (Unsafe.SizeOf() / 16 + 1) * 16, HeapType.Upload) { PaddedElementSizeInBytes = SizeInBytes / Size; } @@ -61,7 +61,7 @@ namespace ComputeSharp.Graphics.Buffers public override void SetData(Span span) { byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); - Span temporarySpan = temporaryArray.AsSpan(); + Span temporarySpan = temporaryArray.AsSpan(0, SizeInBytes); // Array pool arrays can be longer ref T tin = ref span.GetPinnableReference(); ref byte tout = ref temporarySpan.GetPinnableReference(); From 96232a95384fdfc158a2edfc7b5b412c5d47de71 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 21:15:33 +0200 Subject: [PATCH 31/38] Readonly buffer optimized when no padding is needed --- .../Buffers/ReadOnlyBuffer{T}.cs | 82 ++++++++++++------- 1 file changed, 54 insertions(+), 28 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index 2ff26f04..04a7d5c9 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -38,46 +38,72 @@ namespace ComputeSharp.Graphics.Buffers /// public override void GetData(Span span) { - byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); - Span temporarySpan = temporaryArray.AsSpan(); - - Map(0); - MemoryHelper.Copy(MappedResource, temporarySpan); - Unmap(0); - - ref byte tin = ref temporarySpan.GetPinnableReference(); - ref T tout = ref span.GetPinnableReference(); - - for (int i = 0; i < Size; i++) + // Directly copy the data back if there is no padding + if (PaddedElementSizeInBytes == ElementSizeInBytes) { - ref byte rsource = ref Unsafe.Add(ref tin, i * PaddedElementSizeInBytes); - Unsafe.Add(ref tout, i) = Unsafe.As(ref rsource); + Map(0); + MemoryHelper.Copy(MappedResource, span); + Unmap(0); } + else + { + // Create the temporary array + byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); + Span temporarySpan = temporaryArray.AsSpan(); - ArrayPool.Shared.Return(temporaryArray); + // Copy the padded data to the temporary array + Map(0); + MemoryHelper.Copy(MappedResource, temporarySpan); + Unmap(0); + + ref byte tin = ref temporarySpan.GetPinnableReference(); + ref T tout = ref span.GetPinnableReference(); + + // Copy the padded data to the target span, removing the padding + for (int i = 0; i < Size; i++) + { + ref byte rsource = ref Unsafe.Add(ref tin, i * PaddedElementSizeInBytes); + Unsafe.Add(ref tout, i) = Unsafe.As(ref rsource); + } + + ArrayPool.Shared.Return(temporaryArray); + } } /// public override void SetData(Span span) { - byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); - Span temporarySpan = temporaryArray.AsSpan(0, SizeInBytes); // Array pool arrays can be longer - ref T tin = ref span.GetPinnableReference(); - ref byte tout = ref temporarySpan.GetPinnableReference(); - - temporarySpan.Clear(); - - for (int i = 0; i < Size; i++) + // Directly copy the input span if there is no padding + if (PaddedElementSizeInBytes == ElementSizeInBytes) { - ref byte rtarget = ref Unsafe.Add(ref tout, i * PaddedElementSizeInBytes); - Unsafe.As(ref rtarget) = Unsafe.Add(ref tin, i); + Map(0); + MemoryHelper.Copy(span, MappedResource); + Unmap(0); } + else + { + // Create the temporary array + byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); + Span temporarySpan = temporaryArray.AsSpan(0, SizeInBytes); // Array pool arrays can be longer + ref T tin = ref span.GetPinnableReference(); + ref byte tout = ref temporarySpan.GetPinnableReference(); - Map(0); - MemoryHelper.Copy(temporarySpan, MappedResource); - Unmap(0); + temporarySpan.Clear(); - ArrayPool.Shared.Return(temporaryArray); + // Copy the input data to the temporary array and add the padding + for (int i = 0; i < Size; i++) + { + ref byte rtarget = ref Unsafe.Add(ref tout, i * PaddedElementSizeInBytes); + Unsafe.As(ref rtarget) = Unsafe.Add(ref tin, i); + } + + // Copy the padded data to the GPU + Map(0); + MemoryHelper.Copy(temporarySpan, MappedResource); + Unmap(0); + + ArrayPool.Shared.Return(temporaryArray); + } } } } From 244b3535d46fd1f47d5271b05703cfe678fcd05e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 21:16:17 +0200 Subject: [PATCH 32/38] Removed unnecessary buffer cleanup operation --- src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index 04a7d5c9..52427119 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -88,8 +88,6 @@ namespace ComputeSharp.Graphics.Buffers ref T tin = ref span.GetPinnableReference(); ref byte tout = ref temporarySpan.GetPinnableReference(); - temporarySpan.Clear(); - // Copy the input data to the temporary array and add the padding for (int i = 0; i < Size; i++) { From 984d1113f820ae0b7ec4ee74823c51ad1a53c8a5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 21:33:52 +0200 Subject: [PATCH 33/38] Added APIs to set buffers from existing buffers --- .../Buffers/Abstract/HlslBuffer{T}.cs | 12 ++++ .../Buffers/ReadOnlyBuffer{T}.cs | 65 ++++++++++++++----- .../Buffers/ReadWriteBuffer{T}.cs | 47 +++++++++++++- 3 files changed, 106 insertions(+), 18 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs index 1d8fa479..34d3befd 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs @@ -43,5 +43,17 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// /// The input to read data from public abstract void SetData(Span span); + + /// + /// Writes the contents of a given to the current instance + /// + /// The input to read data from + public abstract void SetData(ReadOnlyBuffer buffer); + + /// + /// Writes the contents of a given to the current instance + /// + /// The input to read data from + public abstract void SetData(ReadWriteBuffer buffer); } } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index 52427119..4ceeea12 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -21,12 +21,18 @@ namespace ComputeSharp.Graphics.Buffers internal ReadOnlyBuffer(GraphicsDevice device, int size) : base(device, size, size * (Unsafe.SizeOf() / 16 + 1) * 16, HeapType.Upload) { PaddedElementSizeInBytes = SizeInBytes / Size; + IsPaddingPresent = PaddedElementSizeInBytes > ElementSizeInBytes; } /// /// Gets the size in bytes of the current buffer /// - private int PaddedElementSizeInBytes { get; } + internal int PaddedElementSizeInBytes { get; } + + /// + /// Gets whether or not there is some padding between elements in the current buffer + /// + internal bool IsPaddingPresent { get; } /// /// Gets a single value from the current read write buffer @@ -38,14 +44,7 @@ namespace ComputeSharp.Graphics.Buffers /// public override void GetData(Span span) { - // Directly copy the data back if there is no padding - if (PaddedElementSizeInBytes == ElementSizeInBytes) - { - Map(0); - MemoryHelper.Copy(MappedResource, span); - Unmap(0); - } - else + if (IsPaddingPresent) { // Create the temporary array byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); @@ -68,19 +67,19 @@ namespace ComputeSharp.Graphics.Buffers ArrayPool.Shared.Return(temporaryArray); } + else + { + // Directly copy the data back if there is no padding + Map(0); + MemoryHelper.Copy(MappedResource, span); + Unmap(0); + } } /// public override void SetData(Span span) { - // Directly copy the input span if there is no padding - if (PaddedElementSizeInBytes == ElementSizeInBytes) - { - Map(0); - MemoryHelper.Copy(span, MappedResource); - Unmap(0); - } - else + if (IsPaddingPresent) { // Create the temporary array byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); @@ -102,6 +101,38 @@ namespace ComputeSharp.Graphics.Buffers ArrayPool.Shared.Return(temporaryArray); } + else + { + // Directly copy the input span if there is no padding + Map(0); + MemoryHelper.Copy(span, MappedResource); + Unmap(0); + } + } + + /// + public override void SetData(ReadOnlyBuffer buffer) + { + using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + + copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); + copyCommandList.Flush(true); + } + + /// + public override void SetData(ReadWriteBuffer buffer) + { + // Create a temporary array + T[] array = ArrayPool.Shared.Rent(buffer.Size); + Span span = array.AsSpan(buffer.Size); + + // Get the unpadded data from the read write buffer + buffer.GetData(span); + + // Set the data, adding the padding if needed + SetData(span); + + ArrayPool.Shared.Return(array); } } } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs index 446719b5..4414c1b1 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs @@ -1,4 +1,5 @@ using System; +using System.Buffers; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Abstract; using ComputeSharp.Graphics.Helpers; @@ -48,14 +49,58 @@ namespace ComputeSharp.Graphics.Buffers public override void SetData(Span span) { using Buffer uploadBuffer = new Buffer(GraphicsDevice, Size, SizeInBytes, HeapType.Upload); - using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); uploadBuffer.Map(0); MemoryHelper.Copy(span, uploadBuffer.MappedResource); uploadBuffer.Unmap(0); + using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + copyCommandList.CopyBufferRegion(uploadBuffer, 0, this, 0, SizeInBytes); copyCommandList.Flush(true); } + + /// + public override void SetData(ReadOnlyBuffer buffer) + { + if (buffer.IsPaddingPresent) + { + // Create a temporary array + T[] array = ArrayPool.Shared.Rent(buffer.Size); + Span span = array.AsSpan(buffer.Size); + + // Get the data from the readonly array, removing the padding + buffer.GetData(span); + + // Set the data to the current buffer + SetData(span); + + ArrayPool.Shared.Return(array); + } + else + { + // Directly copy the input buffer + using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + + copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); + copyCommandList.Flush(true); + } + } + + /// + public override void SetData(ReadWriteBuffer buffer) + { + // Create a temporary array + T[] array = ArrayPool.Shared.Rent(buffer.Size); + Span span = array.AsSpan(buffer.Size); + + // Get the unpadded data from the read write buffer + buffer.GetData(span); + + // Set the data to the current buffer + SetData(span); + + ArrayPool.Shared.Return(array); + } } } From 9edbdcfdc3b9d1bf55d7033f887d6dec618b804f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 21:38:39 +0200 Subject: [PATCH 34/38] Code refactoring --- .../Buffers/Abstract/HlslBuffer{T}.cs | 24 ++++++++++++-- .../Buffers/ReadOnlyBuffer{T}.cs | 16 ---------- .../Buffers/ReadWriteBuffer{T}.cs | 31 +------------------ 3 files changed, 23 insertions(+), 48 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs index 34d3befd..d0873434 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs @@ -1,4 +1,5 @@ using System; +using System.Buffers; using System.Diagnostics.Contracts; using SharpDX.Direct3D12; @@ -48,12 +49,31 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// Writes the contents of a given to the current instance /// /// The input to read data from - public abstract void SetData(ReadOnlyBuffer buffer); + public virtual void SetData(ReadOnlyBuffer buffer) => SetDataWithCpuBuffer(buffer); /// /// Writes the contents of a given to the current instance /// /// The input to read data from - public abstract void SetData(ReadWriteBuffer buffer); + public virtual void SetData(ReadWriteBuffer buffer) => SetDataWithCpuBuffer(buffer); + + /// + /// Writes the contents of a given to the current instance, using a temporary CPU buffer + /// + /// The input to read data from + protected void SetDataWithCpuBuffer(HlslBuffer buffer) + { + // Create a temporary array + T[] array = ArrayPool.Shared.Rent(buffer.Size); + Span span = array.AsSpan(buffer.Size); + + // Get the unpadded data from the read write buffer + buffer.GetData(span); + + // Set the data, adding the padding if needed + SetData(span); + + ArrayPool.Shared.Return(array); + } } } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index 4ceeea12..8aac27b4 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -118,21 +118,5 @@ namespace ComputeSharp.Graphics.Buffers copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); copyCommandList.Flush(true); } - - /// - public override void SetData(ReadWriteBuffer buffer) - { - // Create a temporary array - T[] array = ArrayPool.Shared.Rent(buffer.Size); - Span span = array.AsSpan(buffer.Size); - - // Get the unpadded data from the read write buffer - buffer.GetData(span); - - // Set the data, adding the padding if needed - SetData(span); - - ArrayPool.Shared.Return(array); - } } } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs index 4414c1b1..a444baa8 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs @@ -63,20 +63,7 @@ namespace ComputeSharp.Graphics.Buffers /// public override void SetData(ReadOnlyBuffer buffer) { - if (buffer.IsPaddingPresent) - { - // Create a temporary array - T[] array = ArrayPool.Shared.Rent(buffer.Size); - Span span = array.AsSpan(buffer.Size); - - // Get the data from the readonly array, removing the padding - buffer.GetData(span); - - // Set the data to the current buffer - SetData(span); - - ArrayPool.Shared.Return(array); - } + if (buffer.IsPaddingPresent) SetDataWithCpuBuffer(buffer); else { // Directly copy the input buffer @@ -86,21 +73,5 @@ namespace ComputeSharp.Graphics.Buffers copyCommandList.Flush(true); } } - - /// - public override void SetData(ReadWriteBuffer buffer) - { - // Create a temporary array - T[] array = ArrayPool.Shared.Rent(buffer.Size); - Span span = array.AsSpan(buffer.Size); - - // Get the unpadded data from the read write buffer - buffer.GetData(span); - - // Set the data to the current buffer - SetData(span); - - ArrayPool.Shared.Return(array); - } } } From 8abf928b4507a4e9c545bdca27f5ca2d81273f70 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 21:44:35 +0200 Subject: [PATCH 35/38] More code refactoring --- .../Buffers/Abstract/HlslBuffer{T}.cs | 12 +++--------- .../Buffers/ReadOnlyBuffer{T}.cs | 13 +++++++++---- .../Buffers/ReadWriteBuffer{T}.cs | 6 +++--- 3 files changed, 15 insertions(+), 16 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs index d0873434..f3f915e4 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs @@ -46,16 +46,10 @@ namespace ComputeSharp.Graphics.Buffers.Abstract public abstract void SetData(Span span); /// - /// Writes the contents of a given to the current instance + /// Writes the contents of a given to the current instance /// - /// The input to read data from - public virtual void SetData(ReadOnlyBuffer buffer) => SetDataWithCpuBuffer(buffer); - - /// - /// Writes the contents of a given to the current instance - /// - /// The input to read data from - public virtual void SetData(ReadWriteBuffer buffer) => SetDataWithCpuBuffer(buffer); + /// The input to read data from + public abstract void SetData(HlslBuffer buffer); /// /// Writes the contents of a given to the current instance, using a temporary CPU buffer diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index 8aac27b4..09635da1 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -111,12 +111,17 @@ namespace ComputeSharp.Graphics.Buffers } /// - public override void SetData(ReadOnlyBuffer buffer) + public override void SetData(HlslBuffer buffer) { - using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + if (buffer is ReadOnlyBuffer readOnlyBuffer) + { + // Directly copy the input buffer, if possible + using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); - copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); - copyCommandList.Flush(true); + copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); + copyCommandList.Flush(true); + } + else SetDataWithCpuBuffer(buffer); } } } diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs index a444baa8..c0d5c50f 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs @@ -61,10 +61,9 @@ namespace ComputeSharp.Graphics.Buffers } /// - public override void SetData(ReadOnlyBuffer buffer) + public override void SetData(HlslBuffer buffer) { - if (buffer.IsPaddingPresent) SetDataWithCpuBuffer(buffer); - else + if (buffer is ReadOnlyBuffer readOnlyBuffer && !readOnlyBuffer.IsPaddingPresent) { // Directly copy the input buffer using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); @@ -72,6 +71,7 @@ namespace ComputeSharp.Graphics.Buffers copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); copyCommandList.Flush(true); } + else SetDataWithCpuBuffer(buffer); } } } From ea5e460c9f006512f0ab12503f04e3d49626baf7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 21:47:30 +0200 Subject: [PATCH 36/38] Added new buffer extension methods --- .../Buffers/Extensions/BufferExtensions.cs | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs b/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs index 33e0fe69..2f3c0ae3 100644 --- a/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs +++ b/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs @@ -3,6 +3,7 @@ using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Buffers; +using ComputeSharp.Graphics.Buffers.Abstract; namespace ComputeSharp { @@ -74,6 +75,23 @@ namespace ComputeSharp return buffer; } + /// + /// Allocates a new read write buffer with the specified parameters + /// + /// The type of items to store in the buffer + /// The instance to use to allocate the buffer + /// The input with the data to copy on the allocated buffer + /// A read write instance with the contents of the input + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, HlslBuffer buffer) where T : unmanaged + { + ReadWriteBuffer readWriteBuffer = new ReadWriteBuffer(device, buffer.Size); + readWriteBuffer.SetData(buffer); + + return readWriteBuffer; + } + /// /// Allocates a new constant buffer with the specified parameters /// @@ -122,5 +140,22 @@ namespace ComputeSharp return buffer; } + + /// + /// Allocates a new constant buffer with the specified parameters + /// + /// The type of items to store in the buffer + /// The instance to use to allocate the buffer + /// The input with the data to copy on the allocated buffer + /// A constant instance with the contents of the input + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, HlslBuffer buffer) where T : unmanaged + { + ReadOnlyBuffer readOnlyBuffer = new ReadOnlyBuffer(device, buffer.Size); + readOnlyBuffer.SetData(buffer); + + return readOnlyBuffer; + } } } From fc1589800836c2d4ad176790de1c3f76144be131 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 21:56:08 +0200 Subject: [PATCH 37/38] Minor bug fixes --- src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs | 2 +- src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs index f3f915e4..bde98d3e 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs @@ -59,7 +59,7 @@ namespace ComputeSharp.Graphics.Buffers.Abstract { // Create a temporary array T[] array = ArrayPool.Shared.Rent(buffer.Size); - Span span = array.AsSpan(buffer.Size); + Span span = array.AsSpan(0, buffer.Size); // Get the unpadded data from the read write buffer buffer.GetData(span); diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index 09635da1..5bab1210 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -113,7 +113,7 @@ namespace ComputeSharp.Graphics.Buffers /// public override void SetData(HlslBuffer buffer) { - if (buffer is ReadOnlyBuffer readOnlyBuffer) + if (buffer is ReadOnlyBuffer) { // Directly copy the input buffer, if possible using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); From 55e6daa89b494d0db5f46cf7d42d7957d4cfb18a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Aug 2019 21:57:24 +0200 Subject: [PATCH 38/38] Added tests for the new buffer APIs --- .../ComputeSharp.NetCore.Tests/BufferTests.cs | 64 ++++++++++++++++++- 1 file changed, 62 insertions(+), 2 deletions(-) diff --git a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs index 444778cd..5040ea07 100644 --- a/tests/ComputeSharp.NetCore.Tests/BufferTests.cs +++ b/tests/ComputeSharp.NetCore.Tests/BufferTests.cs @@ -11,7 +11,7 @@ namespace ComputeSharp.NetCore.Tests public class BufferTests { [TestMethod] - public void ReadWriteBufferGetSetData() + public void ReadWriteBufferGetSetDataFromArray() { float[] array = Enumerable.Range(0, 4096).Select(i => (float)i).ToArray(); @@ -22,7 +22,7 @@ namespace ComputeSharp.NetCore.Tests } [TestMethod] - public void ReadOnlyBufferGetSetData() + public void ReadOnlyBufferGetSetDataFromArray() { float[] array = Enumerable.Range(0, 4096).Select(i => (float)i).ToArray(); @@ -31,5 +31,65 @@ namespace ComputeSharp.NetCore.Tests Assert.IsTrue(array.AsSpan().ContentEquals(result)); } + + [TestMethod] + public void ReadWriteBufferGetSetDataFromReadWriteBuffer() + { + float[] array = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); + + using ReadWriteBuffer sourceBuffer = Gpu.Default.AllocateReadWriteBuffer(array); + using ReadWriteBuffer destinationBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer); + + float[] sourceResult = sourceBuffer.GetData(); + float[] destinationResult = destinationBuffer.GetData(); + + Assert.IsTrue(array.AsSpan().ContentEquals(sourceResult)); + Assert.IsTrue(array.AsSpan().ContentEquals(destinationResult)); + } + + [TestMethod] + public void ReadWriteBufferGetSetDataFromReadOnlyBuffer() + { + float[] array = Enumerable.Range(0, 4096).Select(i => (float)i).ToArray(); + + using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(array); + using ReadWriteBuffer destinationBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer); + + float[] sourceResult = sourceBuffer.GetData(); + float[] destinationResult = destinationBuffer.GetData(); + + Assert.IsTrue(array.AsSpan().ContentEquals(sourceResult)); + Assert.IsTrue(array.AsSpan().ContentEquals(destinationResult)); + } + + [TestMethod] + public void ReadOnlyBufferGetSetDataFromReadWriteBuffer() + { + float[] array = Enumerable.Range(0, 4096).Select(i => (float)i).ToArray(); + + using ReadWriteBuffer sourceBuffer = Gpu.Default.AllocateReadWriteBuffer(array); + using ReadOnlyBuffer destinationBuffer = Gpu.Default.AllocateReadOnlyBuffer(sourceBuffer); + + float[] sourceResult = sourceBuffer.GetData(); + float[] destinationResult = destinationBuffer.GetData(); + + Assert.IsTrue(array.AsSpan().ContentEquals(sourceResult)); + Assert.IsTrue(array.AsSpan().ContentEquals(destinationResult)); + } + + [TestMethod] + public void ReadOnlyBufferGetSetDataFromReadOnlyBuffer() + { + float[] array = Enumerable.Range(0, 4096).Select(i => (float)i).ToArray(); + + using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(array); + using ReadOnlyBuffer destinationBuffer = Gpu.Default.AllocateReadOnlyBuffer(sourceBuffer); + + float[] sourceResult = sourceBuffer.GetData(); + float[] destinationResult = destinationBuffer.GetData(); + + Assert.IsTrue(array.AsSpan().ContentEquals(sourceResult)); + Assert.IsTrue(array.AsSpan().ContentEquals(destinationResult)); + } } }