diff --git a/README.md b/README.md index 9548b097..5e07cac5 100644 --- a/README.md +++ b/README.md @@ -31,11 +31,27 @@ More details available [here](https://www.nuget.org/packages/ComputeSharp/). The following sample shows how to allocate a writeable buffer, populate it with a compute shader, and read it back. ```C# +// Define a simple shader +public readonly struct MyShader : IComputeShader +{ + public readonly ReadWriteBuffer buffer; + + public MyShader(ReadWriteBuffer buffer) + { + this.buffer = buffer; + } + + public void Execute(ThreadIds ids) + { + buffer[ids.X] = ids.X; + } +} + // Allocate a writeable buffer on the GPU, with the contents of the array using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1000); // Run the shader -Gpu.Default.For(1000, id => buffer[id.X] = id.X); +Gpu.Default.For(1000, new MyShader(buffer)); // Get the data back float[] array = buffer.GetData(); @@ -69,9 +85,41 @@ There are a number of extension APIs for the `GraphicsDevice` class that can be ## Advanced usage -**ComputeSharp** lets you dispatch compute shaders over thread groups from 1 to 3 dimensions, includes supports for constant and readonly buffers, and more. The shader body can both be declared inline, as a separate `Action` or as a local method. Additionally, most of the [HLSL intrinsic functions](https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-intrinsic-functions) are available through the `Hlsl` class. Here is a more advanced sample showcasing all these features. +**ComputeSharp** lets you dispatch compute shaders over thread groups from 1 to 3 dimensions, includes supports for constant and readonly buffers, and more. Additionally, most of the [HLSL intrinsic functions](https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-intrinsic-functions) are available through the `Hlsl` class. Here is a more advanced sample showcasing all these features. ```C# +// Define a class with some utility static functions +public static class Activations +{ + public static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x)); +} + +// Define the shader +public readonly struct ActivationShader : IComputeShader +{ + private readonly int width; + + public readonly ReadOnlyBuffer x; + public readonly ReadWriteBuffer y; + + public ActivationShader( + int width, + ReadOnlyBuffer x, + ReadWriteBuffer y) + { + this.width = width; + this.x = x; + this.y = y; + } + + public void Execute(ThreadIds ids) + { + int offset = ids.X + ids.Y * width; + float pow = Hlsl.Pow(x[offset], 2); + y[offset] = Activations.Sigmoid(pow); + } +} + 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) @@ -79,18 +127,8 @@ float[] y = new float[height * width]; // Result array (assume both had some val using ReadOnlyBuffer xBuffer = Gpu.Default.AllocateReadOnlyBuffer(x); using ReadWriteBuffer yBuffer = Gpu.Default.AllocateReadWriteBuffer(y); -static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x)); - -// Shader body -void Kernel(ThreadIds id) -{ - int offset = id.X + id.Y * width; - float pow = Hlsl.Pow(xBuffer[offset], 2); - yBuffer[offset] = Sigmoid(pow); -} - // Run the shader -Gpu.Default.For(width, height, Kernel); +Gpu.Default.For(width, height, new ActivationShader(width, xBuffer, yBuffer)); // Get the data back and write it to the y array yBuffer.GetData(y); @@ -102,7 +140,7 @@ The **ComputeSharp** library requires .NET Standard 2.1 support, and it is avail - .NET Core >= 3.0 - Windows (x86 or x64) -Additionally, you need an IDE with .NET Core 3.0 and C# 8.0 support to compile the library and samples on your PC. +Additionally, you need an IDE with .NET Core 3.1 and C# 8.0 support to compile the library and samples on your PC. # Special thanks diff --git a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj index f93e3c60..0c070ff3 100644 --- a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj +++ b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj @@ -2,11 +2,11 @@ Exe - netcoreapp3.0 + netcoreapp3.1 - + diff --git a/samples/ComputeSharp.Benchmark/Dnn.cs b/samples/ComputeSharp.Benchmark/Dnn.cs index 38f110e6..904ddd78 100644 --- a/samples/ComputeSharp.Benchmark/Dnn.cs +++ b/samples/ComputeSharp.Benchmark/Dnn.cs @@ -61,24 +61,60 @@ namespace ComputeSharp.Benchmark /// The weights tensor /// The bias tensor /// The result tensor + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void FullyConnectedForwardGpu( int c, int n, int m, int p, ReadOnlyBuffer x, ReadOnlyBuffer w, ReadOnlyBuffer b, ReadWriteBuffer y) { - void Kernel(ThreadIds id) + Gpu.Default.For(c, n, p, new FullyConnectedForwardKernel(n, m, p, x, w, b, y)); + } + + /// + /// Kernel for + /// + private readonly struct FullyConnectedForwardKernel : IComputeShader + { + private readonly int n; + private readonly int m; + private readonly int p; + + private readonly ReadOnlyBuffer x; + private readonly ReadOnlyBuffer w; + private readonly ReadOnlyBuffer b; + private readonly ReadWriteBuffer y; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public FullyConnectedForwardKernel( + int n, + int m, + int p, + ReadOnlyBuffer x, + ReadOnlyBuffer w, + ReadOnlyBuffer b, + ReadWriteBuffer y) { - int x_offset = id.X * n * p + id.Y * m; + this.n = n; + this.m = m; + this.p = p; + this.x = x; + this.w = w; + this.b = b; + this.y = y; + } + + /// + public void Execute(ThreadIds ids) + { + int x_offset = ids.X * n * p + ids.Y * m; float result = 0f; for (int k = 0; k < m; k++) { - result += x[x_offset + k] * w[k * p + id.Z]; + result += x[x_offset + k] * w[k * p + ids.Z]; } - y[id.X * n * p + id.Y * p + id.Z] = result + b[id.Z]; - }; - - Gpu.Default.For(c, n, p, Kernel); + y[ids.X * n * p + ids.Y * p + ids.Z] = result + b[ids.Z]; + } } } } diff --git a/samples/ComputeSharp.Benchmark/DnnBenchmark.cs b/samples/ComputeSharp.Benchmark/DnnBenchmark.cs index 7cdcd870..f7fc3936 100644 --- a/samples/ComputeSharp.Benchmark/DnnBenchmark.cs +++ b/samples/ComputeSharp.Benchmark/DnnBenchmark.cs @@ -130,7 +130,7 @@ namespace ComputeSharp.Benchmark /// /// Runs a fully connected forward operation on the CPU /// - [Benchmark] + [Benchmark(Baseline = true)] public void Cpu() => Dnn.FullyConnectedForwardCpu(C, N, M, P, X, W, B, Y); /// diff --git a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj index 6bd66e66..a849bebf 100644 --- a/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj +++ b/samples/ComputeSharp.ImageProcessing/ComputeSharp.ImageProcessing.csproj @@ -2,7 +2,7 @@ Exe - netcoreapp3.0 + netcoreapp3.1 @@ -16,7 +16,7 @@ - + diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs index c62cd173..2ae2eef1 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs @@ -1,7 +1,6 @@ using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; -using SixLabors.Primitives; namespace ComputeSharp.BokehBlur.Processors { @@ -59,9 +58,10 @@ namespace ComputeSharp.BokehBlur.Processors public float Gamma { get; } /// - public IImageProcessor CreatePixelSpecificProcessor(Image source, Rectangle sourceRectangle) where TPixel : struct, IPixel + public IImageProcessor CreatePixelSpecificProcessor(Configuration configuration, Image source, Rectangle sourceRectangle) + where TPixel : unmanaged, IPixel { - return new HlslBokehBlurProcessor(this, source, sourceRectangle); + return new HlslBokehBlurProcessor(this, configuration, source, sourceRectangle); } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index ea2b0df7..b400ecce 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -6,12 +6,10 @@ using System.Diagnostics.Contracts; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Threading.Tasks; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; -using SixLabors.Primitives; namespace ComputeSharp.BokehBlur.Processors { @@ -20,7 +18,8 @@ namespace ComputeSharp.BokehBlur.Processors /// /// The pixel format /// This processor is based on the code from Mike Pound, see github.com/mikepound/convolve - public sealed class HlslBokehBlurProcessor : IImageProcessor where TPixel : struct, IPixel + public sealed class HlslBokehBlurProcessor : ImageProcessor + where TPixel : unmanaged, IPixel { /// /// The kernel radius @@ -62,24 +61,20 @@ namespace ComputeSharp.BokehBlur.Processors /// private static readonly ConcurrentDictionary<(int Radius, int ComponentsCount), (Vector4[] Parameters, float Scale, Vector2[][] Kernels)> Cache = new ConcurrentDictionary<(int, int), (Vector4[], float, Vector2[][])>(); - /// - /// The source instance to modify - /// - private readonly Image Source; - /// /// Initializes a new instance of the class /// /// The defining the processor parameters + /// The configuration which allows altering default behaviour or extending the library /// The source instance to modify /// The source that indicates the area to edit - public HlslBokehBlurProcessor(HlslBokehBlurProcessor definition, Image source, Rectangle sourceRectangle) + public HlslBokehBlurProcessor(HlslBokehBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle) + : base(configuration, source, sourceRectangle) { Radius = definition.Radius; KernelSize = Radius * 2 + 1; ComponentsCount = definition.Components; Gamma = definition.Gamma; - Source = source; // Reuse the initialized values from the cache, if possible var parameters = (Radius, ComponentsCount); @@ -259,31 +254,36 @@ namespace ComputeSharp.BokehBlur.Processors } /// - public void Apply() + protected override void OnFrameApply(ImageFrame source) { - // Preliminary gamma highlight pass - using IMemoryOwner source4 = GetExposedVector4Buffer(); - - using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span); - using ReadWriteBuffer processingBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size); - using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size * 2); - using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); - - ref Vector4 param0 = ref KernelParameters[0]; // Avoid bounds check to access the kernel parameters - - // Perform two 1D convolutions for each component in the current instance - for (int i = 0; i < Kernels.Length; i++) + foreach (Memory memory in source.GetPixelMemoryGroup()) { - kernelBuffer.SetData(Kernels[i]); - Vector4 parameters = Unsafe.Add(ref param0, i); + // Preliminary gamma highlight pass + using IMemoryOwner source4 = GetExposedVector4Buffer(memory); - ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer); - ApplyHorizontalConvolutionAndAccumulatePartials(firstPassBuffer, processingBuffer, kernelBuffer, parameters.Z, parameters.W); + using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span); + using ReadWriteBuffer processingBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size); + using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size * 2); + using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); + + ref Vector4 param0 = ref KernelParameters[0]; // Avoid bounds check to access the kernel parameters + + // Perform two 1D convolutions for each component in the current instance + for (int j = 0; j < Kernels.Length; j++) + { + kernelBuffer.SetData(Kernels[j]); + Vector4 parameters = Unsafe.Add(ref param0, j); + + ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer); + ApplyHorizontalConvolutionAndAccumulatePartials(firstPassBuffer, processingBuffer, kernelBuffer, parameters.Z, parameters.W); + } + + // Apply the inverse gamma exposure pass + processingBuffer.GetData(source4.Memory.Span); + + // Write the final pixel data + ApplyInverseGammaExposure(source4.Memory, memory); } - - // Apply the inverse gamma exposure pass, and write the final pixel data - processingBuffer.GetData(source4.Memory.Span); - ApplyInverseGammaExposure(source4); } /// @@ -292,6 +292,7 @@ namespace ComputeSharp.BokehBlur.Processors /// The source to read data from /// The target to write the results to /// The with the values for the current complex kernel + [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyVerticalConvolution( ReadOnlyBuffer source, ReadWriteBuffer target, @@ -299,20 +300,44 @@ namespace ComputeSharp.BokehBlur.Processors { int height = Source.Height; int width = Source.Width; - int maxY = height - 1; - int maxX = width - 1; - int kernelLength = kernel.Size; - Gpu.Default.For(width, height, id => + Gpu.Default.For(width, height, new VerticalConvolutionProcessor + { + width = width, + maxY = height - 1, + maxX = width - 1, + kernelLength = kernel.Size, + source = source, + target = target, + kernel = kernel + }); + } + + /// + /// Kernel for + /// + private struct VerticalConvolutionProcessor : IComputeShader + { + public int width; + public int maxY; + public int maxX; + public int kernelLength; + + public ReadOnlyBuffer source; + public ReadWriteBuffer target; + public ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) { Vector4 real = Vector4.Zero; Vector4 imaginary = Vector4.Zero; int radiusY = kernelLength >> 1; - int sourceOffsetColumnBase = id.X; + int sourceOffsetColumnBase = ids.X; for (int i = 0; i < kernelLength; i++) { - int offsetY = Hlsl.Clamp(id.Y + i - radiusY, 0, maxY); + int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); Vector4 color = source[offsetY * width + offsetX]; Vector2 factors = kernel[i]; @@ -321,10 +346,10 @@ namespace ComputeSharp.BokehBlur.Processors imaginary += factors.Y * color; } - int offsetXY = id.Y * width * 2 + id.X * 2; + int offsetXY = ids.Y * width * 2 + ids.X * 2; target[offsetXY] = real; target[offsetXY + 1] = imaginary; - }); + } } /// @@ -335,6 +360,7 @@ namespace ComputeSharp.BokehBlur.Processors /// The with the values for the current complex kernel /// The weight factor for the real component of the complex pixel values /// The weight factor for the imaginary component of the complex pixel values + [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyHorizontalConvolutionAndAccumulatePartials( ReadWriteBuffer source, ReadWriteBuffer target, @@ -344,17 +370,45 @@ namespace ComputeSharp.BokehBlur.Processors { int height = Source.Height; int width = Source.Width; - int maxY = height - 1; - int maxX = width - 1; - int kernelLength = kernel.Size; - Gpu.Default.For(width, height, id => + Gpu.Default.For(width, height, new HorizontalConvolutionAndAccumulatePartialsProcessor + { + width = width, + maxY = height - 1, + maxX = width - 1, + kernelLength = kernel.Size, + z = z, + w = w, + source = source, + target = target, + kernel = kernel + }); + } + + /// + /// Kernel for + /// + private struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader + { + public int width; + public int maxY; + public int maxX; + public int kernelLength; + public float z; + public float w; + + public ReadWriteBuffer source; + public ReadWriteBuffer target; + public ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) { Vector4 real = Vector4.Zero; Vector4 imaginary = Vector4.Zero; int radiusX = kernelLength >> 1; - int sourceOffsetColumnBase = id.X; - int offsetY = Hlsl.Clamp(id.Y, 0, maxY); + int sourceOffsetColumnBase = ids.X; + int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); for (int i = 0; i < kernelLength; i++) { @@ -368,69 +422,143 @@ namespace ComputeSharp.BokehBlur.Processors imaginary += factors.X * sourceImaginary + factors.Y * sourceReal; } - target[id.Y * width + id.X] += real * z + imaginary * w; - }); + target[ids.Y * width + ids.X] += real * z + imaginary * w; + } } /// /// Applies the gamma correction/highlight to the input pixel buffer and returns an instance with values. /// + /// The source image [Pure] - private IMemoryOwner GetExposedVector4Buffer() + private IMemoryOwner GetExposedVector4Buffer(Memory source) { - IMemoryOwner source4 = Source.GetConfiguration().MemoryAllocator.Allocate(Source.Width * Source.Height); + IMemoryOwner target = Configuration.MemoryAllocator.Allocate(source.Length); + float exp = Gamma; int width = Source.Width; + int height = source.Length / width; - Parallel.For(0, Source.Height, y => + ParallelRowIterator.IterateRows( + Configuration, + new Rectangle(0, 0, width, height), + new GetExposedVector4BufferProcessor(width, exp, source, target.Memory, Configuration)); + + return target; + } + + /// + /// The processor for + /// + private readonly struct GetExposedVector4BufferProcessor : IRowOperation + { + private readonly int width; + private readonly float exp; + + private readonly Memory source; + private readonly Memory target; + private readonly Configuration configuration; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public GetExposedVector4BufferProcessor( + int width, + float exp, + Memory source, + Memory target, + Configuration configuration) { - ref TPixel rPixel = ref Source.GetPixelRowSpan(y).GetPinnableReference(); - ref Vector4 r4 = ref source4.Memory.Span.Slice(y * width).GetPinnableReference(); + this.width = width; + this.exp = exp; + this.source = source; + this.target = target; + this.configuration = configuration; + } - for (int x = 0; x < width; x++) + /// + public void Invoke(int y) + { + int offset = y * width; + + Span rowTPixel = source.Span.Slice(offset, width); + Span rowVector4 = target.Span.Slice(offset, width); + + PixelOperations.Instance.ToVector4(configuration, rowTPixel, rowVector4); + + foreach (ref Vector4 v in rowVector4) { - ref Vector4 v = ref Unsafe.Add(ref r4, x); - v = Unsafe.Add(ref rPixel, x).ToVector4(); v.X = MathF.Pow(v.X, exp); v.Y = MathF.Pow(v.Y, exp); v.Z = MathF.Pow(v.Z, exp); } - }); - - return source4; + } } /// /// Applies the inverse gamma exposure pass to compute the final pixel values for a target image /// - /// The source buffer to read from - private void ApplyInverseGammaExposure(IMemoryOwner sourceValues) + /// The source buffer to read from + /// The target image + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ApplyInverseGammaExposure(Memory source, Memory target) { int width = Source.Width; + int height = source.Length / width; float expGamma = 1 / Gamma; - Parallel.For(0, Source.Height, y => + ParallelRowIterator.IterateRows( + Configuration, + new Rectangle(0, 0, width, height), + new ApplyInverseGammaExposureProcessor(width, expGamma, source, target, Configuration)); + } + + /// + /// The processor for + /// + private readonly struct ApplyInverseGammaExposureProcessor : IRowOperation + { + private readonly int width; + private readonly float exp; + + private readonly Memory source; + private readonly Memory target; + private readonly Configuration configuration; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ApplyInverseGammaExposureProcessor( + int width, + float exp, + Memory source, + Memory target, + Configuration configuration) { + this.width = width; + this.exp = exp; + this.source = source; + this.target = target; + this.configuration = configuration; + } + + /// + public void Invoke(int y) + { + int offset = y * width; + + Span rowVector4 = source.Span.Slice(offset, width); + Span rowTPixel = target.Span.Slice(offset, width); + Vector4 low = Vector4.Zero; var high = new Vector4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); - ref TPixel rPixel = ref Source.GetPixelRowSpan(y).GetPinnableReference(); - ref Vector4 r4 = ref sourceValues.Memory.Span.Slice(y * width).GetPinnableReference(); - - for (int x = 0; x < width; x++) + foreach (ref Vector4 v in rowVector4) { - Vector4 v = Unsafe.Add(ref r4, x); var clamp = Vector4.Clamp(v, low, high); - v.X = MathF.Pow(clamp.X, expGamma); - v.Y = MathF.Pow(clamp.Y, expGamma); - v.Z = MathF.Pow(clamp.Z, expGamma); - - Unsafe.Add(ref rPixel, x).FromVector4(v); + v.X = MathF.Pow(clamp.X, exp); + v.Y = MathF.Pow(clamp.Y, exp); + v.Z = MathF.Pow(clamp.Z, exp); } - }); - } - /// - public void Dispose() { } + PixelOperations.Instance.FromVector4Destructive(configuration, rowVector4, rowTPixel); + } + } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs index c32bc696..d628edad 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs @@ -1,7 +1,6 @@ using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; -using SixLabors.Primitives; namespace ComputeSharp.BokehBlur.Processors { @@ -48,9 +47,10 @@ namespace ComputeSharp.BokehBlur.Processors public int Radius { get; } /// - public IImageProcessor CreatePixelSpecificProcessor(Image source, Rectangle sourceRectangle) where TPixel : struct, IPixel + public IImageProcessor CreatePixelSpecificProcessor(Configuration configuration, Image source, Rectangle sourceRectangle) + where TPixel : unmanaged, IPixel { - return new HlslGaussianBlurProcessor(this, source, sourceRectangle); + return new HlslGaussianBlurProcessor(this, configuration, source, sourceRectangle); } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index 274f3228..1cd556b2 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -1,13 +1,11 @@ using System; +using System.Buffers; using System.Numerics; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Threading.Tasks; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; -using SixLabors.Primitives; namespace ComputeSharp.BokehBlur.Processors { @@ -15,29 +13,26 @@ namespace ComputeSharp.BokehBlur.Processors /// Applies Gaussian blur processing to an image. /// /// The pixel format. - internal class HlslGaussianBlurProcessor : IImageProcessor where TPixel : struct, IPixel + internal class HlslGaussianBlurProcessor : ImageProcessor + where TPixel : unmanaged, IPixel { /// /// The 1D kernel to apply /// private readonly float[] Kernel; - /// - /// The source instance to modify - /// - private readonly Image Source; - /// /// Initializes a new instance of the class /// /// The defining the processor parameters + /// The configuration which allows altering default behaviour or extending the library /// The source for the current processor instance /// The source area to process for the current processor instance - public HlslGaussianBlurProcessor(HlslGaussianBlurProcessor definition, Image source, Rectangle sourceRectangle) + public HlslGaussianBlurProcessor(HlslGaussianBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle) + : base(configuration, source, sourceRectangle) { int kernelSize = definition.Radius * 2 + 1; Kernel = CreateGaussianBlurKernel(kernelSize, definition.Sigma); - Source = source; } /// @@ -89,20 +84,29 @@ namespace ComputeSharp.BokehBlur.Processors } /// - public void Apply() + protected override void OnFrameApply(ImageFrame source) { - using Image source = Source.CloneAs(); - Span sourceSpan = MemoryMarshal.Cast(source.GetPixelSpan()); + foreach (Memory memory in source.GetPixelMemoryGroup()) + { + Span spanTPixel = memory.Span; - using ReadWriteBuffer sourceBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceSpan); - using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size); - using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel); + using IMemoryOwner group4 = Configuration.MemoryAllocator.Allocate(spanTPixel.Length); - ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer); - ApplyHorizontalConvolution(firstPassBuffer, sourceBuffer, kernelBuffer); + Span spanVector4 = group4.Memory.Span; - sourceBuffer.GetData(sourceSpan); - WriteResultData(source); + PixelOperations.Instance.ToVector4(Configuration, spanTPixel, spanVector4); + + using ReadWriteBuffer sourceBuffer = Gpu.Default.AllocateReadWriteBuffer(spanVector4); + using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Size); + using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel); + + ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer); + ApplyHorizontalConvolution(firstPassBuffer, sourceBuffer, kernelBuffer); + + sourceBuffer.GetData(spanVector4); + + PixelOperations.Instance.FromVector4Destructive(Configuration, spanVector4, spanTPixel); + } } /// @@ -111,6 +115,7 @@ namespace ComputeSharp.BokehBlur.Processors /// The source to read data from /// The target to write the results to /// The with the values for the current complex kernel + [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyVerticalConvolution( ReadWriteBuffer source, ReadWriteBuffer target, @@ -118,28 +123,52 @@ namespace ComputeSharp.BokehBlur.Processors { int height = Source.Height; int width = Source.Width; - int maxY = height - 1; - int maxX = width - 1; - int kernelLength = kernel.Size; - Gpu.Default.For(width, height, id => + Gpu.Default.For(width, height, new VerticalConvolutionProcessor + { + width = width, + maxY = height - 1, + maxX = width - 1, + kernelLength = kernel.Size, + source = source, + target = target, + kernel = kernel + }); + } + + /// + /// Kernel for + /// + private struct VerticalConvolutionProcessor : IComputeShader + { + public int width; + public int maxY; + public int maxX; + public int kernelLength; + + public ReadWriteBuffer source; + public ReadWriteBuffer target; + public ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) { Vector4 result = Vector4.Zero; int radiusY = kernelLength >> 1; - int sourceOffsetColumnBase = id.X; + int sourceOffsetColumnBase = ids.X; for (int i = 0; i < kernelLength; i++) { - int offsetY = Hlsl.Clamp(id.Y + i - radiusY, 0, maxY); + int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); Vector4 color = source[offsetY * width + offsetX]; result += kernel[i] * color; } - int offsetXY = id.Y * width + id.X; + int offsetXY = ids.Y * width + ids.X; target[offsetXY] = result; - }); + } } /// @@ -148,6 +177,7 @@ namespace ComputeSharp.BokehBlur.Processors /// The source to read data from /// The target to write the results to /// The with the values for the current complex kernel + [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyHorizontalConvolution( ReadWriteBuffer source, ReadWriteBuffer target, @@ -155,16 +185,40 @@ namespace ComputeSharp.BokehBlur.Processors { int height = Source.Height; int width = Source.Width; - int maxY = height - 1; - int maxX = width - 1; - int kernelLength = kernel.Size; - Gpu.Default.For(width, height, id => + Gpu.Default.For(width, height, new HorizontalConvolutionProcessor + { + width = width, + maxY = height - 1, + maxX = width - 1, + kernelLength = kernel.Size, + source = source, + target = target, + kernel = kernel + }); + } + + /// + /// Kernel for + /// + private struct HorizontalConvolutionProcessor : IComputeShader + { + public int width; + public int maxY; + public int maxX; + public int kernelLength; + + public ReadWriteBuffer source; + public ReadWriteBuffer target; + public ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) { Vector4 result = Vector4.Zero; int radiusX = kernelLength >> 1; - int sourceOffsetColumnBase = id.X; - int offsetY = Hlsl.Clamp(id.Y, 0, maxY); + int sourceOffsetColumnBase = ids.X; + int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); int offsetXY; for (int i = 0; i < kernelLength; i++) @@ -176,32 +230,9 @@ namespace ComputeSharp.BokehBlur.Processors result += kernel[i] * color; } - offsetXY = id.Y * width + id.X; + offsetXY = ids.Y * width + ids.X; target[offsetXY] = result; - }); + } } - - /// - /// Writes the final data to the source image - /// - /// The source to read from - private void WriteResultData(Image image) - { - int width = Source.Width; - - Parallel.For(0, Source.Height, y => - { - ref TPixel rPixel = ref Source.GetPixelRowSpan(y).GetPinnableReference(); - ref Vector4 r4 = ref MemoryMarshal.Cast(image.GetPixelRowSpan(y)).GetPinnableReference(); - - for (int x = 0; x < width; x++) - { - Unsafe.Add(ref rPixel, x).FromVector4(Unsafe.Add(ref r4, x)); - } - }); - } - - /// - public void Dispose() { } } } diff --git a/samples/ComputeSharp.ImageProcessing/Program.cs b/samples/ComputeSharp.ImageProcessing/Program.cs index 9aaac4e1..91f52ca5 100644 --- a/samples/ComputeSharp.ImageProcessing/Program.cs +++ b/samples/ComputeSharp.ImageProcessing/Program.cs @@ -3,7 +3,6 @@ using System.IO; using System.Reflection; using ComputeSharp.BokehBlur.Processors; using SixLabors.ImageSharp; -using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; using SixLabors.ImageSharp.Processing.Processors; @@ -15,7 +14,7 @@ namespace ComputeSharp.ImageProcessing { Console.WriteLine(">> Loading image"); string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "city.jpg"); - using Image image = Image.Load(path); + using Image image = Image.Load(path); // Apply a series of processors and save the results foreach (var effect in new (string Name, IImageProcessor Processor)[] @@ -25,8 +24,7 @@ namespace ComputeSharp.ImageProcessing }) { Console.WriteLine($">> Applying {effect.Name}"); - using Image copy = image.Clone(); - copy.Mutate(c => c.ApplyProcessor(effect.Processor)); + using Image copy = image.Clone(c => c.ApplyProcessor(effect.Processor)); Console.WriteLine($">> Saving {effect.Name} to disk"); string targetPath = Path.Combine( diff --git a/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj b/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj index bfb20336..430f758a 100644 --- a/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj +++ b/samples/ComputeSharp.Sample/ComputeSharp.Sample.csproj @@ -2,7 +2,7 @@ Exe - netcoreapp3.0 + netcoreapp3.1 diff --git a/samples/ComputeSharp.Sample/Program.cs b/samples/ComputeSharp.Sample/Program.cs index f94bc6d1..5d2cfcf5 100644 --- a/samples/ComputeSharp.Sample/Program.cs +++ b/samples/ComputeSharp.Sample/Program.cs @@ -27,11 +27,7 @@ namespace ComputeSharp.Sample using ReadWriteBuffer gpuBuffer = Gpu.Default.AllocateReadWriteBuffer(array); // Run the shader - Gpu.Default.For(100, id => - { - int offset = id.X + id.Y * width; - gpuBuffer[offset] *= 2; - }); + Gpu.Default.For(100, new MainKernel(width, gpuBuffer)); // Get the data back gpuBuffer.GetData(array); @@ -42,6 +38,30 @@ namespace ComputeSharp.Sample Console.WriteLine("=================================================="); } + /// + /// Kernel for + /// + private readonly struct MainKernel : IComputeShader + { + private readonly int width; + + private readonly ReadWriteBuffer buffer; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public MainKernel(int width, ReadWriteBuffer buffer) + { + this.width = width; + this.buffer = buffer; + } + + /// + public void Execute(ThreadIds ids) + { + int offset = ids.X + ids.Y * width; + buffer[offset] *= 2; + } + } + /// /// Prints a matrix in a properly formatted way /// diff --git a/src/ComputeSharp.Core/Interfaces/IComputeShader.cs b/src/ComputeSharp.Core/Interfaces/IComputeShader.cs new file mode 100644 index 00000000..66f145dd --- /dev/null +++ b/src/ComputeSharp.Core/Interfaces/IComputeShader.cs @@ -0,0 +1,14 @@ +namespace ComputeSharp +{ + /// + /// An representing a compute shader. + /// + public interface IComputeShader + { + /// + /// Executes the current compute shader. + /// + /// The value with the current execution indices. + void Execute(ThreadIds ids); + } +} diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource.cs index 2f65e9a8..6e266844 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.CompilerServices; using Vortice.Direct3D12; namespace ComputeSharp.Graphics.Buffers.Abstract @@ -22,11 +23,6 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// public GraphicsDevice GraphicsDevice { get; } - /// - /// Gets the associated to the currently mapped resource - /// - internal IntPtr MappedResource { get; private set; } - /// /// Gets the object currently mapped /// @@ -45,24 +41,50 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// /// Maps the current resource to a specified subresource /// - /// An for the newly mapped resource - internal IntPtr Map() + /// A instance representing the mapped resource + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal MappedResource MapResource() { - IntPtr mappedResource = NativeResource?.Map(0) ?? throw new InvalidOperationException("Missing resource"); - MappedResource = mappedResource; - return mappedResource; - } + var resource = NativeResource ?? throw new InvalidOperationException("Missing resource"); - /// - /// Unmaps a subresource specified by a given index - /// - internal void Unmap() - { - NativeResource?.Unmap(0); - MappedResource = IntPtr.Zero; + return new MappedResource(resource); } /// public virtual void Dispose() => NativeResource?.Dispose(); + + /// + /// A type representing a mapped memory resource + /// + internal readonly ref struct MappedResource + { + /// + /// The target to map + /// + private readonly ID3D12Resource Resource; + + /// + /// The pointer to the mapped resource + /// + public readonly IntPtr Pointer; + + /// + /// Creates a new instance for a given value + /// + /// The input instance to map + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public MappedResource(ID3D12Resource resource) + { + Resource = resource; + Pointer = resource.Map(0); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + Resource.Unmap(0); + } + } } } diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs index 76b0e267..4b938cca 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs @@ -71,18 +71,18 @@ namespace ComputeSharp.Graphics.Buffers.Abstract public void SetData(T[] array, int offset, int count) => SetData(array.AsSpan(), offset, count); /// - /// 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 void SetData(Span span) => SetData(span, 0, Size); + /// The input to read data from + public void SetData(ReadOnlySpan span) => SetData(span, 0, Size); /// - /// Writes the contents of a given to a specified area of the current instance + /// Writes the contents of a given to a specified area of the current instance /// - /// The input to read data from + /// The input to read data from /// The offset to start writing data to /// The number of items to write - public abstract void SetData(Span span, int offset, int count); + public abstract void SetData(ReadOnlySpan span, int offset, int count); /// /// Writes the contents of a given to the current instance diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs index 92ad8911..15e2d11e 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs @@ -25,29 +25,30 @@ namespace ComputeSharp.Graphics.Buffers.Abstract public override void GetData(Span span, int offset, int count) { using Buffer transferBuffer = new Buffer(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.ReadBack); - using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); - copyCommandList.CopyBufferRegion(this, offset * ElementSizeInBytes, transferBuffer, 0, count * ElementSizeInBytes); - copyCommandList.Flush(); + using (CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy)) + { + copyCommandList.CopyBufferRegion(this, offset * ElementSizeInBytes, transferBuffer, 0, count * ElementSizeInBytes); + } - transferBuffer.Map(); - MemoryHelper.Copy(transferBuffer.MappedResource, 0, span, 0, count); - transferBuffer.Unmap(); + using MappedResource resource = transferBuffer.MapResource(); + + MemoryHelper.Copy(resource.Pointer, 0, span, 0, count); } /// - public override void SetData(Span span, int offset, int count) + public override void SetData(ReadOnlySpan span, int offset, int count) { using Buffer transferBuffer = new Buffer(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.Transfer); - transferBuffer.Map(); - MemoryHelper.Copy(span, 0, transferBuffer.MappedResource, 0, count); - transferBuffer.Unmap(); + using (MappedResource resource = transferBuffer.MapResource()) + { + MemoryHelper.Copy(span, resource.Pointer, 0, count); + } using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); copyCommandList.CopyBufferRegion(transferBuffer, 0, this, offset * ElementSizeInBytes, count * ElementSizeInBytes); - copyCommandList.Flush(); } /// @@ -59,7 +60,6 @@ namespace ComputeSharp.Graphics.Buffers.Abstract using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); - copyCommandList.Flush(); } else SetDataWithCpuBuffer(buffer); } diff --git a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs index 591d6dda..186a3154 100644 --- a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs @@ -1,7 +1,7 @@ using System; -using System.Buffers; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using ComputeSharp.Exceptions; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Buffers.Abstract; @@ -23,16 +23,18 @@ namespace ComputeSharp /// /// The associated with the current instance /// The number of items to store in the current buffer - internal ConstantBuffer(GraphicsDevice device, int size) : base(device, size, size * GetPaddedSize() * 16, BufferType.Constant) { } + internal ConstantBuffer(GraphicsDevice device, int size) : base(device, size, size * GetPaddedSize(), BufferType.Constant) { } /// /// Gets the right padded size for elements to store in the current instance /// [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int GetPaddedSize() { int size = Unsafe.SizeOf(); - return size % 16 == 0 ? 1 : size / 16 + 1; + + return (size + 15) & ~15; } /// @@ -43,72 +45,49 @@ namespace ComputeSharp public T this[int i] => throw new InvalidExecutionContextException($"{nameof(ConstantBuffer)}[int]"); /// - public override void GetData(Span span, int offset, int count) + public override unsafe void GetData(Span span, int offset, int count) { + using MappedResource resource = MapResource(); + if (IsPaddingPresent) { - // Create the temporary array - byte[] temporaryArray = ArrayPool.Shared.Rent(count * PaddedElementSizeInBytes); - Span temporarySpan = temporaryArray.AsSpan(0, count * PaddedElementSizeInBytes); + ref T spanRef = ref MemoryMarshal.GetReference(span); + ref byte resourceRef = ref Unsafe.AsRef((void*)resource.Pointer); - // Copy the padded data to the temporary array - Map(); - MemoryHelper.Copy(MappedResource, offset * PaddedElementSizeInBytes, temporarySpan, 0, count * PaddedElementSizeInBytes); - Unmap(); + // Move to the initial ref + resourceRef = ref Unsafe.Add(ref resourceRef, offset * GetPaddedSize()); - 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 < count; i++) + for (var i = 0; i < count; i++) { - ref byte rsource = ref Unsafe.Add(ref tin, i * PaddedElementSizeInBytes); - Unsafe.Add(ref tout, i) = Unsafe.As(ref rsource); - } + ref byte targetRef = ref Unsafe.Add(ref resourceRef, i * GetPaddedSize()); - ArrayPool.Shared.Return(temporaryArray); - } - else - { - // Directly copy the data back if there is no padding - Map(); - MemoryHelper.Copy(MappedResource, offset, span, 0, count); - Unmap(); + Unsafe.Add(ref spanRef, i) = Unsafe.As(ref targetRef); + } } + else MemoryHelper.Copy(resource.Pointer, offset, span, 0, count); } /// - public override void SetData(Span span, int offset, int count) + public override unsafe void SetData(ReadOnlySpan span, int offset, int count) { + using MappedResource resource = MapResource(); + if (IsPaddingPresent) { - // Create the temporary array - byte[] temporaryArray = ArrayPool.Shared.Rent(count * PaddedElementSizeInBytes); - Span temporarySpan = temporaryArray.AsSpan(0, count * PaddedElementSizeInBytes); // Array pool arrays can be longer - ref T tin = ref span.GetPinnableReference(); - ref byte tout = ref temporarySpan.GetPinnableReference(); + ref T spanRef = ref MemoryMarshal.GetReference(span); + ref byte resourceRef = ref Unsafe.AsRef((void*)resource.Pointer); - // Copy the input data to the temporary array and add the padding - for (int i = 0; i < count; i++) + // Move to the initial offset + resourceRef = ref Unsafe.Add(ref resourceRef, offset * GetPaddedSize()); + + for (var i = 0; i < count; i++) { - ref byte rtarget = ref Unsafe.Add(ref tout, i * PaddedElementSizeInBytes); - Unsafe.As(ref rtarget) = Unsafe.Add(ref tin, i); + ref byte targetRef = ref Unsafe.Add(ref resourceRef, i * GetPaddedSize()); + + Unsafe.As(ref targetRef) = Unsafe.Add(ref spanRef, i); } - - // Copy the padded data to the GPU - Map(); - MemoryHelper.Copy(temporarySpan, 0, MappedResource, offset * PaddedElementSizeInBytes, count * PaddedElementSizeInBytes); - Unmap(); - - ArrayPool.Shared.Return(temporaryArray); - } - else - { - // Directly copy the input span if there is no padding - Map(); - MemoryHelper.Copy(span, 0, MappedResource, offset, count); - Unmap(); } + else MemoryHelper.Copy(span, resource.Pointer, offset, count); } /// @@ -120,7 +99,6 @@ namespace ComputeSharp using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); - copyCommandList.Flush(); } else SetDataWithCpuBuffer(buffer); } diff --git a/src/ComputeSharp.Graphics/Commands/CommandList.cs b/src/ComputeSharp.Graphics/Commands/CommandList.cs index 413af34e..6f288bce 100644 --- a/src/ComputeSharp.Graphics/Commands/CommandList.cs +++ b/src/ComputeSharp.Graphics/Commands/CommandList.cs @@ -88,23 +88,13 @@ namespace ComputeSharp.Graphics.Commands NativeCommandList.Dispatch(threadGroupCountX, threadGroupCountY, threadGroupCountZ); } - /// - /// Executes the pending operations and waits for them to be completed - /// - public void Flush() - { - Close(); - GraphicsDevice.ExecuteCommandList(this); - } - - /// - /// Closes the current native command list - /// - public void Close() => NativeCommandList.Close(); - /// public override void Dispose() { + NativeCommandList.Close(); + + GraphicsDevice.ExecuteCommandList(this); + switch (CommandListType) { case CommandListType.Direct: diff --git a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj index 873afc89..eb97cc79 100644 --- a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj +++ b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/src/ComputeSharp.Graphics/GraphicsDevice.cs b/src/ComputeSharp.Graphics/GraphicsDevice.cs index 4275c34e..9a5165b6 100644 --- a/src/ComputeSharp.Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp.Graphics/GraphicsDevice.cs @@ -2,9 +2,9 @@ using System.Threading; using ComputeSharp.Graphics.Commands; using Vortice.Direct3D12; -using Vortice.DirectX.Direct3D; using Vortice.DXGI; using CommandList = ComputeSharp.Graphics.Commands.CommandList; +using Direct3DFeatureLevel = Vortice.Direct3D.FeatureLevel; namespace ComputeSharp.Graphics { @@ -16,12 +16,7 @@ namespace ComputeSharp.Graphics /// /// Gets the value that needs to be supported by GPUs mapped to a instance /// - public const FeatureLevel FeatureLevel = Vortice.DirectX.Direct3D.FeatureLevel.Level_12_1; - - /// - /// The instance used to wait for completion when executing commands - /// - private readonly AutoResetEvent AutoResetEvent = new AutoResetEvent(false); + public const Direct3DFeatureLevel FeatureLevel = Direct3DFeatureLevel.Level_12_1; /// /// The instance to use for compute operations @@ -126,11 +121,6 @@ namespace ComputeSharp.Graphics /// internal ID3D12Fence NativeDirectFence { get; } - /// - /// The used to lock command list executions - /// - private readonly object Lock = new object(); - /// /// Gets the next fence value for compute operations /// @@ -174,11 +164,11 @@ namespace ComputeSharp.Graphics if (fenceValue <= fence.CompletedValue) return; - lock (Lock) - { - fence.SetEventOnCompletion(fenceValue, AutoResetEvent.SafeWaitHandle.DangerousGetHandle()); - AutoResetEvent.WaitOne(); - } + using ManualResetEvent fenceEvent = new ManualResetEvent(false); + + fence.SetEventOnCompletion(fenceValue, fenceEvent); + + fenceEvent.WaitOne(); } /// @@ -244,8 +234,6 @@ namespace ComputeSharp.Graphics NativeDirectFence.Dispose(); NativeDevice.Dispose(); - - AutoResetEvent.Dispose(); } } } diff --git a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs index 70537bb2..be1af1ef 100644 --- a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; +using Vortice.Direct3D; using Vortice.Direct3D12; -using Vortice.DirectX.Direct3D; using Vortice.DXGI; namespace ComputeSharp.Graphics.Helpers @@ -23,7 +23,7 @@ namespace ComputeSharp.Graphics.Helpers { List<(ID3D12Device, AdapterDescription)> devices = new List<(ID3D12Device, AdapterDescription)>(); - foreach (IDXGIAdapter1 adapter in factory.EnumAdapters1()) + foreach (IDXGIAdapter1 adapter in factory.Adapters1) { if (adapter.Description.DedicatedVideoMemory == 0) continue; if (D3D12.D3D12CreateDevice(adapter, FeatureLevel.Level_12_0, out ID3D12Device device).Success) diff --git a/src/ComputeSharp.Graphics/Helpers/MemoryHelper.cs b/src/ComputeSharp.Graphics/Helpers/MemoryHelper.cs index 560db122..b9911acb 100644 --- a/src/ComputeSharp.Graphics/Helpers/MemoryHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/MemoryHelper.cs @@ -9,19 +9,19 @@ namespace ComputeSharp.Graphics.Helpers internal static class MemoryHelper { /// - /// Copies the content of a to the area pointed by an input value + /// Copies the content of a to the area pointed by an input value /// - /// The type of values in the input - /// The source to read - /// The source offset to start reading data from + /// The type of values in the input + /// The source to read /// The for the destination memory area /// The destination offset to start writing data to /// The total number of items to copy - public static unsafe void Copy(Span source, int sourceOffset, IntPtr destination, int destinationOffset, int count) where T : unmanaged + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void Copy(ReadOnlySpan source, IntPtr destination, int destinationOffset, int count) where T : unmanaged { - ref T rout = ref Unsafe.AsRef(destination.ToPointer()); - void* target = Unsafe.AsPointer(ref Unsafe.Add(ref rout, destinationOffset)); - source.Slice(sourceOffset, count).CopyTo(new Span(target, count)); + T* p = (T*)destination.ToPointer() + destinationOffset; + + source.CopyTo(new Span(p, count)); } /// diff --git a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj index 5ed31bb6..a46b9c92 100644 --- a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj +++ b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj @@ -7,10 +7,11 @@ - - - - + + + + + diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs similarity index 83% rename from src/ComputeSharp.Shaders/ShaderRunner.cs rename to src/ComputeSharp.Shaders/ShaderRunner{T}.cs index 090a474e..eba0bbb6 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs @@ -1,11 +1,11 @@ using System; -using System.Collections.Generic; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Buffers.Abstract; using ComputeSharp.Shaders.Renderer; using ComputeSharp.Shaders.Renderer.Models; using ComputeSharp.Shaders.Translation; using ComputeSharp.Shaders.Translation.Models; +using Microsoft.Collections.Extensions; using Vortice.Direct3D12; using CommandList = ComputeSharp.Graphics.Commands.CommandList; using PipelineState = ComputeSharp.Graphics.Commands.PipelineState; @@ -15,7 +15,9 @@ namespace ComputeSharp.Shaders /// /// A responsible for performing all the necessary operations to compile and run a compute shader /// - internal static class ShaderRunner + /// The type of compute shader to run + internal static class ShaderRunner + where T : struct, IComputeShader { /// /// Compiles and runs the input shader on a target instance, with the specified parameters @@ -24,8 +26,8 @@ namespace ComputeSharp.Shaders /// The number of iterations to run on the X axis /// The number of iterations to run on the Y axis /// The number of iterations to run on the Z axis - /// The input representing the compute shader to run - public static void Run(GraphicsDevice device, int x, int y, int z, Action action) + /// The input instance representing the compute shader to run + public static void Run(GraphicsDevice device, int x, int y, int z, in T shader) { // Calculate the optimized thread num values int threadsX, threadsY = 1, threadsZ = 1; @@ -33,13 +35,13 @@ namespace ComputeSharp.Shaders else if (z == 1) threadsX = threadsY = 8; else threadsX = threadsY = threadsZ = 4; - Run(device, x, y, z, threadsX, threadsY, threadsZ, action); + Run(device, x, y, z, threadsX, threadsY, threadsZ, shader); } /// /// The mapping used to cache and reuse compiled shaders /// - private static readonly Dictionary<(int Id, int ThreadsX, int ThreadsY, int ThreadsZ), CachedShader> ShadersCache = new Dictionary<(int, int, int, int), CachedShader>(); + private static readonly DictionarySlim> ShadersCache = new DictionarySlim>(); /// /// Compiles and runs the input shader on a target instance, with the specified parameters @@ -51,22 +53,22 @@ namespace ComputeSharp.Shaders /// The number of threads in each thread group for the X axis /// The number of threads in each thread group for the Y axis /// The number of threads in each thread group for the Z axis - /// The input representing the compute shader to run + /// The input instance representing the compute shader to run public static void Run( GraphicsDevice device, int x, int y, int z, int threadsX, int threadsY, int threadsZ, - Action action) + in T shader) { // Try to get the cache shader - CachedShader shaderData; + CachedShader shaderData; lock (ShadersCache) { - var key = (ShaderHashCodeProvider.GetHashCode(action), threadsX, threadsY, threadsZ); + var key = new ShaderKey(ShaderHashCodeProvider.GetHashCode(shader), threadsX, threadsY, threadsZ); if (!ShadersCache.TryGetValue(key, out shaderData)) { // Load the input shader - ShaderLoader shaderLoader = ShaderLoader.Load(action); + ShaderLoader shaderLoader = ShaderLoader.Load(shader); // Render the loaded shader ShaderInfo shaderInfo = new ShaderInfo @@ -87,8 +89,7 @@ namespace ComputeSharp.Shaders ShaderBytecode shaderBytecode = ShaderCompiler.CompileShader(shaderSource); // Cache for later use - shaderData = new CachedShader(shaderLoader, shaderBytecode); - ShadersCache.Add(key, shaderData); + ShadersCache.GetOrAddValueRef(key) = shaderData = new CachedShader(shaderLoader, shaderBytecode); } } @@ -102,7 +103,7 @@ namespace ComputeSharp.Shaders commandList.SetPipelineState(pipelineState); // Extract the dispatch data for the shader invocation - using DispatchData dispatchData = shaderData.Loader.GetDispatchData(action, x, y, z); + using DispatchData dispatchData = shaderData.Loader.GetDispatchData(shader, x, y, z); // Load the captured buffers Span resources = dispatchData.Resources; @@ -124,7 +125,6 @@ namespace ComputeSharp.Shaders // Dispatch and wait for completion commandList.Dispatch(groupsX, groupsY, groupsZ); - commandList.Flush(); } } } diff --git a/src/ComputeSharp.Shaders/Translation/Enums/MethodType.cs b/src/ComputeSharp.Shaders/Translation/Enums/MethodType.cs index 7df4f830..c3c188e8 100644 --- a/src/ComputeSharp.Shaders/Translation/Enums/MethodType.cs +++ b/src/ComputeSharp.Shaders/Translation/Enums/MethodType.cs @@ -6,9 +6,9 @@ internal enum MethodType { /// - /// An instance method that belongs to a closure class + /// The instance method on some shader type /// - Closure, + Execute, /// /// A standalone, static method diff --git a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs index 5c10cd5b..4ff57cfd 100644 --- a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs @@ -6,7 +6,6 @@ using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; -using System.Text; using System.Text.RegularExpressions; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Translation.Enums; @@ -138,7 +137,7 @@ namespace ComputeSharp.Shaders.Translation { string sourceCode = methodType switch { - MethodType.Closure => GetSyntaxTreeForClosureMethod(methodInfo), + MethodType.Execute => GetSyntaxTreeForExecuteMethod(methodInfo), MethodType.Static => GetSyntaxTreeForStaticMethod(methodInfo), _ => throw new ArgumentOutOfRangeException(nameof(methodType), $"Invalid method type: {methodType}") }; @@ -147,7 +146,12 @@ namespace ComputeSharp.Shaders.Translation SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode); // Get the root node to return - rootNode = syntaxTree.GetRoot().DescendantNodes().OfType().First(node => node.GetLeadingTrivia().ToFullString().Contains(methodInfo.Name)); + rootNode = syntaxTree + .GetRoot() + .DescendantNodes() + .OfType() + .First(node => node.Identifier.ToString().Equals(methodInfo.Name) || + node.GetLeadingTrivia().ToFullString().Contains(methodInfo.Name)); // Update the incremental compilation and retrieve the syntax tree for the method Compilation compilation = _Compilation.AddSyntaxTrees(syntaxTree); @@ -159,31 +163,13 @@ namespace ComputeSharp.Shaders.Translation /// /// The input to inspect [Pure] - private string GetSyntaxTreeForClosureMethod(MethodInfo methodInfo) + private string GetSyntaxTreeForExecuteMethod(MethodInfo methodInfo) { - // Decompile the method source and fix the method declaration for local methods converted to lambdas - string - sourceCode = DecompileMethodOrDeclaringType(methodInfo), - typeFixedCode = ClosureTypeDeclarationRegex.Replace(sourceCode, "Shader"), - methodFixedCode = LambdaMethodDeclarationRegex.Replace(typeFixedCode, m => $"// {m.Value}{Environment.NewLine} internal void Main"); - - // Workaround for some local methods not being decompiled correctly - if (!methodFixedCode.Contains("internal void Main")) - { - string - methodOnlySourceCode = DecompileMethodOrDeclaringType(methodInfo, true), - methodOnlyFixedSourceCode = LambdaMethodDeclarationRegex.Replace(methodOnlySourceCode, m => $"// {m.Value}{Environment.NewLine} internal void Main"), - methodOnlyIndentedSourceCode = $" {methodOnlyFixedSourceCode.Replace(Environment.NewLine, $"{Environment.NewLine} ")}"; - - int lastClosedBracketsIndex = methodFixedCode.LastIndexOf('}'); - methodFixedCode = methodFixedCode.Insert(lastClosedBracketsIndex, methodOnlyIndentedSourceCode); - } - - // Unwrap the nested fields - string unwrappedSourceCode = UnwrapSyntaxTree(methodFixedCode); + // Decompile the method source + string sourceCode = DecompileMethodOrDeclaringType(methodInfo); // Remove the in keyword from the source - string inFixedSourceCode = Regex.Replace(unwrappedSourceCode, @"(?|]", "_")), - prototype = methodFixedCode.Split(Environment.NewLine)[0], - commentedSourceCode = $"// {methodInfo.Name}{Environment.NewLine}{methodFixedCode}", + methodWithoutAttributes = CSharpSyntaxTree + .ParseText(methodFixedCode) + .GetRoot() + .DescendantNodes() + .OfType() + .First() + .WithAttributeLists(default) + .ToString(), + prototype = methodWithoutAttributes.Split(Environment.NewLine)[0], + commentedSourceCode = $"// {methodInfo.Name}{Environment.NewLine}{methodWithoutAttributes}", inFixedSourceCode = Regex.Replace(commentedSourceCode, @"(? - /// A used to preprocess the closure type declarations for both lambda expressions and local methods - /// - private static readonly Regex ClosureTypeDeclarationRegex = new Regex(@"(?<=private sealed class )<\w*>[\w_]+", RegexOptions.Compiled); - - /// - /// A used 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); - - /// - /// A used to find fields that represent nested closure types - /// - private static readonly Regex NestedClosureFieldRegex = new Regex(@"(?<=public )((?:\w+\.)+<>[\w_]+) (CS\$<>[\w_]+)(?=;)", RegexOptions.Compiled); - - /// - /// A used to identify compiler generated fields - /// - private static readonly Regex CompilerGeneratedFieldRegex = new Regex(@"CS\$<>[\w_]+\.", RegexOptions.Compiled); - - /// - /// Unwraps all the nested captured fields in the given source code, moving them to the top level - /// - /// The input source code to process - [Pure] - private string UnwrapSyntaxTree(string source) - { - List parsedFields = new List(); - - // Local function to recursively extract all the nested fields - void ParseNestedFields(string typeSource) - { - // Find the field declarations - Match match = NestedClosureFieldRegex.Match(typeSource); - if (!match.Success) return; - - // Load the nested closure type - string fullname = match.Groups[1].Value.Replace(".<>", "+<>"); // Fullname of a nested type - Type type = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType(fullname)).First(t => t != null); - - // Decompile the type and get a readable source code - EntityHandle typeHandle = MetadataTokenHelpers.TryAsEntityHandle(type.MetadataToken) ?? throw new InvalidOperationException(); - CSharpDecompiler decompiler = Decompilers[type.Assembly.Location]; - string - sourceCode = decompiler.DecompileAsString(typeHandle), - typeFixedCode = ClosureTypeDeclarationRegex.Replace(sourceCode, "Scope"); - - // Load the syntax tree and retrieve the list of fields - SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(typeFixedCode); - FieldDeclarationSyntax[] fields = syntaxTree.GetRoot().DescendantNodes().OfType().First().ChildNodes().OfType().ToArray(); - - // Add the captured fields - foreach (FieldDeclarationSyntax field in fields) - if (!field.Declaration.Variables.ToFullString().StartsWith("CS$<>")) - parsedFields.Add(field); - - // Explore the new decompiled type - ParseNestedFields(typeFixedCode); - } - - ParseNestedFields(source); - - if (parsedFields.Count > 0) - { - // Build the aggregated string with all the captured fields - StringBuilder builder = new StringBuilder(); - foreach (FieldDeclarationSyntax field in parsedFields) - builder.AppendLine(field.ToFullString()); - string fields = builder.ToString().TrimEnd(' ', '\r', '\n'); - - // Replace the field declarations - Match match = NestedClosureFieldRegex.Match(source); - source = source.Remove(match.Index - 11, match.Length + 12); // leading " public " and trailing ";" - source = source.Insert(match.Index - 11, fields); - - // Adjust the method body to remove references to compiler generated fields - source = CompilerGeneratedFieldRegex.Replace(source, string.Empty); - } - - return source; - } - /// /// Refactors all the inline out expressions with a variable declaration /// @@ -308,7 +220,12 @@ namespace ComputeSharp.Shaders.Translation // Load the syntax tree and the entry node SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source); - MethodDeclarationSyntax rootNode = syntaxTree.GetRoot().DescendantNodes().OfType().First(node => node.GetLeadingTrivia().ToFullString().Contains(entryPoint)); + MethodDeclarationSyntax rootNode = syntaxTree + .GetRoot() + .DescendantNodes() + .OfType() + .First(node => node.Identifier.ToString().Equals(entryPoint) || + node.GetLeadingTrivia().ToFullString().Contains(entryPoint)); // Get the out declarations to replace var outs = ( diff --git a/src/ComputeSharp.Shaders/Translation/Models/CachedShader.cs b/src/ComputeSharp.Shaders/Translation/Models/CachedShader{T}.cs similarity index 75% rename from src/ComputeSharp.Shaders/Translation/Models/CachedShader.cs rename to src/ComputeSharp.Shaders/Translation/Models/CachedShader{T}.cs index 8c5cf20c..3b0005e0 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/CachedShader.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/CachedShader{T}.cs @@ -5,12 +5,14 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// A that contains info on a cached shader /// - internal readonly struct CachedShader + /// The type of compute shader in use + internal readonly struct CachedShader + where T : struct, IComputeShader { /// /// The instance with the shader metadata /// - public readonly ShaderLoader Loader; + public readonly ShaderLoader Loader; /// /// The compiled shader bytecode @@ -22,7 +24,7 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// The instance with the shader metadata /// The compiled shader bytecode - public CachedShader(ShaderLoader loader, ShaderBytecode bytecode) + public CachedShader(ShaderLoader loader, ShaderBytecode bytecode) { Loader = loader; Bytecode = bytecode; diff --git a/src/ComputeSharp.Shaders/Translation/Models/ShaderKey.cs b/src/ComputeSharp.Shaders/Translation/Models/ShaderKey.cs new file mode 100644 index 00000000..89c3cd1d --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/Models/ShaderKey.cs @@ -0,0 +1,85 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace ComputeSharp.Shaders.Translation.Models +{ + /// + /// A representing a key for a given shader + /// + [StructLayout(LayoutKind.Explicit)] + internal readonly struct ShaderKey : IEquatable + { + /// + /// The hashcode of the current shader type + /// + [FieldOffset(0)] + private readonly int Id; + + /// + /// The number of iterations to run on the X axis + /// + [FieldOffset(4)] + private readonly int ThreadsX; + + /// + /// The number of iterations to run on the Y axis + /// + [FieldOffset(8)] + private readonly int ThreadsY; + + /// + /// The number of iterations to run on the Z axis + /// + [FieldOffset(12)] + private readonly int ThreadsZ; + + /// + /// Creates a new instance with the specified parameters + /// + /// The hashcode of the current shader type + /// The number of iterations to run on the X axis + /// The number of iterations to run on the Y axis + /// The number of iterations to run on the Z axis + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ShaderKey(int id, int threadsX, int threadsY, int threadsZ) + { + Id = id; + ThreadsX = threadsX; + ThreadsY = threadsY; + ThreadsZ = threadsZ; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Equals(ShaderKey other) + { + return + Unsafe.As(ref Unsafe.AsRef(Id)) + == Unsafe.As(ref Unsafe.AsRef(other.Id)) && + Unsafe.As(ref Unsafe.AsRef(ThreadsY)) + == Unsafe.As(ref Unsafe.AsRef(other.ThreadsY)); + } + + /// + public override bool Equals(object? obj) + { + return obj is ShaderKey other && Equals(other); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override int GetHashCode() + { + ulong ul0 = Unsafe.As(ref Unsafe.AsRef(Id)); + + int hash = unchecked((int)ul0) ^ (int)(ul0 >> 32); + + ulong ul1 = Unsafe.As(ref Unsafe.AsRef(ThreadsY)); + + hash = (hash << 5) + hash + unchecked((int)ul1) ^ ((int)(ul1 >> 32)); + + return hash; + } + } +} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs index 93c32d04..c0421fde 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; -using ComputeSharp.Shaders.Mappings; namespace ComputeSharp.Shaders.Translation { @@ -15,99 +14,102 @@ namespace ComputeSharp.Shaders.Translation internal static class ShaderHashCodeProvider { /// - /// The mapping of hashcodes to aggregate hashing functions + /// A type containing static info for a given shader type /// - private static readonly Dictionary HasherMapping = new Dictionary(); - - /// - /// Gets a unique hashcode for the input shader closure - /// - /// The input representing the shader to run - [Pure] - public static int GetHashCode(Action action) + /// The type of compute shader currently in use + private static class TypeInfo + where T : struct, IComputeShader { - // Get the delegate hashcode - MethodInfo methodInfo = action.Method; - int hash = methodInfo.GetHashCode(); + /// + /// The id of the compute shader type in use + /// + public static readonly int Id; - if (!HasherMapping.TryGetValue(hash, out Hasher? hasher)) + /// + /// The optional instance, if needed + /// + public static readonly Hasher? Hasher; + + /// + /// Initializes the static members of the type + /// + static TypeInfo() { - // Get the candidate fields for delegate checking + Id = HashCode.Combine(typeof(T)); + + // Get the valid delegates for delegate checking FieldInfo[] delegateFieldInfos = ( - from fieldInfo in methodInfo.DeclaringType.GetFields() - where fieldInfo.FieldType.IsDelegate() && - fieldInfo.FieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) || HlslKnownTypes.IsKnownVectorType(type)) + from fieldInfo in typeof(T).GetFields() + where fieldInfo.FieldType.IsDelegate() select fieldInfo).ToArray(); - // If at least one captured delegate is present, build the hasher method - hasher = delegateFieldInfos.Length == 0 ? null : BuildDynamicHasher(action.Method.DeclaringType, delegateFieldInfos); - HasherMapping.Add(hash, hasher); + // If at least one delegate is present, build the hasher method + if (delegateFieldInfos.Length > 0) + { + Hasher = BuildDynamicHasher(delegateFieldInfos); + } } + } - // Aggregate the hash of the captured delegates, if needed - if (hasher != null) hash = hasher(hash, action.Target); + /// + /// Gets a unique hashcode for the input compute shader instance + /// + /// The type of compute shader currently in use + /// The input instance representing the shader to run + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int GetHashCode(in T shader) + where T : struct, IComputeShader + { + int hash = TypeInfo.Id; + + Hasher? hasher = TypeInfo.Hasher; + + if (hasher != null) hash = hasher(hash, shader); return hash; } /// - /// A that represents an aggregate hash function for a given instance + /// A that represents an aggregate hash function for a given instance /// + /// The type of compute shader currently in use /// The initial hash value - /// The closure instance to use to compute the final hash value + /// The compute shader instance to use to compute the final hash value /// The final hash value for the input closure - private delegate int Hasher(int hash, object instance); + private delegate int Hasher(int hash, in T shader) + where T : struct, IComputeShader; /// - /// Builds a new instance for the target and sequence of values + /// Builds a new instance for the target and sequence of values /// - /// The declaring to analyze + /// The type of compute shader currently in use /// The list of captured fields to inspect [Pure] - private static Hasher BuildDynamicHasher(Type declaringType, IReadOnlyCollection fieldInfos) + private static Hasher BuildDynamicHasher(IReadOnlyCollection fieldInfos) + where T : struct, IComputeShader { - return DynamicMethod.New(il => + return DynamicMethod>.New(il => { - // Declare the local variable to store the target instance - il.DeclareLocal(declaringType); - - // Load the argument (the object instance) - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Castclass, declaringType); - il.Emit(OpCodes.Stloc_0); - - // Unroll the member access MethodInfo - validateDelegateInfo = typeof(ShaderHashCodeProvider).GetMethod(nameof(ValidateDelegate), BindingFlags.NonPublic | BindingFlags.Static), getMethodInfo = typeof(Delegate).GetProperty(nameof(Delegate.Method)).GetMethod, - getHashCodeInfo = typeof(object).GetMethod(nameof(GetHashCode)); + getHashCodeInfo = typeof(object).GetMethod(nameof(object.GetHashCode)); foreach (FieldInfo fieldInfo in fieldInfos) { - Label label = il.DefineLabel(); - - // if (fieldInfo.GetValue(obj) != null) { - il.Emit(OpCodes.Ldloc_0); - il.Emit(OpCodes.Ldfld, fieldInfo); - il.Emit(OpCodes.Brfalse_S, label); - - // if (ValidateDelegate(field)) { - il.Emit(OpCodes.Ldloc_0); - il.Emit(OpCodes.Ldfld, fieldInfo); - il.EmitCall(OpCodes.Call, validateDelegateInfo, null); - il.Emit(OpCodes.Brfalse_S, label); - - // hash = hash * 17 + field.Method.GetHashCode(); + // (hashcode << 5) + hashcode il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Ldc_I4_S, (byte)17); - il.Emit(OpCodes.Mul); - il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldc_I4_5); + il.Emit(OpCodes.Shl); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Add); + + // hashcode += shader.Function[#].Method.GetHashCode(); + il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldfld, fieldInfo); il.EmitCall(OpCodes.Callvirt, getMethodInfo, null); il.EmitCall(OpCodes.Callvirt, getHashCodeInfo, null); il.Emit(OpCodes.Add); il.Emit(OpCodes.Starg_S, (byte)0); - - il.MarkLabel(label); } // Return the computed hash @@ -115,18 +117,5 @@ namespace ComputeSharp.Shaders.Translation il.Emit(OpCodes.Ret); }); } - - /// - /// A method that checks whether an input is supported in HLSL - /// - /// The input instance to check - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool ValidateDelegate(Delegate candidate) - { - MethodInfo methodInfo = candidate.Method; - return (methodInfo.IsStatic || methodInfo.DeclaringType.IsStatelessDelegateContainer()) && - (HlslKnownTypes.IsKnownScalarType(methodInfo.ReturnType) || HlslKnownTypes.IsKnownVectorType(methodInfo.ReturnType)); - } } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs similarity index 56% rename from src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs rename to src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs index c1aad0c1..24814bdf 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs @@ -2,7 +2,6 @@ using System.Buffers; using System.Collections.Generic; using System.Diagnostics.Contracts; -using System.Linq; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -12,8 +11,8 @@ using ComputeSharp.Shaders.Translation.Models; namespace ComputeSharp.Shaders.Translation { - /// - internal sealed partial class ShaderLoader + /// + internal sealed partial class ShaderLoader { /// /// The number of captured graphics resources (buffers) @@ -34,22 +33,22 @@ namespace ComputeSharp.Shaders.Translation private readonly List _CapturedMembers = new List(); /// - /// A that loads all the captured members from a shader closure + /// A that loads all the captured members from a shader instance /// - /// The shader closure instance to load the data from + /// The shader instance to load the data from /// A reference to the buffer with all the captured instances /// A reference to the buffer to use to store all the captured value types - private delegate void DispatchDataLoader(object obj, ref GraphicsResource r0, ref byte r1); + private delegate void DispatchDataLoader(in T shader, ref GraphicsResource r0, ref byte r1); /// /// Gets a new instance with all the captured data for the current shader instance /// - /// The input representing the compute shader to run + /// The input instance representing the compute shader to run /// The number of iterations to run on the X axis /// The number of iterations to run on the Y axis /// The number of iterations to run on the Z axis [Pure] - public DispatchData GetDispatchData(Action action, int x, int y, int z) + public DispatchData GetDispatchData(in T shader, int x, int y, int z) { // Resources and variables buffers GraphicsResource[] resources = ArrayPool.Shared.Rent(_ResourcesCount); @@ -63,7 +62,7 @@ namespace ComputeSharp.Shaders.Translation Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; // Invoke the dynamic method to extract the captured data - _DispatchDataLoader!(action.Target, ref r0, ref r1); + _DispatchDataLoader!(shader, ref r0, ref r1); return new DispatchData(resources, _ResourcesCount, variables, _VariablesByteSize); } @@ -73,66 +72,8 @@ namespace ComputeSharp.Shaders.Translation /// private void BuildDispatchDataLoader() { - // Mapping of parent members to index of the relative local variable - var map = - _CapturedMembers - .Where(m => !m.IsStatic && m.Parents != null) - .SelectMany(m => m.Parents) - .Distinct() - .Select((m, i) => (Member: m, Index: i)) - .ToDictionary(p => (object)p.Member, p => p.Index + 1); - object root = new object(); // Placeholder - map.Add(root, 0); - - // Set of indices of the loaded parent members - HashSet loaded = new HashSet(new[] { 0 }); - - // Build the dynamic IL method _DispatchDataLoader = DynamicMethod.New(il => { - // Loads a given member on the top of the execution stack - void LoadMember(ReadableMember member) - { - if (!member.IsStatic) - { - // Load the parent instance on the execution stack if the member isn't static - int index = map[member.Parents?.Last() ?? root]; - if (loaded.Contains(index)) il.EmitLoadLocal(index); - else - { - // Seek upwards to find the most in depth loaded parent - int i = member.Parents!.Count - 1; - while (i > 0 && !loaded.Contains(map[member.Parents[i]])) i--; - - // Load the local variables for all the parents of the current member - il.EmitLoadLocal(i); - for (; i < member.Parents.Count; i++) - { - index = map[member.Parents[i]]; - il.Emit(OpCodes.Ldfld, member.Parents[i]); - il.EmitStoreLocal(index); - il.EmitLoadLocal(index); - loaded.Add(index); - } - } - } - - il.EmitReadMember(member); - } - - // Declare the local variables - il.DeclareLocal(ShaderType); - foreach (ReadableMember member in map.OrderBy(p => p.Value).Skip(1).Select(p => p.Key)) - { - il.DeclareLocal(member.MemberType); - } - - // Cast the closure instance and assign it to the local variable - il.Emit(OpCodes.Ldarg_0); - il.EmitCastOrUnbox(ShaderType); - il.Emit(OpCodes.Stloc_0); - - // Handle all the captured members, both resources and variables foreach (ReadableMember member in _CapturedMembers) { if (HlslKnownTypes.IsKnownBufferType(member.MemberType)) @@ -155,11 +96,11 @@ namespace ComputeSharp.Shaders.Translation } else throw new InvalidOperationException($"Invalid captured member of type {member.MemberType}"); - /* Load the current member accordingly. - * When this method returns, the value of the current - * member will be at the top of the execution stack */ - LoadMember(member); + // Load the reference to the input delegate if the member is not static + if (!member.IsStatic) il.Emit(OpCodes.Ldarg_0); + // Read the current member and store it to the target address + il.EmitReadMember(member); il.EmitStoreToAddress(member.MemberType); } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs similarity index 76% rename from src/ComputeSharp.Shaders/Translation/ShaderLoader.cs rename to src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index fbf49dc5..0541da9a 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -21,24 +21,16 @@ using ParameterInfo = ComputeSharp.Shaders.Renderer.Models.Functions.ParameterIn namespace ComputeSharp.Shaders.Translation { /// - /// A responsible for loading and processing instances + /// A responsible for loading and processing shaders of a given type /// - internal sealed partial class ShaderLoader + /// The type of compute shader currently in use + internal sealed partial class ShaderLoader + where T : struct, IComputeShader { /// - /// The that represents the shader to load + /// Creates a new instance /// - private readonly Action Action; - - /// - /// Creates a new with the specified parameters - /// - /// The to use to build the shader - private ShaderLoader(Action action) - { - Action = action; - ShaderType = action.Method.DeclaringType; - } + private ShaderLoader() { } /// /// The number of constant buffers to define in the shader @@ -55,17 +47,12 @@ namespace ComputeSharp.Shaders.Translation /// private int _ReadWriteBuffersCount; - /// - /// Gets the closure for the field - /// - public Type ShaderType { get; } - /// /// The of items that are required to load the captured values /// private readonly List DescriptorRanges = new List(); - private RootParameter1[] _RootParameters; + private RootParameter1[]? _RootParameters; /// /// Gets the array for the current shader @@ -111,17 +98,22 @@ namespace ComputeSharp.Shaders.Translation public IReadOnlyList LocalFunctionsList => _LocalFunctionsList; /// - /// Loads and processes an input + /// Loads and processes an input shadeer /// - /// The to use to build the shader + /// The instance to use to build the shader /// A new instance representing the input shader [Pure] - public static ShaderLoader Load(Action action) + public static ShaderLoader Load(in T shader) { - ShaderLoader @this = new ShaderLoader(action); + ShaderLoader @this = new ShaderLoader(); - @this.LoadFieldsInfo(); - @this.LoadMethodSource(); + /* Reading members through reflection requires an object parameter, + * so here we're just boxing the input shader once to avoid allocating + * it multiple times in the managed heap while processing the shader. */ + object box = shader; + + @this.LoadFieldsInfo(box); + @this.LoadMethodSource(box); @this.BuildDispatchDataLoader(); return @this; @@ -130,10 +122,16 @@ namespace ComputeSharp.Shaders.Translation /// /// Loads the fields info for the current shader being loaded /// - private void LoadFieldsInfo() + /// The boxed instance to use to build the shader + private void LoadFieldsInfo(object shader) { - IReadOnlyList shaderFields = ShaderType.GetFields().ToArray(); - if (shaderFields.Any(fieldInfo => fieldInfo.IsStatic)) throw new InvalidOperationException("Empty shader body"); + IReadOnlyList shaderFields = typeof(T).GetFields( + BindingFlags.Instance | + BindingFlags.Static | + BindingFlags.Public | + BindingFlags.NonPublic).ToArray(); + + if (shaderFields.Count == 0) throw new InvalidOperationException("Empty shader body"); // Descriptor for the buffer for captured scalar/vector variables DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount++)); @@ -141,17 +139,17 @@ namespace ComputeSharp.Shaders.Translation // Inspect the captured fields foreach (FieldInfo fieldInfo in shaderFields) { - LoadFieldInfo(fieldInfo); + LoadFieldInfo(shader, fieldInfo); } } /// /// Loads a specified and adds it to the shader model /// + /// The boxed instance to use to build the shader /// The target to load /// The optional explicit name to use for the field - /// The list of parent fields to reach the current from a given - private void LoadFieldInfo(ReadableMember memberInfo, string? name = null, IReadOnlyList? parents = null) + private void LoadFieldInfo(object shader, ReadableMember memberInfo, string? name = null) { Type fieldType = memberInfo.MemberType; string fieldName = HlslKnownKeywords.GetMappedName(name ?? memberInfo.Name); @@ -161,8 +159,6 @@ namespace ComputeSharp.Shaders.Translation { DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount)); - // Track the buffer field - memberInfo.Parents = parents; _CapturedMembers.Add(memberInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); @@ -173,8 +169,6 @@ namespace ComputeSharp.Shaders.Translation // Root parameter for a readonly buffer DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ShaderResourceView, 1, _ReadOnlyBuffersCount)); - // Track the buffer field - memberInfo.Parents = parents; _CapturedMembers.Add(memberInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); @@ -185,8 +179,6 @@ namespace ComputeSharp.Shaders.Translation // Root parameter for a read write buffer DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.UnorderedAccessView, 1, _ReadWriteBuffersCount)); - // Track the buffer field - memberInfo.Parents = parents; _CapturedMembers.Add(memberInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); @@ -194,48 +186,36 @@ namespace ComputeSharp.Shaders.Translation } else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType)) { - // Register the captured field - memberInfo.Parents = parents; _CapturedMembers.Add(memberInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); _FieldsList.Add(new CapturedFieldInfo(fieldType, typeName, fieldName)); } - else if (fieldType.IsClass && fieldName.StartsWith("CS$<>")) - { - // Captured scope, update the parents list - List updatedParents = parents?.ToList() ?? new List(); - updatedParents.Add(memberInfo); - - // Recurse on the new compiler generated class - IReadOnlyList fields = fieldType.GetFields().ToArray(); - foreach (FieldInfo fieldInfo in fields) - { - LoadFieldInfo(fieldInfo, null, updatedParents); - } - } else if (fieldType.IsDelegate() && - memberInfo.GetValue(Action.Target) is Delegate func && + memberInfo.GetValue(shader) is Delegate func && (func.Method.IsStatic || func.Method.DeclaringType.IsStatelessDelegateContainer()) && (HlslKnownTypes.IsKnownScalarType(func.Method.ReturnType) || HlslKnownTypes.IsKnownVectorType(func.Method.ReturnType)) && fieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) || HlslKnownTypes.IsKnownVectorType(type))) { // Captured static delegates with a return type - LoadStaticMethodSource(fieldName, func.Method); + LoadStaticMethodSource(shader, fieldName, func.Method); } + else throw new ArgumentException($"Invalid captured variable of type {fieldType} with name \"{memberInfo.Name}\""); } /// /// Loads the entry method for the current shader being loaded /// - private void LoadMethodSource() + /// The boxed instance to use to build the shader + private void LoadMethodSource(object shader) { // Decompile the shader method - MethodDecompiler.Instance.GetSyntaxTree(Action.Method, MethodType.Closure, out MethodDeclarationSyntax root, out SemanticModel semanticModel); + MethodInfo methodInfo = typeof(T).GetMethod(nameof(IComputeShader.Execute)); + MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Execute, out MethodDeclarationSyntax root, out SemanticModel semanticModel); // Rewrite the shader method (eg. to fix the type declarations) - ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, ShaderType); + ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, typeof(T)); root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root); // Extract the implicit local functions @@ -253,18 +233,18 @@ namespace ComputeSharp.Shaders.Translation // Register the captured static members foreach (var member in syntaxRewriter.StaticMembers) { - LoadFieldInfo(member.Value, member.Key); + LoadFieldInfo(shader, member.Value, member.Key); } // Register the captured static methods foreach (var method in syntaxRewriter.StaticMethods) { - LoadStaticMethodSource(method.Key, method.Value); + LoadStaticMethodSource(shader, method.Key, method.Value); } // Get the thread ids identifier name and shader method body ThreadsIdsVariableName = root.ParameterList.Parameters.First().Identifier.Text; - MethodBody = root.Body.ToFullString(); + MethodBody = root.Body!.ToFullString(); // Additional preprocessing MethodBody = Regex.Replace(MethodBody, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value); @@ -275,9 +255,10 @@ namespace ComputeSharp.Shaders.Translation /// /// Loads additional static methods used by the shader /// + /// The boxed instance to use to build the shader /// The HLSL name of the new method to load /// The instance for the method to load - private void LoadStaticMethodSource(string name, MethodInfo methodInfo) + private void LoadStaticMethodSource(object shader, string name, MethodInfo methodInfo) { // Decompile the target method MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Static, out MethodDeclarationSyntax root, out SemanticModel semanticModel); @@ -289,26 +270,26 @@ namespace ComputeSharp.Shaders.Translation // Register the captured static members foreach (var member in syntaxRewriter.StaticMembers) { - LoadFieldInfo(member.Value, member.Key); + LoadFieldInfo(shader, member.Value, member.Key); } // Register the captured static methods foreach (var method in syntaxRewriter.StaticMethods) { - LoadStaticMethodSource(method.Key, method.Value); + LoadStaticMethodSource(shader, method.Key, method.Value); } // Get the function parameters IReadOnlyList parameters = ( from parameter in root.ParameterList.Parameters.Select((p, i) => (Node: p, Index: i)) let modifiers = parameter.Node.Modifiers - let type = parameter.Node.Type.ToFullString() + let type = parameter.Node.Type!.ToFullString() let parameterName = parameter.Node.Identifier.ToFullString() let last = parameter.Index == root.ParameterList.Parameters.Count - 1 select new ParameterInfo(modifiers, type, parameterName, last)).ToArray(); // Get the function body - string body = root.Body.ToFullString(); + string body = root.Body!.ToFullString(); body = Regex.Replace(body, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value); body = body.TrimEnd('\n', '\r', ' '); body = HlslKnownKeywords.GetMappedText(body); diff --git a/src/ComputeSharp/ComputeSharp.nuspec b/src/ComputeSharp/ComputeSharp.nuspec index 2f661804..7bbc3e6c 100644 --- a/src/ComputeSharp/ComputeSharp.nuspec +++ b/src/ComputeSharp/ComputeSharp.nuspec @@ -2,7 +2,7 @@ ComputeSharp - 1.3.1 + 2.0.0 ComputeSharp Sergio Pedri Sergio Pedri @@ -12,17 +12,18 @@ false A .NET Standard 2.1 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders Bug fixes, NuGet updates - Copyright (c) 2019 Sergio Pedri + Copyright (c) 2020 Sergio Pedri dotnet net netcore netstandard csharp library graphics shader hlsl compute gpu - - - - - - + + + + + + + diff --git a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs index db36a328..7bd3d7e2 100644 --- a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs +++ b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs @@ -1,5 +1,4 @@ -using System; -using ComputeSharp.Graphics; +using ComputeSharp.Graphics; using ComputeSharp.Shaders; namespace ComputeSharp @@ -12,33 +11,49 @@ namespace ComputeSharp /// /// Compiles and runs the input shader on a target instance, with the specified parameters /// + /// The type of compute shader to run /// The to use to run the shader /// The number of iterations to run on the X axis - /// The input representing the compute shader to run - public static void For(this GraphicsDevice device, int x, Action action) => ShaderRunner.Run(device, x, 1, 1, action); + /// The input instance representing the compute shader to run + public static void For(this GraphicsDevice device, int x, in T shader) + where T : struct, IComputeShader + { + ShaderRunner.Run(device, x, 1, 1, shader); + } /// /// Compiles and runs the input shader on a target instance, with the specified parameters /// + /// The type of compute shader to run /// The to use to run the shader /// The number of iterations to run on the X axis /// The number of iterations to run on the Y axis - /// The input representing the compute shader to run - public static void For(this GraphicsDevice device, int x, int y, Action action) => ShaderRunner.Run(device, x, y, 1, action); + /// The input instance representing the compute shader to run + public static void For(this GraphicsDevice device, int x, int y, in T shader) + where T : struct, IComputeShader + { + ShaderRunner.Run(device, x, y, 1, shader); + } /// /// Compiles and runs the input shader on a target instance, with the specified parameters /// + /// The type of compute shader to run /// The to use to run the shader /// The number of iterations to run on the X axis /// The number of iterations to run on the Y axis /// The number of iterations to run on the Z axis - /// The input representing the compute shader to run - public static void For(this GraphicsDevice device, int x, int y, int z, Action action) => ShaderRunner.Run(device, x, y, z, action); + /// The input instance representing the compute shader to run + public static void For(this GraphicsDevice device, int x, int y, int z, in T shader) + where T : struct, IComputeShader + { + ShaderRunner.Run(device, x, y, z, shader); + } /// /// Compiles and runs the input shader on a target instance, with the specified parameters /// + /// The type of compute shader to run /// The to use to run the shader /// The number of iterations to run on the X axis /// The number of iterations to run on the Y axis @@ -46,11 +61,15 @@ namespace ComputeSharp /// The number of threads in each thread group for the X axis /// The number of threads in each thread group for the Y axis /// The number of threads in each thread group for the Z axis - /// The input representing the compute shader to run - public static void For( + /// The input instance representing the compute shader to run + public static void For( this GraphicsDevice device, int x, int y, int z, int threadsX, int threadsY, int threadsZ, - Action action) => ShaderRunner.Run(device, x, y, z, threadsX, threadsY, threadsZ, action); + in T shader) + where T : struct, IComputeShader + { + ShaderRunner.Run(device, x, y, z, threadsX, threadsY, threadsZ, shader); + } } } diff --git a/src/ComputeSharp/Gpu.cs b/src/ComputeSharp/Gpu.cs index 75507597..26ae6399 100644 --- a/src/ComputeSharp/Gpu.cs +++ b/src/ComputeSharp/Gpu.cs @@ -21,6 +21,11 @@ namespace ComputeSharp { Devices = DeviceHelper.QueryAllSupportedDevices(); IsSupported = Devices.Any(); + + if (IsSupported) + { + _Default = new GraphicsDevice(Devices[0].Device, Devices[0].Description); + } } /// @@ -28,25 +33,17 @@ namespace ComputeSharp /// private static readonly IReadOnlyList<(ID3D12Device Device, AdapterDescription Description)> Devices; - /// - /// 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; } - - private static GraphicsDevice? _Default; + private static readonly GraphicsDevice? _Default; /// /// Gets the default instance for the current machine /// - public static GraphicsDevice Default - { - get - { - if (!IsSupported) throw new NotSupportedException("There isn't a supported GPU device on the current machine"); + public static GraphicsDevice Default => _Default ?? throw new NotSupportedException("There isn't a supported GPU device on the current machine"); - return _Default ??= new GraphicsDevice(Devices[0].Device, Devices[0].Description); - } - } + /// + /// 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; } /// /// Enumerates all the available objects on the current machine diff --git a/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj b/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj index 6f0f9fe8..518343ba 100644 --- a/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj +++ b/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj @@ -1,15 +1,15 @@  - netcoreapp3.0 + netcoreapp3.1 false - - - + + + diff --git a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs index bd0dfa99..c973bdd0 100644 --- a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs +++ b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs @@ -8,25 +8,48 @@ namespace ComputeSharp.Tests.Internals [TestCategory("ShaderHashCodes")] public class ShaderHashCodeTests { + public struct Shader1 : IComputeShader + { + public float A; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = A; + } + } + [TestMethod] public void ShaderWithNoCapturedDelegates() { float value = 10; using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action1 = id => buffer[0] = value; + Shader1 shader1 = new Shader1 { A = value, B = buffer }; int - hash1 = ShaderHashCodeProvider.GetHashCode(action1), - hash2 = ShaderHashCodeProvider.GetHashCode(action1); + hash1 = ShaderHashCodeProvider.GetHashCode(shader1), + hash2 = ShaderHashCodeProvider.GetHashCode(shader1); Assert.IsTrue(hash1 == hash2); - Action action2 = id => buffer[0] = value; + Shader1 shader2 = new Shader1 { A = value, B = buffer }; - int hash3 = ShaderHashCodeProvider.GetHashCode(action2); + int hash3 = ShaderHashCodeProvider.GetHashCode(shader2); - Assert.IsFalse(hash1 == hash3); + Assert.IsTrue(hash1 == hash3); + } + + public struct Shader2 : IComputeShader + { + public float A; + public ReadWriteBuffer B; + public Func F; + + public void Execute(ThreadIds ids) + { + B[0] = F(A); + } } [TestMethod] @@ -36,17 +59,19 @@ namespace ComputeSharp.Tests.Internals using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = f(2); + Shader2 shader1 = new Shader2 { A = 1, B = buffer, F = f }; int - hash1 = ShaderHashCodeProvider.GetHashCode(action), - hash2 = ShaderHashCodeProvider.GetHashCode(action); + hash1 = ShaderHashCodeProvider.GetHashCode(shader1), + hash2 = ShaderHashCodeProvider.GetHashCode(shader1); Assert.IsTrue(hash1 == hash2); f = x => x + 1; - int hash3 = ShaderHashCodeProvider.GetHashCode(action); + Shader2 shader2 = new Shader2 { A = 1, B = buffer, F = f }; + + int hash3 = ShaderHashCodeProvider.GetHashCode(shader2); Assert.IsFalse(hash1 == hash3); } diff --git a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj index 6f0f9fe8..518343ba 100644 --- a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj +++ b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj @@ -1,15 +1,15 @@  - netcoreapp3.0 + netcoreapp3.1 false - - - + + + diff --git a/tests/ComputeSharp.Tests/HlslVectorTypesTests.cs b/tests/ComputeSharp.Tests/HlslVectorTypesTests.cs index def28124..46dc389e 100644 --- a/tests/ComputeSharp.Tests/HlslVectorTypesTests.cs +++ b/tests/ComputeSharp.Tests/HlslVectorTypesTests.cs @@ -7,18 +7,50 @@ namespace ComputeSharp.Tests [TestCategory("HlslVectorTypes")] public class HlslVectorTypesTests { + private struct SequentialCompilation_Shader_1 : IComputeShader + { + public Float2 F2; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = F2.XY; + } + } + + private struct SequentialCompilation_Shader_2 : IComputeShader + { + public Float2 F2; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[1] = F2.XY; + } + } + [TestMethod] public void SequentialCompilation() { Float2 f2 = new Float2(1, 2); using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action1 = id => buffer[0] = f2.YX; + var shader1 = new SequentialCompilation_Shader_1 { F2 = f2, B = buffer }; + var shader2 = new SequentialCompilation_Shader_2 { F2 = f2, B = buffer }; - Action action2 = id => buffer[1] = f2.YX; + Gpu.Default.For(1, shader1); + Gpu.Default.For(1, shader2); + } - Gpu.Default.For(1, action1); - Gpu.Default.For(1, action2); + private struct LocalFloatAssignToFloat2Buffer_Shader : IComputeShader + { + public Float2 F2; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = F2.YX; + } } [TestMethod] @@ -27,9 +59,9 @@ namespace ComputeSharp.Tests Float2 f2 = new Float2(1, 2); using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = f2.YX; + var shader = new LocalFloatAssignToFloat2Buffer_Shader { F2 = f2, B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); Float2[] result = buffer.GetData(); @@ -37,29 +69,50 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[0].Y - f2.X) < 0.0001f); } + private struct Int2Properties_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = 1; + } + } + [TestMethod] public void Int2Properties() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0].X = 1; + var shader = new Int2Properties_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); Int2[] result = buffer.GetData(); Assert.IsTrue(result[0].X == 1); } + private struct LocalBoolAssignToBool2Buffer_Shader : IComputeShader + { + public Bool2 B2; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = B2; + } + } + [TestMethod] public void LocalBoolAssignToBool2Buffer() { Bool2 b2 = Bool2.TrueY; using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = b2; + var shader = new LocalBoolAssignToBool2Buffer_Shader { B2 = b2, B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); Bool2[] result = buffer.GetData(); @@ -67,19 +120,26 @@ namespace ComputeSharp.Tests Assert.IsTrue(result[0].Y == b2.Y); } + private struct Bool3Operations_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = Bool3.TrueX; + B[1] = Bool3.True; + B[2].YZ = Bool2.True; + } + } + [TestMethod] public void Bool3Operations() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(3); - Action action = id => - { - buffer[0] = Bool3.TrueX; - buffer[1] = Bool3.True; - buffer[2].YZ = Bool2.True; - }; + var shader = new Bool3Operations_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); Bool3[] result = buffer.GetData(); diff --git a/tests/ComputeSharp.Tests/InitializationTests.cs b/tests/ComputeSharp.Tests/InitializationTests.cs index 397214ef..1406152f 100644 --- a/tests/ComputeSharp.Tests/InitializationTests.cs +++ b/tests/ComputeSharp.Tests/InitializationTests.cs @@ -17,6 +17,16 @@ namespace ComputeSharp.Tests else Assert.ThrowsException(() => Gpu.Default); } + private struct RunShaderOnAllDevicesShader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[ids.X] = ids.X; + } + } + [TestMethod] public void RunShaderOnAllDevices() { @@ -24,9 +34,9 @@ namespace ComputeSharp.Tests { using (ReadWriteBuffer buffer = gpu.AllocateReadWriteBuffer(100)) { - Action action = id => buffer[id.X] = id.X; + var shader = new RunShaderOnAllDevicesShader { B = buffer }; - gpu.For(100, action); + gpu.For(100, shader); float[] array = buffer.GetData(); float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); diff --git a/tests/ComputeSharp.Tests/InternalStaticMembersTests.cs b/tests/ComputeSharp.Tests/InternalStaticMembersTests.cs index 5cdc6087..ea58abc3 100644 --- a/tests/ComputeSharp.Tests/InternalStaticMembersTests.cs +++ b/tests/ComputeSharp.Tests/InternalStaticMembersTests.cs @@ -39,60 +39,97 @@ namespace ComputeSharp.Tests [TestCategory("StaticFields")] public class InternalStaticMembersTests { + private struct StaticReadonlyScalarFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMembersContainer.ReadonlyFloat; + } + } + [TestMethod] public void StaticReadonlyScalarFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticMembersContainer.ReadonlyFloat; + var shader = new StaticReadonlyScalarFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticMembersContainer.ReadonlyFloat) < 0.0001f); } + private struct StaticScalarFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMembersContainer.StaticFloat; + } + } + [TestMethod] public void StaticScalarFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticMembersContainer.StaticFloat; + var shader = new StaticScalarFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticMembersContainer.StaticFloat) < 0.0001f); } + private struct StaticScalarFieldRepeatedAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMembersContainer.StaticFloat + StaticMembersContainer.StaticFloat; + } + } + [TestMethod] public void StaticScalarFieldRepeatedAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticMembersContainer.StaticFloat + StaticMembersContainer.StaticFloat; + var shader = new StaticScalarFieldRepeatedAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticMembersContainer.StaticFloat * 2) < 0.0001f); } + private struct StaticReadonlyVectorFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticMembersContainer.ReadonlyVector2.X; + else B[1] = StaticMembersContainer.ReadonlyVector2.Y; + } + } + [TestMethod] public void StaticReadonlyVectorFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticMembersContainer.ReadonlyVector2.X; - else buffer[1] = StaticMembersContainer.ReadonlyVector2.Y; - }; + var shader = new StaticReadonlyVectorFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); @@ -100,18 +137,25 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[1] - StaticMembersContainer.ReadonlyVector2.Y) < 0.0001f); } + private struct StaticVectorFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticMembersContainer.StaticVector2.X; + else B[1] = StaticMembersContainer.StaticVector2.Y; + } + } + [TestMethod] public void StaticVectorFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticMembersContainer.StaticVector2.X; - else buffer[1] = StaticMembersContainer.StaticVector2.Y; - }; + var shader = new StaticVectorFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); @@ -119,18 +163,25 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[1] - StaticMembersContainer.StaticVector2.Y) < 0.0001f); } + private struct StaticReadOnlyBufferFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticMembersContainer.StaticBuffer[0]; + else B[1] = StaticMembersContainer.StaticBuffer[1]; + } + } + [TestMethod] public void StaticReadOnlyBufferFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticMembersContainer.StaticBuffer[0]; - else buffer[1] = StaticMembersContainer.StaticBuffer[1]; - }; + var shader = new StaticReadOnlyBufferFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); float[] expected = StaticMembersContainer.StaticBuffer.GetData(); diff --git a/tests/ComputeSharp.Tests/IntrinsicTests.cs b/tests/ComputeSharp.Tests/IntrinsicTests.cs index d6cd3365..b240f081 100644 --- a/tests/ComputeSharp.Tests/IntrinsicTests.cs +++ b/tests/ComputeSharp.Tests/IntrinsicTests.cs @@ -7,22 +7,30 @@ namespace ComputeSharp.Tests [TestCategory("Intrinsics")] public class IntrinsicTests { + private struct IntrinsicWithInlineOutParamater_Shader : IComputeShader + { + public float A; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = Hlsl.Sin(A); + B[1] = Hlsl.Cos(A); + Hlsl.SinCos(A, out float sine, out float cosine); + B[2] = sine; + B[3] = cosine; + } + } + [TestMethod] public void IntrinsicWithInlineOutParamater() { float angle = 80; using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(4); - Action action = id => - { - buffer[0] = Hlsl.Sin(angle); - buffer[1] = Hlsl.Cos(angle); - Hlsl.SinCos(angle, out float sine, out float cosine); - buffer[2] = sine; - buffer[3] = cosine; - }; + var shader = new IntrinsicWithInlineOutParamater_Shader { A = angle, B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -30,40 +38,56 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[1] - result[3]) < 0.0001f); } + private struct IntrinsicWithInlineOutParamaterAndDiscard_Shader : IComputeShader + { + public float A; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = Hlsl.Sin(A); + Hlsl.SinCos(A, out float sine, out _); + B[1] = sine; + } + } + [TestMethod] public void IntrinsicWithInlineOutParamaterAndDiscard() { float angle = 80; using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - buffer[0] = Hlsl.Sin(angle); - Hlsl.SinCos(angle, out float sine, out _); - buffer[1] = sine; - }; + var shader = new IntrinsicWithInlineOutParamaterAndDiscard_Shader { A = angle, B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - result[1]) < 0.0001f); } + private struct IntrinsicWithOutParamaters_Shader : IComputeShader + { + public float A; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = Hlsl.Sin(A); + B[1] = Hlsl.Cos(A); + Hlsl.SinCos(A, out B[2], out B[3]); + } + } + [TestMethod] public void IntrinsicWithOutParamaters() { float angle = 80; using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(4); - Action action = id => - { - buffer[0] = Hlsl.Sin(angle); - buffer[1] = Hlsl.Cos(angle); - Hlsl.SinCos(angle, out buffer[2], out buffer[3]); - }; + var shader = new IntrinsicWithOutParamaters_Shader { A = angle, B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); diff --git a/tests/ComputeSharp.Tests/InvalidShaderTests.cs b/tests/ComputeSharp.Tests/InvalidShaderTests.cs index 393dbfba..a1da283e 100644 --- a/tests/ComputeSharp.Tests/InvalidShaderTests.cs +++ b/tests/ComputeSharp.Tests/InvalidShaderTests.cs @@ -10,24 +10,41 @@ namespace ComputeSharp.Tests [TestCategory("InvalidShader")] public class InvalidShaderTests { - [TestMethod] - public void EmptyShaderCompileError() + private struct EmptyShaderCompileError_Shader : IComputeShader { - Action action = id => { }; - - Assert.ThrowsException(() => Gpu.Default.For(10, action)); + public void Execute(ThreadIds ids) { } } [TestMethod] + [ExpectedException(typeof(InvalidOperationException))] + public void EmptyShaderCompileError() + { + var shader = default(EmptyShaderCompileError_Shader); + + Gpu.Default.For(10, shader); + } + + private struct DeviceMismatchException_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = 1; + } + } + + [TestMethod] + [ExpectedException(typeof(GraphicsDeviceMismatchException))] public void DeviceMismatchException() { ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); GraphicsDevice device = Gpu.EnumerateDevices().First(); - Action action = id => buffer[0] = 1; + var shader = new DeviceMismatchException_Shader { B = buffer }; - Assert.ThrowsException(() => device.For(1, action)); + device.For(1, shader); } } } diff --git a/tests/ComputeSharp.Tests/ShaderClosureTests.cs b/tests/ComputeSharp.Tests/ShaderClosureTests.cs index 808edeaa..40573273 100644 --- a/tests/ComputeSharp.Tests/ShaderClosureTests.cs +++ b/tests/ComputeSharp.Tests/ShaderClosureTests.cs @@ -10,19 +10,33 @@ namespace ComputeSharp.Tests [TestCategory("ShaderClosure")] public class ShaderClosureTests { + private struct LocalScalarAssignToBuffer_Shader : IComputeShader where T : unmanaged + { + public T Value; + public T Zero; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X % 2 == 0) B[ids.X] = Value; + else B[ids.X] = Zero; + } + } + private static void LocalScalarAssignToBuffer(T value, Func equals) where T : unmanaged { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(4); T zero = default; - Action action = id => + var shader = new LocalScalarAssignToBuffer_Shader { - if (id.X % 2 == 0) buffer[id.X] = value; - else buffer[id.X] = zero; + Value = value, + Zero = zero, + B = buffer }; - Gpu.Default.For(4, action); + Gpu.Default.For(4, shader); T[] result = buffer.GetData(); @@ -41,19 +55,27 @@ namespace ComputeSharp.Tests LocalScalarAssignToBuffer(true, (a, b) => a == b); } + private struct ShaderWithBoolType_Shader : IComputeShader + { + public ReadWriteBuffer B; + public ReadWriteBuffer I; + + public void Execute(ThreadIds ids) + { + if (B[ids.X]) I[ids.X] = ids.X + 1; + B[ids.X] = (ids.X % 2) == 0; + } + } + [TestMethod] public void ShaderWithBoolType() { using ReadWriteBuffer bools = Gpu.Default.AllocateReadWriteBuffer(new Bool[] { true, false, true, true }); using ReadWriteBuffer ints = Gpu.Default.AllocateReadWriteBuffer(4); - void Foo(ThreadIds id) - { - if (bools[id.X]) ints[id.X] = id.X + 1; - bools[id.X] = (id.X % 2) == 0; - } + var shader = new ShaderWithBoolType_Shader { B = bools, I = ints }; - Gpu.Default.For(4, Foo); + Gpu.Default.For(4, shader); Bool[] boolResults = bools.GetData(); @@ -70,19 +92,18 @@ namespace ComputeSharp.Tests Assert.IsTrue(intResults[3] == 4); } - [TestMethod] - public void LocalScalarAssignToBufferWithinLocalMethod() + private struct LocalKnownVectorAssignToBuffer_Shader : IComputeShader { - float value = 10; - using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + public Vector4 V4; + public ReadWriteBuffer B; - void Foo(ThreadIds id) => buffer[0] = value; - - Gpu.Default.For(1, Foo); - - float[] result = buffer.GetData(); - - Assert.IsTrue((int)result[0] == (int)value); + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = V4.X; + else if (ids.X == 1) B[1] = V4.Y; + else if (ids.X == 2) B[2] = V4.Z; + else if (ids.X == 3) B[3] = V4.W; + } } [TestMethod] @@ -91,15 +112,9 @@ namespace ComputeSharp.Tests 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; - }; + var shader = new LocalKnownVectorAssignToBuffer_Shader { V4 = vector4, B = buffer }; - Gpu.Default.For(4, action); + Gpu.Default.For(4, shader); float[] result = buffer.GetData(); float[] expected = { 1, 2, 3, 4 }; @@ -107,6 +122,17 @@ namespace ComputeSharp.Tests Assert.IsTrue(result.AsSpan().ContentEquals(expected)); } + private struct CopyBetweenConstantAndWriteableBuffers_Shader : IComputeShader + { + public ConstantBuffer C; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[ids.X] = C[ids.X]; + } + } + [TestMethod] public void CopyBetweenConstantAndWriteableBuffers() { @@ -115,15 +141,26 @@ namespace ComputeSharp.Tests using ConstantBuffer input = Gpu.Default.AllocateConstantBuffer(source); using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(source.Length); - Action action = id => buffer[id.X] = input[id.X]; + var shader = new CopyBetweenConstantAndWriteableBuffers_Shader { C = input, B = buffer }; - Gpu.Default.For(source.Length, action); + Gpu.Default.For(source.Length, shader); float[] result = buffer.GetData(); Assert.IsTrue(result.AsSpan().ContentEquals(source)); } + private struct CopyBetweenReadOnlyAndWriteableBuffers_Shader : IComputeShader + { + public ReadOnlyBuffer IN; + public ReadWriteBuffer OUT; + + public void Execute(ThreadIds ids) + { + OUT[ids.X] = IN[ids.X]; + } + } + [TestMethod] public void CopyBetweenReadOnlyAndWriteableBuffers() { @@ -132,15 +169,26 @@ namespace ComputeSharp.Tests using ReadOnlyBuffer input = Gpu.Default.AllocateReadOnlyBuffer(source); using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(source.Length); - Action action = id => buffer[id.X] = input[id.X]; + var shader = new CopyBetweenReadOnlyAndWriteableBuffers_Shader { IN = input, OUT = buffer }; - Gpu.Default.For(source.Length, action); + Gpu.Default.For(source.Length, shader); float[] result = buffer.GetData(); Assert.IsTrue(result.AsSpan().ContentEquals(source)); } + private struct CopyBetweenWriteableBuffers_Shader : IComputeShader + { + public ReadWriteBuffer IN; + public ReadWriteBuffer OUT; + + public void Execute(ThreadIds ids) + { + OUT[ids.X] = IN[ids.X]; + } + } + [TestMethod] public void CopyBetweenWriteableBuffers() { @@ -149,75 +197,13 @@ namespace ComputeSharp.Tests using ReadWriteBuffer input = Gpu.Default.AllocateReadWriteBuffer(source); using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(source.Length); - Action action = id => buffer[id.X] = input[id.X]; + var shader = new CopyBetweenWriteableBuffers_Shader { IN = input, OUT = buffer }; - Gpu.Default.For(source.Length, action); + Gpu.Default.For(source.Length, shader); float[] result = buffer.GetData(); Assert.IsTrue(result.AsSpan().ContentEquals(source)); } - - [TestMethod] - public void CopyBetweenNestedClosuresEasy() - { - int value1 = 1; - using (ReadWriteBuffer buffer1 = Gpu.Default.AllocateReadWriteBuffer(1)) - { - int value2 = 2; - Action action = id => - { - int sum = value1 + value2; - buffer1[0] = sum; - }; - - Gpu.Default.For(1, action); - - int[] result1 = buffer1.GetData(); - - Assert.IsTrue(result1[0] == value1 + value2); - } - } - - [TestMethod] - public void CopyBetweenNestedClosuresHard() - { - int value1 = 1, value2 = 55, value3 = 77; - using (ReadWriteBuffer buffer1 = Gpu.Default.AllocateReadWriteBuffer(1)) - { - int value4 = 2, value5 = 24, value6 = 99; - using (ReadWriteBuffer buffer2 = Gpu.Default.AllocateReadWriteBuffer(1)) - { - int value7 = 3, value8 = 12, value9 = 333; - using (ReadWriteBuffer buffer3 = Gpu.Default.AllocateReadWriteBuffer(1)) - { - int value10 = 4, value11 = 22; - Action action = id => - { - int sum_gpu = - value1 + value2 + value3 + value4 + - value5 + value6 + value7 + value8 + - value9 + value10 + value11; - buffer1[0] = buffer2[0] = buffer3[0] = sum_gpu; - }; - - Gpu.Default.For(1, action); - - int[] result1 = buffer1.GetData(); - int[] result2 = buffer2.GetData(); - int[] result3 = buffer3.GetData(); - - int sum_cpu = - value1 + value2 + value3 + value4 + - value5 + value6 + value7 + value8 + - value9 + value10 + value11; - - Assert.IsTrue(result1[0] == sum_cpu); - Assert.IsTrue(result2[0] == sum_cpu); - Assert.IsTrue(result3[0] == sum_cpu); - } - } - } - } } } diff --git a/tests/ComputeSharp.Tests/ShaderDispatchTests.cs b/tests/ComputeSharp.Tests/ShaderDispatchTests.cs index 9c4c2f7c..8957192c 100644 --- a/tests/ComputeSharp.Tests/ShaderDispatchTests.cs +++ b/tests/ComputeSharp.Tests/ShaderDispatchTests.cs @@ -9,14 +9,24 @@ namespace ComputeSharp.Tests [TestCategory("ShaderDispatch")] public class ShaderDispatch { + private struct WriteToReadWriteBufferDispatch1D_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[ids.X] = ids.X; + } + } + [TestMethod] public void WriteToReadWriteBufferDispatch1D() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(100); - Action action = id => buffer[id.X] = id.X; + var shader = new WriteToReadWriteBufferDispatch1D_Shader { B = buffer }; - Gpu.Default.For(100, action); + Gpu.Default.For(100, shader); float[] array = buffer.GetData(); float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); @@ -29,9 +39,9 @@ namespace ComputeSharp.Tests { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(100); - Action action = id => buffer[id.X] = id.X; + var shader = new WriteToReadWriteBufferDispatch1D_Shader { B = buffer }; - Gpu.Default.For(100, 1, 1, 64, 1, 1, action); + Gpu.Default.For(100, 1, 1, 64, 1, 1, shader); float[] array = buffer.GetData(); float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); @@ -39,14 +49,24 @@ namespace ComputeSharp.Tests Assert.IsTrue(array.AsSpan().ContentEquals(expected)); } + private struct WriteToReadWriteBufferDispatch2D_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[ids.X + ids.Y * 10] = ids.X + ids.Y * 10; + } + } + [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; + var shader = new WriteToReadWriteBufferDispatch2D_Shader { B = buffer }; - Gpu.Default.For(10, 10, action); + Gpu.Default.For(10, 10, shader); float[] array = buffer.GetData(); float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray(); @@ -54,14 +74,24 @@ namespace ComputeSharp.Tests Assert.IsTrue(array.AsSpan().ContentEquals(expected)); } + private struct WriteToReadWriteBufferDispatch3D_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[ids.X + ids.Y * 10 + ids.Z * 100] = ids.X + ids.Y * 10 + ids.Z * 100; + } + } + [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; + var shader = new WriteToReadWriteBufferDispatch3D_Shader { B = buffer }; - Gpu.Default.For(10, 10, 10, action); + Gpu.Default.For(10, 10, 10, shader); float[] array = buffer.GetData(); float[] expected = Enumerable.Range(0, 1000).Select(i => (float)i).ToArray(); @@ -74,9 +104,9 @@ namespace ComputeSharp.Tests { 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; + var shader = new WriteToReadWriteBufferDispatch3D_Shader { B = buffer }; - Gpu.Default.For(10, 10, 10, 4, 4, 4, action); + Gpu.Default.For(10, 10, 10, 4, 4, 4, shader); float[] array = buffer.GetData(); float[] expected = Enumerable.Range(0, 1000).Select(i => (float)i).ToArray(); diff --git a/tests/ComputeSharp.Tests/StaticFieldsTests.cs b/tests/ComputeSharp.Tests/StaticFieldsTests.cs index 2d73b3ae..e2aeb367 100644 --- a/tests/ComputeSharp.Tests/StaticFieldsTests.cs +++ b/tests/ComputeSharp.Tests/StaticFieldsTests.cs @@ -39,60 +39,97 @@ namespace ComputeSharp.Tests [TestCategory("StaticFields")] public class StaticFieldsTests { + private struct StaticReadonlyScalarFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticFieldsContainer.ReadonlyFloat; + } + } + [TestMethod] public void StaticReadonlyScalarFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticFieldsContainer.ReadonlyFloat; + var shader = new StaticReadonlyScalarFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticFieldsContainer.ReadonlyFloat) < 0.0001f); } + private struct StaticScalarFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticFieldsContainer.StaticFloat; + } + } + [TestMethod] public void StaticScalarFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticFieldsContainer.StaticFloat; + var shader = new StaticScalarFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticFieldsContainer.StaticFloat) < 0.0001f); } + private struct StaticScalarFieldRepeatedAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticFieldsContainer.StaticFloat + StaticFieldsContainer.StaticFloat; + } + } + [TestMethod] public void StaticScalarFieldRepeatedAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticFieldsContainer.StaticFloat + StaticFieldsContainer.StaticFloat; + var shader = new StaticScalarFieldRepeatedAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticFieldsContainer.StaticFloat * 2) < 0.0001f); } + private struct StaticReadonlyVectorFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticFieldsContainer.ReadonlyVector2.X; + else B[1] = StaticFieldsContainer.ReadonlyVector2.Y; + } + } + [TestMethod] public void StaticReadonlyVectorFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticFieldsContainer.ReadonlyVector2.X; - else buffer[1] = StaticFieldsContainer.ReadonlyVector2.Y; - }; + var shader = new StaticReadonlyVectorFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); @@ -100,18 +137,25 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[1] - StaticFieldsContainer.ReadonlyVector2.Y) < 0.0001f); } + private struct StaticVectorFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticFieldsContainer.StaticVector2.X; + else B[1] = StaticFieldsContainer.StaticVector2.Y; + } + } + [TestMethod] public void StaticVectorFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticFieldsContainer.StaticVector2.X; - else buffer[1] = StaticFieldsContainer.StaticVector2.Y; - }; + var shader = new StaticVectorFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); @@ -119,18 +163,25 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[1] - StaticFieldsContainer.StaticVector2.Y) < 0.0001f); } + private struct StaticReadOnlyBufferFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticFieldsContainer.StaticBuffer[0]; + else B[1] = StaticFieldsContainer.StaticBuffer[1]; + } + } + [TestMethod] public void StaticReadOnlyBufferFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticFieldsContainer.StaticBuffer[0]; - else buffer[1] = StaticFieldsContainer.StaticBuffer[1]; - }; + var shader = new StaticReadOnlyBufferFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); float[] expected = StaticFieldsContainer.StaticBuffer.GetData(); diff --git a/tests/ComputeSharp.Tests/StaticFunctionsTests.cs b/tests/ComputeSharp.Tests/StaticFunctionsTests.cs index ce7ccb7c..93b979a5 100644 --- a/tests/ComputeSharp.Tests/StaticFunctionsTests.cs +++ b/tests/ComputeSharp.Tests/StaticFunctionsTests.cs @@ -7,14 +7,77 @@ namespace ComputeSharp.Tests [TestCategory("StaticFunctions")] public class StaticFunctionsTests { + private struct ExternalStaticFunctionDirect_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMethodsContainer.Square(4); + } + } + + [TestMethod] + public void ExternalStaticFunctionDirect() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + var shader = new ExternalStaticFunctionDirect_Shader { B = buffer }; + + Gpu.Default.For(1, shader); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - 16) < 0.0001f); + } + + private struct ExternalStaticFunctionWithAttributesDirect_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMethodsContainer.SquareWithAttributes(4); + } + } + + [TestMethod] + public void ExternalStaticFunctionWithAttributesDirect() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + var shader = new ExternalStaticFunctionWithAttributesDirect_Shader { B = buffer }; + + Gpu.Default.For(1, shader); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - 16) < 0.0001f); + } + + private struct FloatToFloatFunc_Shader : IComputeShader + { + public Func F; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = F(3); + } + } + [TestMethod] public void FloatToFloatFunc() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Func square = StaticMethodsContainer.Square; + var shader = new FloatToFloatFunc_Shader + { + F = StaticMethodsContainer.Square, + B = buffer + }; - Gpu.Default.For(1, id => buffer[0] = square(3)); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -28,7 +91,13 @@ namespace ComputeSharp.Tests Func square = StaticMethodsContainer.InternalSquare; - Gpu.Default.For(1, id => buffer[0] = square(3)); + var shader = new FloatToFloatFunc_Shader + { + F = square, + B = buffer + }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -40,23 +109,39 @@ namespace ComputeSharp.Tests { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Func func = StaticMethodsContainer.Square; + var shader = new FloatToFloatFunc_Shader + { + F = StaticMethodsContainer.Square, + B = buffer + }; - Gpu.Default.For(1, id => buffer[0] = func(3)); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); - func = StaticMethodsContainer.Negate; + shader.F = StaticMethodsContainer.Negate; - Gpu.Default.For(1, id => buffer[0] = func(3)); + Gpu.Default.For(1, shader); result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] + 3) < 0.0001f); } + private struct ChangingFuncsFromExternalMethod_Shader : IComputeShader + { + public Func F; + public ReadWriteBuffer B; + public float I; + + public void Execute(ThreadIds ids) + { + B[0] = F(I); + } + } + [TestMethod] public void ChangingFuncsFromExternalMethod() { @@ -69,7 +154,14 @@ namespace ComputeSharp.Tests { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => buffer[0] = func(input)); + var shader = new ChangingFuncsFromExternalMethod_Shader + { + F = func, + B = buffer, + I = input + }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -78,6 +170,17 @@ namespace ComputeSharp.Tests public delegate float Squarer(float x); + private struct CustomStaticDelegate_Shader : IComputeShader + { + public Squarer F; + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = F(3); + } + } + [TestMethod] public void CustomStaticDelegate() { @@ -85,7 +188,13 @@ namespace ComputeSharp.Tests Squarer square = StaticMethodsContainer.Square; - Gpu.Default.For(1, id => buffer[0] = square(3)); + var shader = new CustomStaticDelegate_Shader + { + F = square, + B = buffer + }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -99,7 +208,13 @@ namespace ComputeSharp.Tests Func f = x => x * x; - Gpu.Default.For(1, id => buffer[0] = f(3)); + var shader = new FloatToFloatFunc_Shader + { + F = f, + B = buffer + }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -115,7 +230,33 @@ namespace ComputeSharp.Tests Func f = Func; - Gpu.Default.For(1, id => buffer[0] = f(3)); + var shader = new FloatToFloatFunc_Shader + { + F = f, + B = buffer + }; + + Gpu.Default.For(1, shader); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); + } + + [TestMethod] + public void StaticLocalFunction() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + static float f(float x) => x * x; + + var shader = new FloatToFloatFunc_Shader + { + F = f, + B = buffer + }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -129,7 +270,13 @@ namespace ComputeSharp.Tests float f(float x) => x * x; - Gpu.Default.For(1, id => buffer[0] = f(3)); + var shader = new FloatToFloatFunc_Shader + { + F = f, + B = buffer + }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -138,12 +285,24 @@ namespace ComputeSharp.Tests public static float Square(float x) => x * x; + private struct StaticMethodInSameClass_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = Square(3); + } + } + [TestMethod] public void StaticMethodInSameClass() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => buffer[0] = Square(3)); + var shader = new StaticMethodInSameClass_Shader { B = buffer }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); @@ -152,46 +311,77 @@ namespace ComputeSharp.Tests public static Func SquareFunc { get; } = x => x * x; + private struct StaticFunctionInSameClass_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = SquareFunc(3); + } + } + [TestMethod] public void StaticFunctionInSameClass() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => buffer[0] = SquareFunc(3)); + var shader = new StaticFunctionInSameClass_Shader { B = buffer }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); } + private struct StaticFunctionInExternalClass_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticPropertiesContainer.SquareFunc(3); + } + } + [TestMethod] public void StaticFunctionInExternalClass() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => buffer[0] = StaticPropertiesContainer.SquareFunc(3)); + var shader = new StaticFunctionInExternalClass_Shader { B = buffer }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); } + private static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x)); + + private struct ReadmeSample_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + int offset = ids.X + ids.Y * 1; + float pow = Hlsl.Pow(B[offset], 2); // 9 + B[offset] = Sigmoid(pow); // 0.9998766 + } + } + [TestMethod] public void ReadmeSample() { float[] buffer = { 3 }; using ReadWriteBuffer xBuffer = Gpu.Default.AllocateReadWriteBuffer(buffer); - static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x)); + var shader = new ReadmeSample_Shader { B = xBuffer }; - void Kernel(ThreadIds id) - { - int offset = id.X + id.Y * 1; - float pow = Hlsl.Pow(xBuffer[offset], 2); // 9 - xBuffer[offset] = Sigmoid(pow); // 0.9998766 - } - - Gpu.Default.For(1, Kernel); + Gpu.Default.For(1, shader); float[] result = xBuffer.GetData(); diff --git a/tests/ComputeSharp.Tests/StaticMethodsTests.cs b/tests/ComputeSharp.Tests/StaticMethodsTests.cs index 3efd02a7..ee321748 100644 --- a/tests/ComputeSharp.Tests/StaticMethodsTests.cs +++ b/tests/ComputeSharp.Tests/StaticMethodsTests.cs @@ -1,5 +1,7 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComputeSharp.Tests @@ -12,6 +14,11 @@ namespace ComputeSharp.Tests [Pure] public static float Square(float x) => x * x; + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [return: NotNull] + public static float SquareWithAttributes(float x) => x * x; + [Pure] public static float Negate(float x) => -x; @@ -33,36 +40,72 @@ namespace ComputeSharp.Tests [TestCategory("StaticMethods")] public class StaticMethodsTests { + private struct FloatToFloatFunc_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMethodsContainer.Square(3); + } + } + [TestMethod] public void FloatToFloatFunc() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => buffer[0] = StaticMethodsContainer.Square(3)); + var shader = new FloatToFloatFunc_Shader { B = buffer }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); } + private struct InternalFloatToFloatFunc_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMethodsContainer.InternalSquare(3); + } + } + [TestMethod] public void InternalFloatToFloatFunc() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => buffer[0] = StaticMethodsContainer.InternalSquare(3)); + var shader = new InternalFloatToFloatFunc_Shader { B = buffer }; + + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); } + private struct FloatToFloat4Func_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMethodsContainer.Range(3); + } + } + [TestMethod] public void FloatToFloat4Func() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => buffer[0] = StaticMethodsContainer.Range(3)); + var shader = new FloatToFloat4Func_Shader { B = buffer }; + + Gpu.Default.For(1, shader); Float4[] result = buffer.GetData(); @@ -72,37 +115,73 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[0].W - 6) < 0.0001f); } + private struct Float4ToIntFunc_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticMethodsContainer.Sum(new Float4(1, 2, 3, 14)); + } + } + [TestMethod] public void Float4ToIntFunc() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => buffer[0] = StaticMethodsContainer.Sum(new Float4(1, 2, 3, 14))); + var shader = new Float4ToIntFunc_Shader { B = buffer }; + + Gpu.Default.For(1, shader); int[] result = buffer.GetData(); Assert.IsTrue(result[0] == 20); } + private struct IntToOutIntFunc_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + StaticMethodsContainer.Assign(7, out B[0]); + } + } + [TestMethod] public void IntToOutIntFunc() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Gpu.Default.For(1, id => StaticMethodsContainer.Assign(7, out buffer[0])); + var shader = new IntToOutIntFunc_Shader { B = buffer }; + + Gpu.Default.For(1, shader); int[] result = buffer.GetData(); Assert.IsTrue(result[0] == 7); } + private struct IntToRefIntFunc_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + StaticMethodsContainer.ReadAndSquare(ref B[0]); + } + } + [TestMethod] public void IntToRefIntFunc() { int[] data = { 3 }; using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(data); - Gpu.Default.For(1, id => StaticMethodsContainer.ReadAndSquare(ref buffer[0])); + var shader = new IntToRefIntFunc_Shader { B = buffer }; + + Gpu.Default.For(1, shader); buffer.GetData(data); diff --git a/tests/ComputeSharp.Tests/StaticPropertiesTests.cs b/tests/ComputeSharp.Tests/StaticPropertiesTests.cs index bf5ceb57..e785b42b 100644 --- a/tests/ComputeSharp.Tests/StaticPropertiesTests.cs +++ b/tests/ComputeSharp.Tests/StaticPropertiesTests.cs @@ -44,60 +44,97 @@ namespace ComputeSharp.Tests [TestCategory("StaticProperties")] public class StaticPropertiesTests { + private struct StaticReadonlyScalarPropertyAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticPropertiesContainer.ReadonlyFloat; + } + } + [TestMethod] public void StaticReadonlyScalarPropertyAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticPropertiesContainer.ReadonlyFloat; + var shader = new StaticReadonlyScalarPropertyAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticPropertiesContainer.ReadonlyFloat) < 0.0001f); } + private struct StaticScalarPropertyAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticPropertiesContainer.StaticFloat; + } + } + [TestMethod] public void StaticScalarPropertyAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticPropertiesContainer.StaticFloat; + var shader = new StaticScalarPropertyAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticPropertiesContainer.StaticFloat) < 0.0001f); } + private struct StaticScalarPropertyRepeatedAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = StaticPropertiesContainer.StaticFloat + StaticPropertiesContainer.StaticFloat; + } + } + [TestMethod] public void StaticScalarPropertyRepeatedAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = StaticPropertiesContainer.StaticFloat + StaticPropertiesContainer.StaticFloat; + var shader = new StaticScalarPropertyRepeatedAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); float[] result = buffer.GetData(); Assert.IsTrue(MathF.Abs(result[0] - StaticPropertiesContainer.StaticFloat * 2) < 0.0001f); } + private struct StaticReadonlyVectorPropertyAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticPropertiesContainer.ReadonlyVector2.X; + else B[1] = StaticPropertiesContainer.ReadonlyVector2.Y; + } + } + [TestMethod] public void StaticReadonlyVectorPropertyAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticPropertiesContainer.ReadonlyVector2.X; - else buffer[1] = StaticPropertiesContainer.ReadonlyVector2.Y; - }; + var shader = new StaticReadonlyVectorPropertyAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); @@ -105,18 +142,25 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[1] - StaticPropertiesContainer.ReadonlyVector2.Y) < 0.0001f); } + private struct StaticVectorPropertyAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticPropertiesContainer.StaticVector2.X; + else B[1] = StaticPropertiesContainer.StaticVector2.Y; + } + } + [TestMethod] public void StaticVectorPropertyAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticPropertiesContainer.StaticVector2.X; - else buffer[1] = StaticPropertiesContainer.StaticVector2.Y; - }; + var shader = new StaticVectorPropertyAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); @@ -124,18 +168,25 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[1] - StaticPropertiesContainer.StaticVector2.Y) < 0.0001f); } + private struct StaticReadOnlyBufferPropertyAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + if (ids.X == 0) B[0] = StaticPropertiesContainer.StaticBuffer[0]; + else B[1] = StaticPropertiesContainer.StaticBuffer[1]; + } + } + [TestMethod] public void StaticReadOnlyBufferPropertyAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(2); - Action action = id => - { - if (id.X == 0) buffer[0] = StaticPropertiesContainer.StaticBuffer[0]; - else buffer[1] = StaticPropertiesContainer.StaticBuffer[1]; - }; + var shader = new StaticReadOnlyBufferPropertyAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(2, action); + Gpu.Default.For(2, shader); float[] result = buffer.GetData(); float[] expected = StaticPropertiesContainer.StaticBuffer.GetData(); @@ -146,14 +197,24 @@ namespace ComputeSharp.Tests public static int SomeNumber = 7; + private struct StaticLocalScalarFieldAssignToBuffer_Shader : IComputeShader + { + public ReadWriteBuffer B; + + public void Execute(ThreadIds ids) + { + B[0] = SomeNumber; + } + } + [TestMethod] public void StaticLocalScalarFieldAssignToBuffer() { using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); - Action action = id => buffer[0] = SomeNumber; + var shader = new StaticLocalScalarFieldAssignToBuffer_Shader { B = buffer }; - Gpu.Default.For(1, action); + Gpu.Default.For(1, shader); int[] result = buffer.GetData();