diff --git a/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs b/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs new file mode 100644 index 00000000..395624e0 --- /dev/null +++ b/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs @@ -0,0 +1,91 @@ +using System; +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Configs; + +namespace ComputeSharp.Benchmark.Blas; + +/// +/// A that benchmarks the shader dispatch times. +/// +[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)] +public partial class DispatchingBenchmark : IDisposable +{ + /// + /// The test buffer. + /// + private ReadWriteBuffer? Buffer; + + /// + /// Initial setup for a benchmarking session. + /// + [GlobalSetup] + public void Setup() + { + Buffer = GraphicsDevice.Default.AllocateReadWriteBuffer(128); + } + + /// + [GlobalCleanup] + public void Dispose() + { + Buffer!.Dispose(); + } + + /// + /// Invokes a single shader, manually. + /// + [Benchmark(Baseline = true)] + [BenchmarkCategory("SINGLE")] + public void Compute_Single() + { + GraphicsDevice.Default.For(64, new TestShader(Buffer!)); + } + + /// + /// Invokes a single shader through a compute context. + /// + [Benchmark] + [BenchmarkCategory("SINGLE")] + public void Compute_Single_WithContext() + { + using var context = GraphicsDevice.Default.CreateComputeContext(); + + context.For(64, new TestShader(Buffer!)); + } + + /// + /// Invokes two empty compute shaders one by one. + /// + [Benchmark(Baseline = true)] + [BenchmarkCategory("MULTIPLE")] + public void Compute_Multiple() + { + GraphicsDevice.Default.For(64, new TestShader(Buffer!)); + GraphicsDevice.Default.For(64, new TestShader(Buffer!)); + } + + /// + /// Invokes two empty compute shaders in a batch. + /// + [Benchmark] + [BenchmarkCategory("MULTIPLE")] + public void Compute_Multiple_WithContext() + { + using var context = GraphicsDevice.Default.CreateComputeContext(); + + context.For(64, new TestShader(Buffer!)); + context.Barrier(Buffer!); + context.For(64, new TestShader(Buffer!)); + } + + [AutoConstructor] + internal readonly partial struct TestShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + + /// + public void Execute() + { + } + } +} diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index 79eb4b45..25c159d1 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -286,12 +286,17 @@ public sealed partial class HlslBokehBlurProcessor kernel.CopyFrom(Kernels[j]); - GraphicsDevice.For( + using var context = GraphicsDevice.CreateComputeContext(); + + context.For( source.Width, source.Height, new(texture, reals, imaginaries, kernel)); - GraphicsDevice.For( + context.Barrier(reals); + context.Barrier(imaginaries); + + context.For( source.Width, source.Height, new(parameters.Z, parameters.W, reals, imaginaries, temporary, kernel)); diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index 5fb59656..c993f9d2 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -105,8 +105,12 @@ public sealed partial class HlslGaussianBlurProcessor using ReadWriteTexture2D firstPassTexture = GraphicsDevice.AllocateReadWriteTexture2D(source.Width, source.Height); using ReadOnlyBuffer kernelBuffer = GraphicsDevice.AllocateReadOnlyBuffer(Kernel); - GraphicsDevice.For(source.Width, source.Height, new(sourceTexture, firstPassTexture, kernelBuffer)); - GraphicsDevice.For(source.Width, source.Height, new(firstPassTexture, sourceTexture, kernelBuffer)); + using (var context = GraphicsDevice.CreateComputeContext()) + { + context.For(source.Width, source.Height, new(sourceTexture, firstPassTexture, kernelBuffer)); + context.Barrier(firstPassTexture); + context.For(source.Width, source.Height, new(firstPassTexture, sourceTexture, kernelBuffer)); + } sourceTexture.CopyTo(span); } diff --git a/src/ComputeSharp/Graphics/Commands/CommandList.cs b/src/ComputeSharp/Graphics/Commands/CommandList.cs index b6f330c9..e31c9241 100644 --- a/src/ComputeSharp/Graphics/Commands/CommandList.cs +++ b/src/ComputeSharp/Graphics/Commands/CommandList.cs @@ -78,6 +78,16 @@ internal unsafe ref struct CommandList device.SetDescriptorHeapForCommandList(this.d3D12GraphicsCommandList); } + /// + /// Gets whether or not the curreent instance is allocated. + /// + public readonly bool IsAllocated => this.device is not null; + + /// + /// Gets the instance associated with the current command list. + /// + public GraphicsDevice GraphicsDevice => this.device; + /// /// Gets the command list type being used by the current instance. /// diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs index 28475326..8679210c 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs @@ -9,7 +9,7 @@ namespace ComputeSharp; public static partial class GraphicsDeviceExtensions { /// - /// Compiles and runs the input shader on a target instance, with the specified parameters. + /// 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. @@ -22,7 +22,7 @@ public static partial class GraphicsDeviceExtensions } /// - /// Compiles and runs the input shader on a target instance, with the specified parameters. + /// 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. @@ -36,7 +36,7 @@ public static partial class GraphicsDeviceExtensions } /// - /// Compiles and runs the input shader on a target instance, with the specified parameters. + /// 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. @@ -51,7 +51,7 @@ public static partial class GraphicsDeviceExtensions } /// - /// Compiles and runs the input shader on a target instance, with the specified parameters. + /// 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. @@ -69,7 +69,7 @@ public static partial class GraphicsDeviceExtensions } /// - /// Compiles and runs the input shader on a target instance, with the specified parameters. + /// Runs the input shader on a target instance, with the specified parameters. /// /// The type of pixel shader to run. /// The type of pixels being processed by the shader. @@ -83,7 +83,7 @@ public static partial class GraphicsDeviceExtensions } /// - /// Compiles and runs the input shader on a target instance, with the specified parameters. + /// Runs the input shader on a target instance, with the specified parameters. /// /// The type of pixel shader to run. /// The type of pixels being processed by the shader. @@ -96,4 +96,26 @@ public static partial class GraphicsDeviceExtensions { ShaderRunner.Run(device, texture, ref Unsafe.AsRef(in shader)); } + + /// + /// Creates a new instance to batch compute operations together. + /// + /// The to use to run shaders. + /// A new instance to batch compute operations together. + /// + /// The returned instance should be used in a block or declaration: + /// + /// using (var context = device.CreateComputeContext()) + /// { + /// // Dispatch shaders here... + /// } + /// + /// All dispatched shaders will be executed as soon as the context goes out of scope. + /// + public static ComputeContext CreateComputeContext(this GraphicsDevice device) + { + device.ThrowIfDisposed(); + + return new(device); + } } diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12GraphicsCommandListExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12GraphicsCommandListExtensions.cs index 9e52abec..987fbf90 100644 --- a/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12GraphicsCommandListExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12GraphicsCommandListExtensions.cs @@ -1,5 +1,7 @@ using System; using TerraFX.Interop.DirectX; +using static TerraFX.Interop.DirectX.D3D12_RESOURCE_BARRIER_FLAGS; +using static TerraFX.Interop.DirectX.D3D12_RESOURCE_BARRIER_TYPE; namespace ComputeSharp.Graphics.Extensions; @@ -195,7 +197,7 @@ internal static unsafe class ID3D12GraphicsCommandListExtensions /// The to change state for. /// The starting value for the transition. /// The destnation value for the transition. - public static void ResourceBarrier( + public static void TransitionBarrier( this ref ID3D12GraphicsCommandList d3D12GraphicsCommandList, ID3D12Resource* d3D12Resource, D3D12_RESOURCE_STATES d3D12ResourceStatesBefore, @@ -206,6 +208,18 @@ internal static unsafe class ID3D12GraphicsCommandListExtensions d3D12GraphicsCommandList.ResourceBarrier(1, &d3D12ResourceBarrier); } + /// + /// Inserts a UAV resource barrier for a specific resource. + /// + /// The instance in use. + /// The to insert the barrier for. + public static void UAVBarrier(this ref ID3D12GraphicsCommandList d3D12GraphicsCommandList, ID3D12Resource* d3D12Resource) + { + D3D12_RESOURCE_BARRIER d3D12ResourceBarrier = D3D12_RESOURCE_BARRIER.InitUAV(d3D12Resource); + + d3D12GraphicsCommandList.ResourceBarrier(1, &d3D12ResourceBarrier); + } + /// /// Binds an input constant buffer to the first root parameter. /// diff --git a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs index fb40d83b..48df0aa0 100644 --- a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs @@ -17,7 +17,7 @@ public static class GraphicsResourceHelper /// /// An interface for non-generic graphics resource types. /// - internal interface IGraphicsResource + internal unsafe interface IGraphicsResource { /// /// Validates the given resource for usage with a specified device, and retrieves its GPU descriptor handle. @@ -25,6 +25,13 @@ public static class GraphicsResourceHelper /// The target instance in use. /// The GPU descriptor handle for the resource. D3D12_GPU_DESCRIPTOR_HANDLE ValidateAndGetGpuDescriptorHandle(GraphicsDevice device); + + /// + /// Validates the given resource for usage with a specified device, and retrieves the underlying object. + /// + /// The target instance in use. + /// The the underlying object. + ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device); } /// diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs index f4ebdea0..b92907c1 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs @@ -306,4 +306,13 @@ public abstract class StructuredBuffer : Buffer copyCommandList.ExecuteAndWaitForCompletion(); } } + + /// + internal unsafe ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) + { + ThrowIfDisposed(); + ThrowIfDeviceMismatch(device); + + return D3D12Resource; + } } diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs index 2619cc2b..edd0a980 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs @@ -207,7 +207,7 @@ public unsafe abstract class Texture2D : NativeObject, GraphicsResourceHelper { if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); } copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( @@ -226,7 +226,7 @@ public unsafe abstract class Texture2D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); } copyCommandList.ExecuteAndWaitForCompletion(); @@ -287,8 +287,8 @@ public unsafe abstract class Texture2D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(destination.D3D12Resource, destination.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, destination.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); } copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( @@ -306,8 +306,8 @@ public unsafe abstract class Texture2D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(destination.D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, destination.d3D12ResourceState); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, destination.d3D12ResourceState); } copyCommandList.ExecuteAndWaitForCompletion(); @@ -349,7 +349,7 @@ public unsafe abstract class Texture2D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); } fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintDestination = &destination.D3D12PlacedSubresourceFootprint) @@ -371,7 +371,7 @@ public unsafe abstract class Texture2D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); } copyCommandList.ExecuteAndWaitForCompletion(); @@ -439,7 +439,7 @@ public unsafe abstract class Texture2D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); } copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( @@ -458,7 +458,7 @@ public unsafe abstract class Texture2D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); } copyCommandList.ExecuteAndWaitForCompletion(); @@ -500,7 +500,7 @@ public unsafe abstract class Texture2D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); } fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintSource = &source.D3D12PlacedSubresourceFootprint) @@ -522,7 +522,7 @@ public unsafe abstract class Texture2D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); } copyCommandList.ExecuteAndWaitForCompletion(); @@ -555,6 +555,15 @@ public unsafe abstract class Texture2D : NativeObject, GraphicsResourceHelper } } + /// + internal ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) + { + ThrowIfDisposed(); + ThrowIfDeviceMismatch(device); + + return D3D12Resource; + } + /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { @@ -563,4 +572,10 @@ public unsafe abstract class Texture2D : NativeObject, GraphicsResourceHelper return D3D12GpuDescriptorHandle; } + + /// + ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) + { + return ValidateAndGetID3D12Resource(device); + } } diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs index d49a14b3..7c93eacb 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs @@ -223,7 +223,7 @@ public unsafe abstract class Texture3D : NativeObject, GraphicsResourceHelper { if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); } copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( @@ -242,7 +242,7 @@ public unsafe abstract class Texture3D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); } copyCommandList.ExecuteAndWaitForCompletion(); @@ -314,8 +314,8 @@ public unsafe abstract class Texture3D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(destination.D3D12Resource, destination.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, destination.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); } copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( @@ -333,8 +333,8 @@ public unsafe abstract class Texture3D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(destination.D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, destination.d3D12ResourceState); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, destination.d3D12ResourceState); } copyCommandList.ExecuteAndWaitForCompletion(); @@ -385,7 +385,7 @@ public unsafe abstract class Texture3D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); } fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintDestination = &destination.D3D12PlacedSubresourceFootprint) @@ -407,7 +407,7 @@ public unsafe abstract class Texture3D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); } copyCommandList.ExecuteAndWaitForCompletion(); @@ -483,7 +483,7 @@ public unsafe abstract class Texture3D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); } copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( @@ -502,7 +502,7 @@ public unsafe abstract class Texture3D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); } copyCommandList.ExecuteAndWaitForCompletion(); @@ -553,7 +553,7 @@ public unsafe abstract class Texture3D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); } fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintSource = &source.D3D12PlacedSubresourceFootprint) @@ -575,7 +575,7 @@ public unsafe abstract class Texture3D : NativeObject, GraphicsResourceHelper if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) { - copyCommandList.D3D12GraphicsCommandList->ResourceBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); } copyCommandList.ExecuteAndWaitForCompletion(); @@ -608,6 +608,15 @@ public unsafe abstract class Texture3D : NativeObject, GraphicsResourceHelper } } + /// + internal ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device) + { + ThrowIfDisposed(); + ThrowIfDeviceMismatch(device); + + return D3D12Resource; + } + /// D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) { @@ -616,4 +625,10 @@ public unsafe abstract class Texture3D : NativeObject, GraphicsResourceHelper return D3D12GpuDescriptorHandle; } + + /// + ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) + { + return ValidateAndGetID3D12Resource(device); + } } diff --git a/src/ComputeSharp/Shaders/ComputeContext.cs b/src/ComputeSharp/Shaders/ComputeContext.cs new file mode 100644 index 00000000..17b0dcd4 --- /dev/null +++ b/src/ComputeSharp/Shaders/ComputeContext.cs @@ -0,0 +1,278 @@ +using System; +using System.Runtime.CompilerServices; +using ComputeSharp.__Internals; +using ComputeSharp.Graphics.Commands; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.Shaders; +using ComputeSharp.Shaders.Dispatching; +using Microsoft.Toolkit.Diagnostics; +using TerraFX.Interop.DirectX; + +#pragma warning disable CS0618 + +namespace ComputeSharp; + +/// +/// A context to batch compute operations in a single invocation, minimizing GPU overhead. +/// +public ref struct ComputeContext +{ + /// + /// The instance owning the current context. + /// + private readonly GraphicsDevice device; + + /// + /// The current instance used to dispatch shaders. + /// + private CommandList commandList; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance owning the current context. + internal ComputeContext(GraphicsDevice device) + { + this.device = device; + this.commandList = default; + } + + /// + /// Gets the associated with the current instance. + /// + public GraphicsDevice GraphicsDevice => this.device; + + /// + /// Inserts a resource barrier for a specific resource. + /// + /// The to insert the barrier for. + internal readonly unsafe void Barrier(ID3D12Resource* d3D12Resource) + { + ThrowInvalidOperationExceptionIfDeviceIsNull(); + + ref CommandList commandList = ref GetCommandList(in this); + + commandList.D3D12GraphicsCommandList->UAVBarrier(d3D12Resource); + } + + /// + /// Runs the input shader with the specified parameters. + /// + /// 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 instance representing the compute shader to run. + internal readonly unsafe void Run(int x, int y, int z, ref T shader) + where T : struct, IComputeShader + { + ThrowInvalidOperationExceptionIfDeviceIsNull(); + + bool xIs1 = x == 1; + bool yIs1 = y == 1; + bool zIs1 = z == 1; + int mask = *(byte*)&xIs1 << 2 | *(byte*)&yIs1 << 1 | *(byte*)&zIs1; + int threadsX; + int threadsY; + int threadsZ; + + switch (mask - 1) + { + case 0: // (_, _, 1) + threadsX = threadsY = 8; + threadsZ = 1; + break; + case 1: // (_, 1, _) + threadsX = threadsZ = 8; + threadsY = 1; + break; + case 2: // (_, 1, 1) + threadsX = (int)this.device.WavefrontSize; + threadsY = threadsZ = 1; + break; + case 3: // (1, _, _) + threadsX = 1; + threadsY = threadsZ = 8; + break; + case 4: // (1, _, 1) + threadsX = threadsZ = 1; + threadsY = (int)this.device.WavefrontSize; + break; + case 5: // (1, 1, _) + threadsX = threadsY = 1; + threadsZ = (int)this.device.WavefrontSize; + break; + default: // (_, _, _) + threadsX = threadsY = threadsZ = 4; + break; + } + + Run(x, y, z, threadsX, threadsY, threadsZ, ref shader); + } + + /// + /// Runs the input shader with the specified parameters. + /// + /// The type of 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. + /// 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 instance representing the compute shader to run. + internal readonly unsafe void Run( + int x, + int y, + int z, + int threadsX, + int threadsY, + int threadsZ, + ref T shader) + where T : struct, IComputeShader + { + ThrowInvalidOperationExceptionIfDeviceIsNull(); + + Guard.IsGreaterThan(x, 0, nameof(x)); + Guard.IsGreaterThan(y, 0, nameof(y)); + Guard.IsGreaterThan(z, 0, nameof(z)); + Guard.IsBetweenOrEqualTo(threadsX, 1, 1024, nameof(threadsX)); + Guard.IsBetweenOrEqualTo(threadsY, 1, 1024, nameof(threadsY)); + Guard.IsBetweenOrEqualTo(threadsZ, 1, 64, nameof(threadsZ)); + Guard.IsLessThanOrEqualTo(threadsX * threadsY * threadsZ, 1024, "threadsXYZ"); + + int groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1); + int groupsY = Math.DivRem(y, threadsY, out int modY) + (modY == 0 ? 0 : 1); + int groupsZ = Math.DivRem(z, threadsZ, out int modZ) + (modZ == 0 ? 0 : 1); + + Guard.IsBetweenOrEqualTo(groupsX, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); + Guard.IsBetweenOrEqualTo(groupsY, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); + Guard.IsBetweenOrEqualTo(groupsZ, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); + + PipelineData pipelineData = ShaderRunner.GetPipelineData(this.device, threadsX, threadsY, threadsZ, ref shader); + + ref CommandList commandList = ref GetCommandList(in this, pipelineData.D3D12PipelineState); + + commandList.D3D12GraphicsCommandList->SetComputeRootSignature(pipelineData.D3D12RootSignature); + + ComputeShaderDispatchDataLoader dataLoader = new(commandList.D3D12GraphicsCommandList); + + shader.LoadDispatchData(ref dataLoader, this.device, x, y, z); + + commandList.D3D12GraphicsCommandList->Dispatch((uint)groupsX, (uint)groupsY, (uint)groupsZ); + } + + /// + /// Runs the input shader with the specified parameters. + /// + /// The type of pixel shader to run. + /// The type of pixel to work on. + /// The target texture to invoke the pixel shader upon. + /// The input instance representing the pixel shader to run. + internal readonly unsafe void Run(IReadWriteTexture2D texture, ref T shader) + where T : struct, IPixelShader + where TPixel : unmanaged + { + ThrowInvalidOperationExceptionIfDeviceIsNull(); + + int x = texture.Width; + int y = texture.Height; + const int threadsX = 8; + const int threadsY = 8; + const int threadsZ = 1; + int groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1); + int groupsY = Math.DivRem(y, threadsY, out int modY) + (modY == 0 ? 0 : 1); + + Guard.IsBetweenOrEqualTo(groupsX, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); + Guard.IsBetweenOrEqualTo(groupsY, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); + + PipelineData pipelineData = ShaderRunner.GetPipelineData(this.device, threadsX, threadsY, threadsZ, ref shader); + + ref CommandList commandList = ref GetCommandList(in this, pipelineData.D3D12PipelineState); + + commandList.D3D12GraphicsCommandList->SetComputeRootSignature(pipelineData.D3D12RootSignature); + + PixelShaderDispatchDataLoader dataLoader = new(commandList.D3D12GraphicsCommandList); + + shader.LoadDispatchData(ref dataLoader, this.device, x, y, 1); + + // Load the implicit output texture + commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable( + 1, + ((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetGpuDescriptorHandle(this.device)); + + commandList.D3D12GraphicsCommandList->Dispatch((uint)groupsX, (uint)groupsY, 1); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + ThrowInvalidOperationExceptionIfDeviceIsNull(); + + if (!this.commandList.IsAllocated) + { + return; + } + + this.commandList.ExecuteAndWaitForCompletion(); + } + + /// + /// Gets the current instance. + /// + /// The current instance. + /// A reference to the instance to use. + /// Thrown if the has not been initialized yet. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static unsafe ref CommandList GetCommandList(in ComputeContext @this) + { + // This method has to take the context by readonly reference to allow callers to be marked as readonly. + // This is needed to skip the hidden copies done by Roslyn, which would break the dispatching, as the + // original context would not see the changes done by the following queued dispatches. This delegate + // cast is necessary to work around the fact that ref structs cannot currently be used as type arguments. + ref ComputeContext context = ref ((delegate*)(delegate*)&Unsafe.AsRef)(in @this); + + if (!context.commandList.IsAllocated) + { + ThrowHelper.ThrowInvalidOperationException("The current compute context has not yet been initialized."); + } + + return ref context.commandList; + } + + /// + /// Gets the current instance, and initializes it as needed. + /// + /// The current instance. + /// The input to load. + /// A reference to the instance to use. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static unsafe ref CommandList GetCommandList(in ComputeContext @this, ID3D12PipelineState* pipelineState) + { + ref ComputeContext context = ref ((delegate*)(delegate*)&Unsafe.AsRef)(in @this); + + if (context.commandList.IsAllocated) + { + context.commandList.D3D12GraphicsCommandList->SetPipelineState(pipelineState); + } + else + { + context.commandList = new CommandList(context.device, pipelineState); + } + + return ref context.commandList; + } + + /// + /// Throws an if is . + /// + /// Thrown if is . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private readonly void ThrowInvalidOperationExceptionIfDeviceIsNull() + { + if (this.device is null) + { + ThrowHelper.ThrowInvalidOperationException("The current compute context has not been initialized correctly."); + } + } +} diff --git a/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs b/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs new file mode 100644 index 00000000..3fd3e302 --- /dev/null +++ b/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs @@ -0,0 +1,189 @@ +using System.Runtime.CompilerServices; +using ComputeSharp.__Internals; + +#pragma warning disable CS0618 + +namespace ComputeSharp; + +/// +/// A that contains extension methods for the type, used to run compute shaders. +/// +public static partial class ComputeContextExtensions +{ + /// + /// Inserts a resource barrier for a specific resource. + /// + /// The type of items stored on the buffer. + /// The to use to insert the resource barrier. + /// The input instance to insert the barrier for. + public static unsafe void Barrier(this in ComputeContext context, ReadWriteBuffer buffer) + where T : unmanaged + { + context.Barrier(buffer.ValidateAndGetID3D12Resource(context.GraphicsDevice)); + } + + /// + /// Inserts a resource barrier for a specific resource. + /// + /// The type of items stored on the texture. + /// The to use to insert the resource barrier. + /// The input instance to insert the barrier for. + public static unsafe void Barrier(this in ComputeContext context, ReadWriteTexture2D texture) + where T : unmanaged + { + context.Barrier(texture.ValidateAndGetID3D12Resource(context.GraphicsDevice)); + } + + /// + /// Inserts a resource barrier for a specific resource. + /// + /// The type of items stored on the texture. + /// The to use to insert the resource barrier. + /// The input instance to insert the barrier for. + public static unsafe void Barrier(this in ComputeContext context, ReadWriteTexture3D texture) + where T : unmanaged + { + context.Barrier(texture.ValidateAndGetID3D12Resource(context.GraphicsDevice)); + } + + /// + /// Inserts a resource barrier for a specific resource. + /// + /// The type of items stored on the texture. + /// The type of pixels used on the GPU side. + /// The to use to insert the resource barrier. + /// The input instance to insert the barrier for. + public static unsafe void Barrier(this in ComputeContext context, ReadWriteTexture2D texture) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + context.Barrier(texture.ValidateAndGetID3D12Resource(context.GraphicsDevice)); + } + + /// + /// Inserts a resource barrier for a specific resource. + /// + /// The type of items stored on the texture. + /// The type of pixels used on the GPU side. + /// The to use to insert the resource barrier. + /// The input instance to insert the barrier for. + public static unsafe void Barrier(this in ComputeContext context, ReadWriteTexture3D texture) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + context.Barrier(texture.ValidateAndGetID3D12Resource(context.GraphicsDevice)); + } + + /// + /// Inserts a resource barrier for a specific resource. + /// + /// The type of pixels stored on the texture. + /// The to use to insert the resource barrier. + /// The input instance to insert the barrier for. + public static unsafe void Barrier(this in ComputeContext context, IReadWriteTexture2D texture) + where TPixel : unmanaged + { + context.Barrier(((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetID3D12Resource(context.GraphicsDevice)); + } + + /// + /// Inserts a resource barrier for a specific resource. + /// + /// The type of pixels stored on the texture. + /// The to use to insert the resource barrier. + /// The input instance to insert the barrier for. + public static unsafe void Barrier(this in ComputeContext context, IReadWriteTexture3D texture) + where TPixel : unmanaged + { + context.Barrier(((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetID3D12Resource(context.GraphicsDevice)); + } + + /// + /// 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 instance representing the compute shader to run. + public static void For(this in ComputeContext context, int x, in T shader) + where T : struct, IComputeShader + { + context.Run(x, 1, 1, ref Unsafe.AsRef(in shader)); + } + + /// + /// 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 instance representing the compute shader to run. + public static void For(this in ComputeContext context, int x, int y, in T shader) + where T : struct, IComputeShader + { + context.Run(x, y, 1, ref Unsafe.AsRef(in shader)); + } + + /// + /// 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 instance representing the compute shader to run. + public static void For(this in ComputeContext context, int x, int y, int z, in T shader) + where T : struct, IComputeShader + { + context.Run(x, y, z, ref Unsafe.AsRef(in shader)); + } + + /// + /// 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 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 instance representing the compute shader to run. + public static void For(this in ComputeContext context, int x, int y, int z, int threadsX, int threadsY, int threadsZ, in T shader) + where T : struct, IComputeShader + { + context.Run(x, y, z, threadsX, threadsY, threadsZ, ref Unsafe.AsRef(in shader)); + } + + /// + /// Runs the input shader on a target instance, with the specified parameters. + /// + /// The type of pixel shader to run. + /// The type of pixels being processed by the shader. + /// The to use to run the shader. + /// The target texture to apply the pixel shader to. + public static void ForEach(this in ComputeContext context, IReadWriteTexture2D texture) + where T : struct, IPixelShader + where TPixel : unmanaged + { + context.Run(texture, ref Unsafe.AsRef(default(T))); + } + + /// + /// Runs the input shader on a target instance, with the specified parameters. + /// + /// The type of pixel shader to run. + /// The type of pixels being processed by the shader. + /// The to use to run the shader. + /// The target texture to apply the pixel shader to. + /// The input instance representing the pixel shader to run. + public static void ForEach(this in ComputeContext context, IReadWriteTexture2D texture, in T shader) + where T : struct, IPixelShader + where TPixel : unmanaged + { + context.Run(texture, ref Unsafe.AsRef(in shader)); + } +} diff --git a/src/ComputeSharp/Shaders/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp/Shaders/Extensions/Interop/ID3D12DeviceExtensions.cs similarity index 100% rename from src/ComputeSharp/Shaders/Extensions/ID3D12DeviceExtensions.cs rename to src/ComputeSharp/Shaders/Extensions/Interop/ID3D12DeviceExtensions.cs diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs index d7af2136..edd10335 100644 --- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs @@ -27,7 +27,7 @@ internal static class ShaderRunner private static readonly Dictionary ShadersCache = new(); /// - /// Compiles and runs the input shader on a target instance, with the specified parameters. + /// Runs the input shader on a target instance, with the specified parameters. /// /// The to use to run the shader. /// The number of iterations to run on the X axis. @@ -84,7 +84,7 @@ internal static class ShaderRunner } /// - /// Compiles and runs the input shader on a target instance, with the specified parameters. + /// Runs the input shader on a target instance, with the specified parameters. /// /// The to use to run the shader. /// The number of iterations to run on the X axis. @@ -122,26 +122,7 @@ internal static class ShaderRunner Guard.IsBetweenOrEqualTo(groupsY, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); Guard.IsBetweenOrEqualTo(groupsZ, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); - ShaderKey key = new(shader.GetDispatchId(), threadsX, threadsY, threadsZ); - PipelineData? pipelineData; - - lock (ShadersCache) - { - // Get or preload the shader - if (!ShadersCache.TryGetValue(key, out ICachedShader? shaderData)) - { - LoadShader(threadsX, threadsY, threadsZ, ref shader, out shaderData); - - // Cache for later use - ShadersCache.Add(key, shaderData); - } - - // Create the reusable pipeline state - if (!shaderData.CachedPipelines.TryGetValue(device, out pipelineData)) - { - CreatePipelineData(device, shaderData, out pipelineData); - } - } + PipelineData pipelineData = GetPipelineData(device, threadsX, threadsY, threadsZ, ref shader); using CommandList commandList = new(device, pipelineData.D3D12PipelineState); @@ -156,7 +137,7 @@ internal static class ShaderRunner } /// - /// Compiles and runs the input shader on a target instance, with the specified parameters. + /// Runs the input shader on a target instance, with the specified parameters. /// /// The to use to run the shader. /// The target texture to invoke the pixel shader upon. @@ -168,34 +149,16 @@ internal static class ShaderRunner int x = texture.Width; int y = texture.Height; - int threadsX = 8; - int threadsY = 8; + const int threadsX = 8; + const int threadsY = 8; + const int threadsZ = 1; int groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1); int groupsY = Math.DivRem(y, threadsY, out int modY) + (modY == 0 ? 0 : 1); Guard.IsBetweenOrEqualTo(groupsX, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); Guard.IsBetweenOrEqualTo(groupsY, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); - ShaderKey key = new(shader.GetDispatchId(), threadsX, threadsY, 1); - PipelineData? pipelineData; - - lock (ShadersCache) - { - // Get or preload the shader - if (!ShadersCache.TryGetValue(key, out ICachedShader? shaderData)) - { - LoadShader(threadsX, threadsY, 1, ref shader, out shaderData); - - // Cache for later use - ShadersCache.Add(key, shaderData); - } - - // Create the reusable pipeline state - if (!shaderData.CachedPipelines.TryGetValue(device, out pipelineData)) - { - CreatePipelineData(device, shaderData, out pipelineData); - } - } + PipelineData pipelineData = GetPipelineData(device, threadsX, threadsY, threadsZ, ref shader); using CommandList commandList = new(device, pipelineData.D3D12PipelineState); @@ -214,6 +177,40 @@ internal static class ShaderRunner commandList.ExecuteAndWaitForCompletion(); } + /// + /// Gets the instance for a given shader. + /// + /// The to use to run the shader. + /// 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 instance representing the compute shader to run. + /// The instance for a given shader. + public static unsafe PipelineData GetPipelineData(GraphicsDevice device, int threadsX, int threadsY, int threadsZ, ref T shader) + { + ShaderKey key = new(shader.GetDispatchId(), threadsX, threadsY, threadsZ); + + lock (ShadersCache) + { + // Get or preload the shader + if (!ShadersCache.TryGetValue(key, out ICachedShader? shaderData)) + { + LoadShader(threadsX, threadsY, threadsZ, ref shader, out shaderData); + + // Cache for later use + ShadersCache.Add(key, shaderData); + } + + // Create the reusable pipeline state + if (!shaderData.CachedPipelines.TryGetValue(device, out PipelineData? pipelineData)) + { + CreatePipelineData(device, shaderData, out pipelineData); + } + + return pipelineData; + } + } + /// /// Loads a shader with the specified parameters. /// diff --git a/tests/ComputeSharp.Tests/ComputeContextTests.cs b/tests/ComputeSharp.Tests/ComputeContextTests.cs new file mode 100644 index 00000000..c0b48044 --- /dev/null +++ b/tests/ComputeSharp.Tests/ComputeContextTests.cs @@ -0,0 +1,204 @@ +using System; +using System.Linq; +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests; + +[TestClass] +[TestCategory("ComputeContext")] +public partial class ComputeContextTests +{ + [CombinatorialTestMethod] + [AllDevices] + public void For_Batched(Device device) + { + int[] array = Enumerable.Range(0, 1024).ToArray(); + + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(array); + + using (ComputeContext context = device.Get().CreateComputeContext()) + { + context.For(512, new OffsetComputeShader(buffer, 0)); + context.For(64, new OffsetComputeShader(buffer, 512)); + context.For(299, new OffsetComputeShader(buffer, 576)); + context.For(149, new OffsetComputeShader(buffer, 875)); + } + + int[] result = buffer.ToArray(); + + foreach (ref int x in array.AsSpan()) + { + x *= 2; + } + + CollectionAssert.AreEqual(array, result); + } + + [CombinatorialTestMethod] + [AllDevices] + public void ForEach_Batched(Device device) + { + using ReadWriteTexture2D texture = device.Get().AllocateReadWriteTexture2D(128, 128); + + using (ComputeContext context = device.Get().CreateComputeContext()) + { + context.ForEach(texture, default(ClearPixelShader)); + context.Barrier(texture); + context.ForEach(texture, new ColorPixelShader(new float4(0.22f, 0.44f, 0.66f, 0.88f))); + } + + Rgba32[,] result = texture.ToArray(); + + foreach (Rgba32 pixel in result) + { + Assert.AreEqual(pixel.R, 56); + Assert.AreEqual(pixel.G, 112); + Assert.AreEqual(pixel.B, 168); + Assert.AreEqual(pixel.A, 224); + } + } + + [CombinatorialTestMethod] + [AllDevices] + public void ForAndForEach_Batched(Device device) + { + int[] array = Enumerable.Range(0, 1024).ToArray(); + + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(array); + using ReadWriteTexture2D texture = device.Get().AllocateReadWriteTexture2D(128, 128); + + using (ComputeContext context = device.Get().CreateComputeContext()) + { + context.For(512, new OffsetComputeShader(buffer, 0)); + context.For(64, new OffsetComputeShader(buffer, 512)); + context.ForEach(texture, default(ClearPixelShader)); + context.For(299, new OffsetComputeShader(buffer, 576)); + context.Barrier(texture); + context.ForEach(texture, new ColorPixelShader(new float4(0.22f, 0.44f, 0.66f, 0.88f))); + context.For(149, new OffsetComputeShader(buffer, 875)); + } + + // Buffer test + { + int[] result = buffer.ToArray(); + + foreach (ref int x in array.AsSpan()) + { + x *= 2; + } + + CollectionAssert.AreEqual(array, result); + } + + // Texture test + { + Rgba32[,] result = texture.ToArray(); + + foreach (Rgba32 pixel in result) + { + Assert.AreEqual(pixel.R, 56); + Assert.AreEqual(pixel.G, 112); + Assert.AreEqual(pixel.B, 168); + Assert.AreEqual(pixel.A, 224); + } + } + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(InvalidOperationException))] + public void Barrier_WithoutPreviousDispatches_ThrowsException(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(64); + + using (ComputeContext context = device.Get().CreateComputeContext()) + { + context.Barrier(buffer); + } + + Assert.Fail(); + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(InvalidOperationException))] + public void DefaultContext_Barrier_ThrowsException(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(64); + + using ComputeContext context = default; + + context.Barrier(buffer); + + Assert.Fail(); + } + + [TestMethod] + [ExpectedException(typeof(InvalidOperationException))] + public void DefaultContext_For_ThrowsException() + { + using ComputeContext context = default; + + context.For(32, 1, 1, default(OffsetComputeShader)); + + Assert.Fail(); + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(InvalidOperationException))] + public void DefaultContext_ForEach_ThrowsException(Device device) + { + using ReadWriteTexture2D texture = device.Get().AllocateReadWriteTexture2D(128, 128); + + using ComputeContext context = default; + + context.ForEach(texture, default(ColorPixelShader)); + + Assert.Fail(); + } + + [TestMethod] + [ExpectedException(typeof(InvalidOperationException))] + public void DefaultContext_Dispose_ThrowsException() + { + using ComputeContext context = default; + } + + [AutoConstructor] + internal readonly partial struct OffsetComputeShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + public readonly int offset; + + /// + public void Execute() + { + buffer[offset + ThreadIds.X] *= 2; + } + } + + [AutoConstructor] + internal readonly partial struct ClearPixelShader : IPixelShader + { + /// + public float4 Execute() + { + return default; + } + } + + [AutoConstructor] + internal readonly partial struct ColorPixelShader : IPixelShader + { + public readonly float4 color; + + /// + public float4 Execute() + { + return color; + } + } +}