Switched library code to use new data loader pattern

このコミットが含まれているのは:
Sergio Pedri committed 2021-07-12 15:58:51 +02:00
1 親 7e86a23d76
コミット b386c23742
8ファイル変更
+89 -217

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

+4 -1
ファイルの表示
@@ -1,12 +1,15 @@
using System;
using ComputeSharp.__Internals;
using ComputeSharp.Interop;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
#pragma warning disable CS0618
namespace ComputeSharp.SwapChain.Backend
{
internal sealed class SwapChainApplication<T> : Win32Application
where T : struct, IPixelShader<Float4>
where T : struct, IPixelShader<Float4>, IShader<T>
{
/// <summary>
/// The <see cref="Func{T1, TResult}"/> instance used to create shaders to run.
+61
ファイルの表示
@@ -0,0 +1,61 @@
using System;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.__Internals;
using TerraFX.Interop;
using System.Runtime.InteropServices;
#pragma warning disable CS0618
namespace ComputeSharp.Shaders.Dispatching
{
/// <summary>
/// A data loader for pixel shaders.
/// </summary>
internal readonly unsafe struct PixelShaderDispatchDataLoader : IDispatchDataLoader
{
/// <summary>
/// The <see cref="ID3D12GraphicsCommandList"/> object in use.
/// </summary>
private readonly ID3D12GraphicsCommandList* d3D12GraphicsCommandList;
/// <summary>
/// Creates a new <see cref="PixelShaderDispatchDataLoader"/> instance.
/// </summary>
/// <param name="d3D12GraphicsCommandList">The <see cref="ID3D12GraphicsCommandList"/> object to use.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal PixelShaderDispatchDataLoader(ID3D12GraphicsCommandList* d3D12GraphicsCommandList)
{
this.d3D12GraphicsCommandList = d3D12GraphicsCommandList;
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void LoadCapturedValues(ReadOnlySpan<uint> data)
{
this.d3D12GraphicsCommandList->SetComputeRoot32BitConstants(data);
}
/// <inheritdoc/>
public void LoadCapturedResources(ReadOnlySpan<ulong> data)
{
ID3D12GraphicsCommandList* d3D12GraphicsCommandList = this.d3D12GraphicsCommandList;
ref ulong resourcesRef = ref MemoryMarshal.GetReference(data);
ref D3D12_GPU_DESCRIPTOR_HANDLE startRef = ref Unsafe.As<ulong, D3D12_GPU_DESCRIPTOR_HANDLE>(ref resourcesRef);
ref D3D12_GPU_DESCRIPTOR_HANDLE endRef = ref Unsafe.Add(ref startRef, data.Length);
uint offset = 2;
// Skip the first target resource, as that is loaded explicitly by the shader runner using the
// target texture passed in by the user, which is not actually captured by the shader itself.
// The target root descriptor table index is therefore 2 in this case, as it needs to skip not
// only the this implicit texture to draw on, but also the constant buffer with capture values.
while (Unsafe.IsAddressLessThan(ref startRef, ref endRef))
{
d3D12GraphicsCommandList->SetComputeRootDescriptorTable(offset, startRef);
startRef = ref Unsafe.Add(ref startRef, 1);
offset++;
}
}
}
}
+8 -5
ファイルの表示
@@ -1,11 +1,14 @@
using System;
using System.Runtime.CompilerServices;
using ComputeSharp.__Internals;
using ComputeSharp.Core.Extensions;
using ComputeSharp.Shaders.Renderer;
using ComputeSharp.Shaders.Translation;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
#pragma warning disable CS0618
namespace ComputeSharp.Interop
{
/// <summary>
@@ -28,7 +31,7 @@ namespace ComputeSharp.Interop
/// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead.
/// </remarks>
public static void GetShaderInfo<T>(out ShaderInfo shaderInfo)
where T : struct, IComputeShader
where T : struct, IComputeShader, IShader<T>
{
GetNonGenericShaderInfo(default(T), out shaderInfo);
}
@@ -45,7 +48,7 @@ namespace ComputeSharp.Interop
/// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead.
/// </remarks>
public static unsafe void GetShaderInfo<T>(in T shader, out ShaderInfo shaderInfo)
where T : struct, IComputeShader
where T : struct, IComputeShader, IShader<T>
{
GetNonGenericShaderInfo(in shader, out shaderInfo);
}
@@ -66,7 +69,7 @@ namespace ComputeSharp.Interop
/// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead.
/// </remarks>
public static void GetShaderInfo<T, TPixel>(out ShaderInfo shaderInfo)
where T : struct, IPixelShader<TPixel>
where T : struct, IPixelShader<TPixel>, IShader<T>
where TPixel : unmanaged
{
GetNonGenericShaderInfo(default(T), out shaderInfo);
@@ -85,7 +88,7 @@ namespace ComputeSharp.Interop
/// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead.
/// </remarks>
public static unsafe void GetShaderInfo<T, TPixel>(in T shader, out ShaderInfo shaderInfo)
where T : struct, IPixelShader<TPixel>
where T : struct, IPixelShader<TPixel>, IShader<T>
where TPixel : unmanaged
{
GetNonGenericShaderInfo(in shader, out shaderInfo);
@@ -98,7 +101,7 @@ namespace ComputeSharp.Interop
/// <param name="shader">The input shader to retrieve info for.</param>
/// <param name="shaderInfo">The resulting <see cref="ShaderInfo"/> instance.</param>
private static unsafe void GetNonGenericShaderInfo<T>(in T shader, out ShaderInfo shaderInfo)
where T : struct
where T : struct, IShader<T>
{
ShaderLoader<T> shaderLoader = ShaderLoader<T>.Load(in shader);
+3 -19
ファイルの表示
@@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.Shaders.Extensions;
using ComputeSharp.Shaders.Renderer;
using ComputeSharp.Shaders.Translation;
@@ -189,13 +188,12 @@ namespace ComputeSharp.Shaders
// Create the shader key
ShaderKey key = new(shader.GetDispatchId(), threadsX, threadsY, 1);
CachedShader<T> shaderData;
PipelineData? pipelineData;
lock (ShadersCache)
{
// Get or preload the shader
if (!ShadersCache.TryGetValue(key, out shaderData))
if (!ShadersCache.TryGetValue(key, out CachedShader<T> shaderData))
{
LoadShader(threadsX, threadsY, 1, in shader, out shaderData);
@@ -216,29 +214,15 @@ namespace ComputeSharp.Shaders
commandList.D3D12GraphicsCommandList->SetComputeRootSignature(pipelineData.D3D12RootSignature);
commandList.D3D12GraphicsCommandList->SetPipelineState(pipelineData.D3D12PipelineState);
// Extract the dispatch data for the shader invocation
using DispatchData dispatchData = shaderData.Loader.GetDispatchData(device, in shader, x, y, 1);
ComputeShaderDispatchDataLoader dataLoader = new(commandList.D3D12GraphicsCommandList);
// Initialize the loop targets and the captured values
commandList.D3D12GraphicsCommandList->SetComputeRoot32BitConstants(dispatchData.Variables);
shader.LoadDispatchData(in dataLoader, device, x, y, 1);
// Load the implicit output texture
commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable(
1,
((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetGpuDescriptorHandle(device));
// Skip the last (missing) resource, as the internal counter is exceeding the number of explicit
// resources that the shader has actually captured (since it includes the target texture too).
// For the same reason, the target root descriptor table index is also offset by 2, as it needs
// to skip not only the constant buffer with capture values, but the implicit texture as well.
ReadOnlySpan<D3D12_GPU_DESCRIPTOR_HANDLE> resources = dispatchData.Resources[..^1];
for (int i = 0; i < resources.Length; i++)
{
// Load the captured buffers
commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable((uint)i + 2, resources[i]);
}
// Dispatch and wait for completion
commandList.D3D12GraphicsCommandList->Dispatch((uint)groupsX, (uint)groupsY, 1);
commandList.ExecuteAndWaitForCompletion();
+4 -1
ファイルの表示
@@ -1,7 +1,10 @@
using System.Runtime.CompilerServices;
using ComputeSharp.__Internals;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Shaders.Translation.Interop;
#pragma warning disable CS0618
namespace ComputeSharp.Shaders.Translation.Models
{
/// <summary>
@@ -9,7 +12,7 @@ namespace ComputeSharp.Shaders.Translation.Models
/// </summary>
/// <typeparam name="T">The type of compute shader in use.</typeparam>
internal readonly struct CachedShader<T>
where T : struct
where T : struct, IShader<T>
{
/// <summary>
/// The <see cref="ShaderLoader{T}"/> instance with the shader metadata.
-87
ファイルの表示
@@ -1,87 +0,0 @@
using System;
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using TerraFX.Interop;
namespace ComputeSharp.Shaders.Translation.Models
{
/// <summary>
/// A <see langword="struct"/> that contains all the captured data to dispatch a shader.
/// </summary>
internal readonly ref struct DispatchData
{
/// <summary>
/// The <see cref="ulong"/> array (actually <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> values) with the captured buffers.
/// </summary>
private readonly ulong[] resourcesArray;
/// <summary>
/// The number of <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> values in <see cref="resourcesArray"/>.
/// </summary>
private readonly int resourcesCount;
/// <summary>
/// The <see cref="byte"/> array with all the captured variables, with proper padding.
/// </summary>
private readonly byte[] variablesArray;
/// <summary>
/// The actual size in bytes to use from <see cref="variablesArray"/>.
/// </summary>
private readonly int variablesByteSize;
/// <summary>
/// Creates a new <see cref="DispatchData"/> instance with the specified parameters.
/// </summary>
/// <param name="resourcesArray">The <see cref="ulong"/> array with the captured buffers.</param>
/// <param name="resourcesCount">The number of <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> instances in <see cref="resourcesArray"/>.</param>
/// <param name="variablesArray">The <see cref="byte"/> array with all the captured variables, with proper padding.</param>
/// <param name="variablesByteSize">The actual size in bytes to use from <see cref="variablesArray"/>.</param>
public DispatchData(ulong[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize)
{
this.resourcesArray = resourcesArray;
this.variablesArray = variablesArray;
this.resourcesCount = resourcesCount;
this.variablesByteSize = variablesByteSize;
}
/// <summary>
/// Gets a <see cref="ReadOnlySpan{T}"/> with all the captured buffers.
/// </summary>
public ReadOnlySpan<D3D12_GPU_DESCRIPTOR_HANDLE> Resources
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray);
ref D3D12_GPU_DESCRIPTOR_HANDLE r1 = ref Unsafe.As<ulong, D3D12_GPU_DESCRIPTOR_HANDLE>(ref r0);
return MemoryMarshal.CreateReadOnlySpan(ref r1, this.resourcesCount);
}
}
/// <summary>
/// Gets a <see cref="ReadOnlySpan{T}"/> with the padded data representing all the captured variables.
/// </summary>
public unsafe ReadOnlySpan<uint> Variables
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ref byte r0 = ref MemoryMarshal.GetArrayDataReference(this.variablesArray);
ref uint r1 = ref Unsafe.As<byte, uint>(ref r0);
int length = (int)((uint)this.variablesByteSize / sizeof(uint));
return MemoryMarshal.CreateReadOnlySpan(ref r1, length);
}
}
/// <inheritdoc cref="IDisposable.Dispose"/>
public void Dispose()
{
ArrayPool<ulong>.Shared.Return(this.resourcesArray);
ArrayPool<byte>.Shared.Return(this.variablesArray);
}
}
}
-97
ファイルの表示
@@ -1,97 +0,0 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.__Internals;
using ComputeSharp.Shaders.Translation.Models;
using TerraFX.Interop;
#pragma warning disable CS0419, CS0618
namespace ComputeSharp.Shaders.Translation
{
/// <inheritdoc cref="ShaderLoader{T}"/>
internal sealed partial class ShaderLoader<T>
{
/// <summary>
/// A <see langword="delegate"/> that loads all the captured members from a shader instance.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="shader">The shader instance to load the data from.</param>
/// <param name="r0">
/// A reference to the buffer with all the captured <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> instances.
/// This is just represented as a <see cref="ulong"/> reference, to avoid exposing the type publicly.
/// </param>
/// <param name="r1">A reference to the buffer to use to store all the captured value types.</param>
/// <returns>The returned value indicates the total number of written bytes into <paramref name="r1"/>.</returns>
private delegate int DispatchDataLoader(GraphicsDevice device, in T shader, ref ulong r0, ref byte r1);
/// <summary>
/// The number of captured graphics resources (buffers).
/// </summary>
private int totalResourceCount;
/// <summary>
/// The cached <see cref="DispatchDataLoader"/> instance to load dispatch data before execution.
/// </summary>
private DispatchDataLoader? dispatchDataLoader;
/// <summary>
/// The <see cref="List{T}"/> of <see cref="FieldInfo"/> instances mapping the captured variables in the current shader.
/// </summary>
private readonly List<FieldInfo> capturedFields = new();
/// <summary>
/// Gets a new <see cref="DispatchData"/> instance with all the captured data for the current shader instance.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</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>
[Pure]
public DispatchData GetDispatchData(GraphicsDevice device, in T shader, int x, int y, int z)
{
// Resources and variables buffers
ulong[] resources = ArrayPool<ulong>.Shared.Rent(this.totalResourceCount);
byte[] variables = ArrayPool<byte>.Shared.Rent(256);
ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(resources);
ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables);
// Set the x, y and (optionally) z counters
Unsafe.As<byte, int>(ref r1) = x;
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 1) = y;
if (IsComputeShader)
{
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 2) = z;
}
// Invoke the dynamic method to extract the captured data
int totalVariablesByteSize = this.dispatchDataLoader!(device, in shader, ref r0, ref r1);
return new(resources, this.totalResourceCount, variables, totalVariablesByteSize);
}
/// <summary>
/// Initializes the <see cref="DispatchDataLoader"/> instance that loads the dispatch data for the current shader type.
/// </summary>
private void InitializeDispatchDataLoader()
{
// Get the generated data loader
Type[] argumentTypes = new[] { typeof(GraphicsDevice), typeof(T).MakeByRefType(), typeof(ulong).MakeByRefType(), typeof(byte).MakeByRefType() };
Type type = typeof(T).Assembly.GetType("ComputeSharp.__Internals.DispatchDataLoader")!;
MethodInfo method = type.GetMethod("LoadDispatchData", argumentTypes)!;
// Extract the computed count of 32 bit root constants to load
D3D12Root32BitConstantsCount = ((ComputeRoot32BitConstantsAttribute)method.ReturnTypeCustomAttributes.GetCustomAttributes(false)[0]).Count;
// Create a delegate from the generated shader data loader
this.dispatchDataLoader = method.CreateDelegate<DispatchDataLoader>();
}
}
}
+9 -7
ファイルの表示
@@ -19,13 +19,18 @@ namespace ComputeSharp.Shaders.Translation
/// </summary>
/// <typeparam name="T">The type of compute shader currently in use.</typeparam>
internal sealed partial class ShaderLoader<T> : IShaderLoader
where T : struct
where T : struct, IShader<T>
{
/// <summary>
/// The associated <see cref="IComputeShaderSourceAttribute"/> instance for the current shader type.
/// </summary>
private static readonly IComputeShaderSourceAttribute Attribute = IComputeShaderSourceAttribute.GetForType<T>();
/// <summary>
/// The <see cref="List{T}"/> of <see cref="FieldInfo"/> instances mapping the captured variables in the current shader.
/// </summary>
private readonly List<FieldInfo> capturedFields = new();
/// <summary>
/// The number of constant buffers to define in the shader.
/// </summary>
@@ -151,8 +156,6 @@ namespace ComputeSharp.Shaders.Translation
// the input shader once to avoid allocating it multiple times while processing the shader.
@this.d3D12DescriptorRanges1 = @this.LoadFieldsInfo(shader);
@this.InitializeDispatchDataLoader();
return @this;
}
@@ -173,6 +176,9 @@ namespace ComputeSharp.Shaders.Translation
{
this.definesInfo.Add(pair.Key, pair.Value);
}
// Extract the computed count of 32 bit root constants to load
D3D12Root32BitConstantsCount = ((ComputeRoot32BitConstantsAttribute)typeof(T).GetMethod(nameof(IShader<T>.LoadDispatchData))!.ReturnTypeCustomAttributes.GetCustomAttributes(false)[0]).Count;
}
/// <summary>
@@ -200,7 +206,6 @@ namespace ComputeSharp.Shaders.Translation
(string hlslType, string hlslName) = Attribute.ImplicitTextureField!.Value;
this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++));
this.totalResourceCount++;
break;
}
@@ -251,7 +256,6 @@ namespace ComputeSharp.Shaders.Translation
this.capturedFields.Add(fieldInfo);
this.hlslResourceInfo.Add(new HlslResourceInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++));
this.totalResourceCount++;
}
else if (HlslKnownTypes.IsReadOnlyResourceType(fieldType))
{
@@ -259,7 +263,6 @@ namespace ComputeSharp.Shaders.Translation
this.capturedFields.Add(fieldInfo);
this.hlslResourceInfo.Add(new HlslResourceInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++));
this.totalResourceCount++;
}
else if (HlslKnownTypes.IsReadWriteResourceType(fieldType))
{
@@ -267,7 +270,6 @@ namespace ComputeSharp.Shaders.Translation
this.capturedFields.Add(fieldInfo);
this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++));
this.totalResourceCount++;
}
else if (fieldInfo.GetValue(shader) is Delegate func)
{