Merge pull request #182 from Sergio0694/feature/compute-context

Add ComputeContext APIs
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2021-12-28 18:49:56 +01:00
コミット 184856b66f
15ファイル変更
+941 -81

検索条件に一致するファイルはありません

+91
ファイルの表示
@@ -0,0 +1,91 @@
using System;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
namespace ComputeSharp.Benchmark.Blas;
/// <summary>
/// A <see langword="class"/> that benchmarks the shader dispatch times.
/// </summary>
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
public partial class DispatchingBenchmark : IDisposable
{
/// <summary>
/// The test buffer.
/// </summary>
private ReadWriteBuffer<float>? Buffer;
/// <summary>
/// Initial setup for a benchmarking session.
/// </summary>
[GlobalSetup]
public void Setup()
{
Buffer = GraphicsDevice.Default.AllocateReadWriteBuffer<float>(128);
}
/// <inheritdoc/>
[GlobalCleanup]
public void Dispose()
{
Buffer!.Dispose();
}
/// <summary>
/// Invokes a single shader, manually.
/// </summary>
[Benchmark(Baseline = true)]
[BenchmarkCategory("SINGLE")]
public void Compute_Single()
{
GraphicsDevice.Default.For(64, new TestShader(Buffer!));
}
/// <summary>
/// Invokes a single shader through a compute context.
/// </summary>
[Benchmark]
[BenchmarkCategory("SINGLE")]
public void Compute_Single_WithContext()
{
using var context = GraphicsDevice.Default.CreateComputeContext();
context.For(64, new TestShader(Buffer!));
}
/// <summary>
/// Invokes two empty compute shaders one by one.
/// </summary>
[Benchmark(Baseline = true)]
[BenchmarkCategory("MULTIPLE")]
public void Compute_Multiple()
{
GraphicsDevice.Default.For(64, new TestShader(Buffer!));
GraphicsDevice.Default.For(64, new TestShader(Buffer!));
}
/// <summary>
/// Invokes two empty compute shaders in a batch.
/// </summary>
[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<float> buffer;
/// <inheritdoc/>
public void Execute()
{
}
}
}
+7 -2
ファイルの表示
@@ -286,12 +286,17 @@ public sealed partial class HlslBokehBlurProcessor
kernel.CopyFrom(Kernels[j]);
GraphicsDevice.For<VerticalConvolutionProcessor>(
using var context = GraphicsDevice.CreateComputeContext();
context.For<VerticalConvolutionProcessor>(
source.Width,
source.Height,
new(texture, reals, imaginaries, kernel));
GraphicsDevice.For<HorizontalConvolutionAndAccumulatePartialsProcessor>(
context.Barrier(reals);
context.Barrier(imaginaries);
context.For<HorizontalConvolutionAndAccumulatePartialsProcessor>(
source.Width,
source.Height,
new(parameters.Z, parameters.W, reals, imaginaries, temporary, kernel));
+6 -2
ファイルの表示
@@ -105,8 +105,12 @@ public sealed partial class HlslGaussianBlurProcessor
using ReadWriteTexture2D<Rgba32, Vector4> firstPassTexture = GraphicsDevice.AllocateReadWriteTexture2D<Rgba32, Vector4>(source.Width, source.Height);
using ReadOnlyBuffer<float> kernelBuffer = GraphicsDevice.AllocateReadOnlyBuffer(Kernel);
GraphicsDevice.For<VerticalConvolutionProcessor>(source.Width, source.Height, new(sourceTexture, firstPassTexture, kernelBuffer));
GraphicsDevice.For<HorizontalConvolutionProcessor>(source.Width, source.Height, new(firstPassTexture, sourceTexture, kernelBuffer));
using (var context = GraphicsDevice.CreateComputeContext())
{
context.For<VerticalConvolutionProcessor>(source.Width, source.Height, new(sourceTexture, firstPassTexture, kernelBuffer));
context.Barrier(firstPassTexture);
context.For<HorizontalConvolutionProcessor>(source.Width, source.Height, new(firstPassTexture, sourceTexture, kernelBuffer));
}
sourceTexture.CopyTo(span);
}
+10
ファイルの表示
@@ -78,6 +78,16 @@ internal unsafe ref struct CommandList
device.SetDescriptorHeapForCommandList(this.d3D12GraphicsCommandList);
}
/// <summary>
/// Gets whether or not the curreent <see cref="CommandList"/> instance is allocated.
/// </summary>
public readonly bool IsAllocated => this.device is not null;
/// <summary>
/// Gets the <see cref="GraphicsDevice"/> instance associated with the current command list.
/// </summary>
public GraphicsDevice GraphicsDevice => this.device;
/// <summary>
/// Gets the command list type being used by the current instance.
/// </summary>
+28 -6
ファイルの表示
@@ -9,7 +9,7 @@ namespace ComputeSharp;
public static partial class GraphicsDeviceExtensions
{
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// Runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
@@ -22,7 +22,7 @@ public static partial class GraphicsDeviceExtensions
}
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// Runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
@@ -36,7 +36,7 @@ public static partial class GraphicsDeviceExtensions
}
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// Runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
@@ -51,7 +51,7 @@ public static partial class GraphicsDeviceExtensions
}
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// Runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
@@ -69,7 +69,7 @@ public static partial class GraphicsDeviceExtensions
}
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// Runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of pixel shader to run.</typeparam>
/// <typeparam name="TPixel">The type of pixels being processed by the shader.</typeparam>
@@ -83,7 +83,7 @@ public static partial class GraphicsDeviceExtensions
}
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// Runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of pixel shader to run.</typeparam>
/// <typeparam name="TPixel">The type of pixels being processed by the shader.</typeparam>
@@ -96,4 +96,26 @@ public static partial class GraphicsDeviceExtensions
{
ShaderRunner<T>.Run(device, texture, ref Unsafe.AsRef(in shader));
}
/// <summary>
/// Creates a new <see cref="ComputeContext"/> instance to batch compute operations together.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run shaders.</param>
/// <returns>A new <see cref="ComputeContext"/> instance to batch compute operations together.</returns>
/// <remarks>
/// The returned <see cref="ComputeContext"/> instance should be used in a <see langword="using"/> block or declaration:
/// <code>
/// using (var context = device.CreateComputeContext())
/// {
/// // Dispatch shaders here...
/// }
/// </code>
/// All dispatched shaders will be executed as soon as the context goes out of scope.
/// </remarks>
public static ComputeContext CreateComputeContext(this GraphicsDevice device)
{
device.ThrowIfDisposed();
return new(device);
}
}
+15 -1
ファイルの表示
@@ -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
/// <param name="d3D12Resource">The <see cref="ID3D12Resource"/> to change state for.</param>
/// <param name="d3D12ResourceStatesBefore">The starting <see cref="D3D12_RESOURCE_STATES"/> value for the transition.</param>
/// <param name="d3D12ResourceStatesAfter">The destnation <see cref="D3D12_RESOURCE_STATES"/> value for the transition.</param>
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);
}
/// <summary>
/// Inserts a UAV resource barrier for a specific resource.
/// </summary>
/// <param name="d3D12GraphicsCommandList">The <see cref="ID3D12GraphicsCommandList"/> instance in use.</param>
/// <param name="d3D12Resource">The <see cref="ID3D12Resource"/> to insert the barrier for.</param>
public static void UAVBarrier(this ref ID3D12GraphicsCommandList d3D12GraphicsCommandList, ID3D12Resource* d3D12Resource)
{
D3D12_RESOURCE_BARRIER d3D12ResourceBarrier = D3D12_RESOURCE_BARRIER.InitUAV(d3D12Resource);
d3D12GraphicsCommandList.ResourceBarrier(1, &d3D12ResourceBarrier);
}
/// <summary>
/// Binds an input constant buffer to the first root parameter.
/// </summary>
+8 -1
ファイルの表示
@@ -17,7 +17,7 @@ public static class GraphicsResourceHelper
/// <summary>
/// An interface for non-generic graphics resource types.
/// </summary>
internal interface IGraphicsResource
internal unsafe interface IGraphicsResource
{
/// <summary>
/// Validates the given resource for usage with a specified device, and retrieves its GPU descriptor handle.
@@ -25,6 +25,13 @@ public static class GraphicsResourceHelper
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
/// <returns>The GPU descriptor handle for the resource.</returns>
D3D12_GPU_DESCRIPTOR_HANDLE ValidateAndGetGpuDescriptorHandle(GraphicsDevice device);
/// <summary>
/// Validates the given resource for usage with a specified device, and retrieves the underlying <see cref="ID3D12Resource"/> object.
/// </summary>
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
/// <returns>The the underlying <see cref="ID3D12Resource"/> object.</returns>
ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device);
}
/// <summary>
+9
ファイルの表示
@@ -306,4 +306,13 @@ public abstract class StructuredBuffer<T> : Buffer<T>
copyCommandList.ExecuteAndWaitForCompletion();
}
}
/// <inheritdoc cref="__Internals.GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice)"/>
internal unsafe ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device)
{
ThrowIfDisposed();
ThrowIfDeviceMismatch(device);
return D3D12Resource;
}
}
+27 -12
ファイルの表示
@@ -207,7 +207,7 @@ public unsafe abstract class Texture2D<T> : 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<T> : 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<T> : 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<T> : 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<T> : 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<T> : 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<T> : 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<T> : 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<T> : 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<T> : 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<T> : NativeObject, GraphicsResourceHelper
}
}
/// <inheritdoc cref="GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice)"/>
internal ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device)
{
ThrowIfDisposed();
ThrowIfDeviceMismatch(device);
return D3D12Resource;
}
/// <inheritdoc/>
D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device)
{
@@ -563,4 +572,10 @@ public unsafe abstract class Texture2D<T> : NativeObject, GraphicsResourceHelper
return D3D12GpuDescriptorHandle;
}
/// <inheritdoc/>
ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device)
{
return ValidateAndGetID3D12Resource(device);
}
}
+27 -12
ファイルの表示
@@ -223,7 +223,7 @@ public unsafe abstract class Texture3D<T> : 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<T> : 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<T> : 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<T> : 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<T> : 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<T> : 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<T> : 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<T> : 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<T> : 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<T> : 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<T> : NativeObject, GraphicsResourceHelper
}
}
/// <inheritdoc cref="GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice)"/>
internal ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device)
{
ThrowIfDisposed();
ThrowIfDeviceMismatch(device);
return D3D12Resource;
}
/// <inheritdoc/>
D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device)
{
@@ -616,4 +625,10 @@ public unsafe abstract class Texture3D<T> : NativeObject, GraphicsResourceHelper
return D3D12GpuDescriptorHandle;
}
/// <inheritdoc/>
ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device)
{
return ValidateAndGetID3D12Resource(device);
}
}
+278
ファイルの表示
@@ -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;
/// <summary>
/// A context to batch compute operations in a single invocation, minimizing GPU overhead.
/// </summary>
public ref struct ComputeContext
{
/// <summary>
/// The <see cref="GraphicsDevice"/> instance owning the current context.
/// </summary>
private readonly GraphicsDevice device;
/// <summary>
/// The current <see cref="CommandList"/> instance used to dispatch shaders.
/// </summary>
private CommandList commandList;
/// <summary>
/// Creates a new <see cref="ComputeContext"/> instance with the specified parameters.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> instance owning the current context.</param>
internal ComputeContext(GraphicsDevice device)
{
this.device = device;
this.commandList = default;
}
/// <summary>
/// Gets the <see cref="ComputeSharp.GraphicsDevice"/> associated with the current instance.
/// </summary>
public GraphicsDevice GraphicsDevice => this.device;
/// <summary>
/// Inserts a resource barrier for a specific resource.
/// </summary>
/// <param name="d3D12Resource">The <see cref="ID3D12Resource"/> to insert the barrier for.</param>
internal readonly unsafe void Barrier(ID3D12Resource* d3D12Resource)
{
ThrowInvalidOperationExceptionIfDeviceIsNull();
ref CommandList commandList = ref GetCommandList(in this);
commandList.D3D12GraphicsCommandList->UAVBarrier(d3D12Resource);
}
/// <summary>
/// Runs the input shader with the specified parameters.
/// </summary>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
internal readonly unsafe void Run<T>(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);
}
/// <summary>
/// Runs the input shader with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
internal readonly unsafe void Run<T>(
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<T>.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);
}
/// <summary>
/// Runs the input shader with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of pixel shader to run.</typeparam>
/// <typeparam name="TPixel">The type of pixel to work on.</typeparam>
/// <param name="texture">The target texture to invoke the pixel shader upon.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the pixel shader to run.</param>
internal readonly unsafe void Run<T, TPixel>(IReadWriteTexture2D<TPixel> texture, ref T shader)
where T : struct, IPixelShader<TPixel>
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<T>.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);
}
/// <inheritdoc cref="IDisposable.Dispose"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
ThrowInvalidOperationExceptionIfDeviceIsNull();
if (!this.commandList.IsAllocated)
{
return;
}
this.commandList.ExecuteAndWaitForCompletion();
}
/// <summary>
/// Gets the current <see cref="CommandList"/> instance.
/// </summary>
/// <param name="this">The current <see cref="ComputeContext"/> instance.</param>
/// <returns>A reference to the <see cref="CommandList"/> instance to use.</returns>
/// <exception cref="InvalidOperationException">Thrown if the <see cref="CommandList"/> has not been initialized yet.</exception>
[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*<in ComputeContext, ref ComputeContext>)(delegate*<in byte, ref byte>)&Unsafe.AsRef<byte>)(in @this);
if (!context.commandList.IsAllocated)
{
ThrowHelper.ThrowInvalidOperationException("The current compute context has not yet been initialized.");
}
return ref context.commandList;
}
/// <summary>
/// Gets the current <see cref="CommandList"/> instance, and initializes it as needed.
/// </summary>
/// <param name="this">The current <see cref="ComputeContext"/> instance.</param>
/// <param name="pipelineState">The input <see cref="ID3D12PipelineState"/> to load.</param>
/// <returns>A reference to the <see cref="CommandList"/> instance to use.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe ref CommandList GetCommandList(in ComputeContext @this, ID3D12PipelineState* pipelineState)
{
ref ComputeContext context = ref ((delegate*<in ComputeContext, ref ComputeContext>)(delegate*<in byte, ref byte>)&Unsafe.AsRef<byte>)(in @this);
if (context.commandList.IsAllocated)
{
context.commandList.D3D12GraphicsCommandList->SetPipelineState(pipelineState);
}
else
{
context.commandList = new CommandList(context.device, pipelineState);
}
return ref context.commandList;
}
/// <summary>
/// Throws an <see cref="InvalidOperationException"/> if <see cref="device"/> is <see langword="null"/>.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if <see cref="device"/> is <see langword="null"/>.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private readonly void ThrowInvalidOperationExceptionIfDeviceIsNull()
{
if (this.device is null)
{
ThrowHelper.ThrowInvalidOperationException("The current compute context has not been initialized correctly.");
}
}
}
+189
ファイルの表示
@@ -0,0 +1,189 @@
using System.Runtime.CompilerServices;
using ComputeSharp.__Internals;
#pragma warning disable CS0618
namespace ComputeSharp;
/// <summary>
/// A <see langword="class"/> that contains extension methods for the <see cref="ComputeContext"/> type, used to run compute shaders.
/// </summary>
public static partial class ComputeContextExtensions
{
/// <summary>
/// Inserts a resource barrier for a specific resource.
/// </summary>
/// <typeparam name="T">The type of items stored on the buffer.</typeparam>
/// <param name="context">The <see cref="ComputeContext"/> to use to insert the resource barrier.</param>
/// <param name="buffer">The input <see cref="ReadWriteBuffer{T}"/> instance to insert the barrier for.</param>
public static unsafe void Barrier<T>(this in ComputeContext context, ReadWriteBuffer<T> buffer)
where T : unmanaged
{
context.Barrier(buffer.ValidateAndGetID3D12Resource(context.GraphicsDevice));
}
/// <summary>
/// Inserts a resource barrier for a specific resource.
/// </summary>
/// <typeparam name="T">The type of items stored on the texture.</typeparam>
/// <param name="context">The <see cref="ComputeContext"/> to use to insert the resource barrier.</param>
/// <param name="texture">The input <see cref="ReadWriteTexture2D{T}"/> instance to insert the barrier for.</param>
public static unsafe void Barrier<T>(this in ComputeContext context, ReadWriteTexture2D<T> texture)
where T : unmanaged
{
context.Barrier(texture.ValidateAndGetID3D12Resource(context.GraphicsDevice));
}
/// <summary>
/// Inserts a resource barrier for a specific resource.
/// </summary>
/// <typeparam name="T">The type of items stored on the texture.</typeparam>
/// <param name="context">The <see cref="ComputeContext"/> to use to insert the resource barrier.</param>
/// <param name="texture">The input <see cref="ReadWriteBuffer{T}"/> instance to insert the barrier for.</param>
public static unsafe void Barrier<T>(this in ComputeContext context, ReadWriteTexture3D<T> texture)
where T : unmanaged
{
context.Barrier(texture.ValidateAndGetID3D12Resource(context.GraphicsDevice));
}
/// <summary>
/// Inserts a resource barrier for a specific resource.
/// </summary>
/// <typeparam name="T">The type of items stored on the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="context">The <see cref="ComputeContext"/> to use to insert the resource barrier.</param>
/// <param name="texture">The input <see cref="ReadWriteTexture2D{T,TPixel}"/> instance to insert the barrier for.</param>
public static unsafe void Barrier<T, TPixel>(this in ComputeContext context, ReadWriteTexture2D<T, TPixel> texture)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
context.Barrier(texture.ValidateAndGetID3D12Resource(context.GraphicsDevice));
}
/// <summary>
/// Inserts a resource barrier for a specific resource.
/// </summary>
/// <typeparam name="T">The type of items stored on the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="context">The <see cref="ComputeContext"/> to use to insert the resource barrier.</param>
/// <param name="texture">The input <see cref="ReadWriteTexture3D{T,TPixel}"/> instance to insert the barrier for.</param>
public static unsafe void Barrier<T, TPixel>(this in ComputeContext context, ReadWriteTexture3D<T, TPixel> texture)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
context.Barrier(texture.ValidateAndGetID3D12Resource(context.GraphicsDevice));
}
/// <summary>
/// Inserts a resource barrier for a specific resource.
/// </summary>
/// <typeparam name="TPixel">The type of pixels stored on the texture.</typeparam>
/// <param name="context">The <see cref="ComputeContext"/> to use to insert the resource barrier.</param>
/// <param name="texture">The input <see cref="IReadWriteTexture2D{TPixel}"/> instance to insert the barrier for.</param>
public static unsafe void Barrier<TPixel>(this in ComputeContext context, IReadWriteTexture2D<TPixel> texture)
where TPixel : unmanaged
{
context.Barrier(((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetID3D12Resource(context.GraphicsDevice));
}
/// <summary>
/// Inserts a resource barrier for a specific resource.
/// </summary>
/// <typeparam name="TPixel">The type of pixels stored on the texture.</typeparam>
/// <param name="context">The <see cref="ComputeContext"/> to use to insert the resource barrier.</param>
/// <param name="texture">The input <see cref="IReadWriteTexture3D{TPixel}"/> instance to insert the barrier for.</param>
public static unsafe void Barrier<TPixel>(this in ComputeContext context, IReadWriteTexture3D<TPixel> texture)
where TPixel : unmanaged
{
context.Barrier(((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetID3D12Resource(context.GraphicsDevice));
}
/// <summary>
/// Runs the input shader on a target <see cref="ComputeContext"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
/// <param name="context">The <see cref="ComputeContext"/> to use to run the shader.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void For<T>(this in ComputeContext context, int x, in T shader)
where T : struct, IComputeShader
{
context.Run(x, 1, 1, ref Unsafe.AsRef(in shader));
}
/// <summary>
/// Runs the input shader on a target <see cref="ComputeContext"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
/// <param name="context">The <see cref="ComputeContext"/> to use to run the shader.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void For<T>(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));
}
/// <summary>
/// Runs the input shader on a target <see cref="ComputeContext"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
/// <param name="context">The <see cref="ComputeContext"/> to use to run the shader.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void For<T>(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));
}
/// <summary>
/// Runs the input shader on a target <see cref="ComputeContext"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
/// <param name="context">The <see cref="ComputeContext"/> to use to run the shader.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static void For<T>(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));
}
/// <summary>
/// Runs the input shader on a target <see cref="ComputeContext"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of pixel shader to run.</typeparam>
/// <typeparam name="TPixel">The type of pixels being processed by the shader.</typeparam>
/// <param name="context">The <see cref="ComputeContext"/> to use to run the shader.</param>
/// <param name="texture">The target texture to apply the pixel shader to.</param>
public static void ForEach<T, TPixel>(this in ComputeContext context, IReadWriteTexture2D<TPixel> texture)
where T : struct, IPixelShader<TPixel>
where TPixel : unmanaged
{
context.Run(texture, ref Unsafe.AsRef(default(T)));
}
/// <summary>
/// Runs the input shader on a target <see cref="ComputeContext"/> instance, with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of pixel shader to run.</typeparam>
/// <typeparam name="TPixel">The type of pixels being processed by the shader.</typeparam>
/// <param name="context">The <see cref="ComputeContext"/> to use to run the shader.</param>
/// <param name="texture">The target texture to apply the pixel shader to.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the pixel shader to run.</param>
public static void ForEach<T, TPixel>(this in ComputeContext context, IReadWriteTexture2D<TPixel> texture, in T shader)
where T : struct, IPixelShader<TPixel>
where TPixel : unmanaged
{
context.Run(texture, ref Unsafe.AsRef(in shader));
}
}
差分なしでファイル名を変更。
+42 -45
ファイルの表示
@@ -27,7 +27,7 @@ internal static class ShaderRunner<T>
private static readonly Dictionary<ShaderKey, ICachedShader> ShadersCache = new();
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// Runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
@@ -84,7 +84,7 @@ internal static class ShaderRunner<T>
}
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// Runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
@@ -122,26 +122,7 @@ internal static class ShaderRunner<T>
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<T>
}
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// Runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="texture">The target texture to invoke the pixel shader upon.</param>
@@ -168,34 +149,16 @@ internal static class ShaderRunner<T>
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<T>
commandList.ExecuteAndWaitForCompletion();
}
/// <summary>
/// Gets the <see cref="PipelineData"/> instance for a given shader.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
/// <returns>The <see cref="PipelineData"/> instance for a given shader.</returns>
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;
}
}
/// <summary>
/// Loads a shader with the specified parameters.
/// </summary>
+204
ファイルの表示
@@ -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<int> 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<Rgba32, float4> texture = device.Get().AllocateReadWriteTexture2D<Rgba32, float4>(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<int> buffer = device.Get().AllocateReadWriteBuffer(array);
using ReadWriteTexture2D<Rgba32, float4> texture = device.Get().AllocateReadWriteTexture2D<Rgba32, float4>(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<int> buffer = device.Get().AllocateReadWriteBuffer<int>(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<int> buffer = device.Get().AllocateReadWriteBuffer<int>(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<Rgba32, float4> texture = device.Get().AllocateReadWriteTexture2D<Rgba32, float4>(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<int> buffer;
public readonly int offset;
/// <inheritdoc/>
public void Execute()
{
buffer[offset + ThreadIds.X] *= 2;
}
}
[AutoConstructor]
internal readonly partial struct ClearPixelShader : IPixelShader<float4>
{
/// <inheritdoc/>
public float4 Execute()
{
return default;
}
}
[AutoConstructor]
internal readonly partial struct ColorPixelShader : IPixelShader<float4>
{
public readonly float4 color;
/// <inheritdoc/>
public float4 Execute()
{
return color;
}
}
}