Removed Vortice.Windows references and files

このコミットが含まれているのは:
Sergio Pedri committed 2020-11-17 19:40:24 +01:00
1 親 b67af4aaa1
コミット 4811769ebc
46ファイル変更
+1124 -3358

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

-1
ファイルの表示
@@ -10,7 +10,6 @@
<PackageReference Include="ICSharpCode.Decompiler" Version="5.0.2.5153" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.7.0" />
<PackageReference Include="Stubble.Core" Version="1.9.3" />
<PackageReference Include="Vortice.Dxc" Version="1.8.6" />
</ItemGroup>
<ItemGroup>
-204
ファイルの表示
@@ -1,204 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Shaders.Extensions;
using ComputeSharp.Shaders.Renderer;
using ComputeSharp.Shaders.Renderer.Models;
using ComputeSharp.Shaders.Translation;
using ComputeSharp.Shaders.Translation.Interop;
using ComputeSharp.Shaders.Translation.Models;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE;
namespace ComputeSharp.Shaders
{
/// <summary>
/// A <see langword="class"/> with helper methods to support <see cref="ShaderRunner2{T}"/>.
/// This type is primarily needed to avoid having fields being repeated per generic instantiation.
/// </summary>
internal static class ShaderRunner2
{
/// <summary>
/// A thread-safe map of reusable GPU buffers for captured locals.
/// </summary>
[ThreadStatic]
private static ConditionalWeakTable<GraphicsDevice2, ConstantBuffer2<Int4>>? variablesBuffers;
/// <summary>
/// Gets the reusable <see cref="ConstantBuffer2{T}"/> instance for a shader invocation.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice2"/> to use to run the shader.</param>
/// <returns>The reusable <see cref="ConstantBuffer2{T}"/> instance to populate.</returns>
[Pure]
public static ConstantBuffer2<Int4> GetVariablesBuffer(GraphicsDevice2 device)
{
ConditionalWeakTable<GraphicsDevice2, ConstantBuffer2<Int4>> map = variablesBuffers ??= new();
return map.GetValue(device, gpu => new ConstantBuffer2<Int4>(gpu, 4096));
}
}
/// <summary>
/// A <see langword="class"/> responsible for performing all the necessary operations to compile and run a compute shader.
/// </summary>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
internal static class ShaderRunner2<T>
where T : struct, IComputeShader
{
/// <summary>
/// The mapping used to cache and reuse compiled shaders.
/// </summary>
private static readonly Dictionary<ShaderKey, CachedShader2<T>> ShadersCache = new();
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice2"/> instance, with the specified parameters.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice2"/> 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 Run(GraphicsDevice2 device, int x, int y, int z, in T shader)
{
// Calculate the optimized thread num values
int threadsX, threadsY = 1, threadsZ = 1;
if (y == 1 && z == 1) threadsX = (int)device.WavefrontSize;
else if (z == 1) threadsX = threadsY = 8;
else threadsX = threadsY = threadsZ = 4;
Run(device, x, y, z, threadsX, threadsY, threadsZ, shader);
}
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice2"/> instance, with the specified parameters.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice2"/> 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 Run(
GraphicsDevice2 device,
int x, int y, int z,
int threadsX, int threadsY, int threadsZ,
in T shader)
{
// Create the shader key
ShaderKey key = new(ShaderHashCodeProvider.GetHashCode(shader), threadsX, threadsY, threadsZ);
CachedShader2<T> shaderData;
PipelineData? pipelineData;
lock (ShadersCache)
{
// Get or preload the shader
if (!ShadersCache.TryGetValue(key, out shaderData))
{
LoadShader(threadsX, threadsY, threadsZ, 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);
}
}
// Create the commands list and set the pipeline state
using CommandList2 commandList = new(device, D3D12_COMMAND_LIST_TYPE_COMPUTE);
commandList.SetPipelineData(pipelineData);
// Extract the dispatch data for the shader invocation
using DispatchData2 dispatchData = shaderData.Loader.GetDispatchData(shader, x, y, z);
// Load the captured buffers
ReadOnlySpan<D3D12_GPU_DESCRIPTOR_HANDLE> resources = dispatchData.Resources;
for (int i = 0; i < resources.Length; i++)
{
commandList.SetComputeRootDescriptorTable(i + 1, resources[i]);
}
// Initialize the loop targets and the captured values
ConstantBuffer2<Int4> variablesBuffer = ShaderRunner2.GetVariablesBuffer(device);
variablesBuffer.SetData(dispatchData.Variables);
commandList.SetComputeRootDescriptorTable(0, variablesBuffer.D3D12GpuDescriptorHandle);
// Calculate the dispatch values
int
groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1),
groupsY = Math.DivRem(y, threadsY, out int modY) + (modY == 0 ? 0 : 1),
groupsZ = Math.DivRem(z, threadsZ, out int modZ) + (modZ == 0 ? 0 : 1);
// Dispatch and wait for completion
commandList.Dispatch(groupsX, groupsY, groupsZ);
commandList.ExecuteAndWaitForCompletion();
}
/// <summary>
/// Loads a shader with the specified parameters.
/// </summary>
/// <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>
/// <param name="shaderData">The <see cref="CachedShader2{T}"/> instance to return with the cached shader data.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private static void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader2<T> shaderData)
{
// Load the input shader
ShaderLoader2<T> shaderLoader = ShaderLoader2<T>.Load(shader);
// Render the loaded shader
string shaderSource = ShaderRenderer.Instance.Render(new ShaderInfo
{
BuffersList = shaderLoader.HslsBuffersInfo,
FieldsList = shaderLoader.FieldsInfo,
NumThreadsX = threadsX,
NumThreadsY = threadsY,
NumThreadsZ = threadsZ,
ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName,
ShaderBody = shaderLoader.MethodBody,
FunctionsList = shaderLoader.FunctionsInfo,
LocalFunctionsList = shaderLoader.LocalFunctionsInfo
});
// Compile the loaded shader to HLSL bytecode
IDxcBlobObject shaderBytecode = new(ShaderCompiler2.CompileShader(shaderSource));
// Get the cached shader data
shaderData = new CachedShader2<T>(shaderLoader, shaderBytecode);
}
/// <summary>
/// Creates and caches a <see cref="PipelineData"/> instance for a given shader.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice2"/> to use to run the shader.</param>
/// <param name="shaderData">The <see cref="CachedShader2{T}"/> instance with the data on the loaded shader.</param>
/// <param name="pipelineData">The resulting <see cref="PipelineData"/> instance to use to run the shader.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe void CreatePipelineData(GraphicsDevice2 device, in CachedShader2<T> shaderData, out PipelineData pipelineData)
{
using ComPtr<ID3D12RootSignature> d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12DescriptorRanges1);
D3D12_SHADER_BYTECODE d3D12ShaderBytecode = new((ID3DBlob*)shaderData.Bytecode.DxcBlob);
using ComPtr<ID3D12PipelineState> d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), d3D12ShaderBytecode);
pipelineData = new PipelineData(d3D12RootSignature.Move(), d3D12PipelineState.Move());
shaderData.CachedPipelines.Add(device, pipelineData);
}
}
}
+69 -63
ファイルの表示
@@ -3,14 +3,15 @@ using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Shaders.Extensions;
using ComputeSharp.Shaders.Renderer;
using ComputeSharp.Shaders.Renderer.Models;
using ComputeSharp.Shaders.Translation;
using ComputeSharp.Shaders.Translation.Interop;
using ComputeSharp.Shaders.Translation.Models;
using Vortice.Direct3D12;
using CommandList = ComputeSharp.Graphics.Commands.CommandList;
using PipelineState = ComputeSharp.Graphics.Commands.PipelineState;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE;
namespace ComputeSharp.Shaders
{
@@ -21,45 +22,50 @@ namespace ComputeSharp.Shaders
internal static class ShaderRunner
{
/// <summary>
/// A thread-safe map of reusable GPU buffers for captured locals
/// A thread-safe map of reusable GPU buffers for captured locals.
/// </summary>
[ThreadStatic]
private static ConditionalWeakTable<GraphicsDevice, ConstantBuffer<Int4>>? variablesBuffers;
/// <summary>
/// Gets the reusable <see cref="ConstantBuffer{T}"/> instance for a shader invocation
/// Gets the reusable <see cref="ConstantBuffer{T}"/> instance for a shader invocation.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <returns>The reusable <see cref="ConstantBuffer{T}"/> instance to populate</returns>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <returns>The reusable <see cref="ConstantBuffer{T}"/> instance to populate.</returns>
[Pure]
public static ConstantBuffer<Int4> GetVariablesBuffer(GraphicsDevice device)
{
var map = variablesBuffers ??= new ConditionalWeakTable<GraphicsDevice, ConstantBuffer<Int4>>();
ConditionalWeakTable<GraphicsDevice, ConstantBuffer<Int4>> map = variablesBuffers ??= new();
return map.GetValue(device, gpu => new ConstantBuffer<Int4>(gpu, 4096));
}
}
/// <summary>
/// A <see langword="class"/> responsible for performing all the necessary operations to compile and run a compute shader
/// A <see langword="class"/> responsible for performing all the necessary operations to compile and run a compute shader.
/// </summary>
/// <typeparam name="T">The type of compute shader to run</typeparam>
/// <typeparam name="T">The type of compute shader to run.</typeparam>
internal static class ShaderRunner<T>
where T : struct, IComputeShader
{
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// The mapping used to cache and reuse compiled shaders.
/// </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>
/// <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>
private static readonly Dictionary<ShaderKey, CachedShader<T>> ShadersCache = new();
/// <summary>
/// Compiles and 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>
/// <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 Run(GraphicsDevice device, int x, int y, int z, in T shader)
{
// Calculate the optimized thread num values
int threadsX, threadsY = 1, threadsZ = 1;
if (y == 1 && z == 1) threadsX = device.WavefrontSize;
if (y == 1 && z == 1) threadsX = (int)device.WavefrontSize;
else if (z == 1) threadsX = threadsY = 8;
else threadsX = threadsY = threadsZ = 4;
@@ -67,21 +73,16 @@ namespace ComputeSharp.Shaders
}
/// <summary>
/// The mapping used to cache and reuse compiled shaders
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
private static readonly Dictionary<ShaderKey, CachedShader<T>> ShadersCache = new Dictionary<ShaderKey, CachedShader<T>>();
/// <summary>
/// Compiles and 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>
/// <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>
/// <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>
/// <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 Run(
GraphicsDevice device,
int x, int y, int z,
@@ -89,9 +90,9 @@ namespace ComputeSharp.Shaders
in T shader)
{
// Create the shader key
ShaderKey key = new ShaderKey(ShaderHashCodeProvider.GetHashCode(shader), threadsX, threadsY, threadsZ);
ShaderKey key = new(ShaderHashCodeProvider.GetHashCode(shader), threadsX, threadsY, threadsZ);
CachedShader<T> shaderData;
PipelineState? pipelineState;
PipelineData? pipelineData;
lock (ShadersCache)
{
@@ -105,21 +106,23 @@ namespace ComputeSharp.Shaders
}
// Create the reusable pipeline state
if (!shaderData.CachedPipelines.TryGetValue(device, out pipelineState))
if (!shaderData.CachedPipelines.TryGetValue(device, out pipelineData))
{
CreatePipelineState(device, shaderData, out pipelineState);
CreatePipelineData(device, shaderData, out pipelineData);
}
}
// Create the commands list and set the pipeline state
using CommandList commandList = new CommandList(device, CommandListType.Compute);
commandList.SetPipelineState(pipelineState);
using CommandList commandList = new(device, D3D12_COMMAND_LIST_TYPE_COMPUTE);
commandList.SetPipelineData(pipelineData);
// Extract the dispatch data for the shader invocation
using DispatchData dispatchData = shaderData.Loader.GetDispatchData(shader, x, y, z);
// Load the captured buffers
Span<GraphicsResource> resources = dispatchData.Resources;
ReadOnlySpan<D3D12_GPU_DESCRIPTOR_HANDLE> resources = dispatchData.Resources;
for (int i = 0; i < resources.Length; i++)
{
commandList.SetComputeRootDescriptorTable(i + 1, resources[i]);
@@ -127,8 +130,10 @@ namespace ComputeSharp.Shaders
// Initialize the loop targets and the captured values
ConstantBuffer<Int4> variablesBuffer = ShaderRunner.GetVariablesBuffer(device);
variablesBuffer.SetData(dispatchData.Variables);
commandList.SetComputeRootDescriptorTable(0, variablesBuffer);
commandList.SetComputeRootDescriptorTable(0, variablesBuffer.D3D12GpuDescriptorHandle);
// Calculate the dispatch values
int
@@ -142,13 +147,13 @@ namespace ComputeSharp.Shaders
}
/// <summary>
/// Loads a shader with the specified parameters
/// Loads a shader with the specified parameters.
/// </summary>
/// <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>
/// <param name="shaderData">The <see cref="CachedShader{T}"/> instance to return with the cached shader data</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>
/// <param name="shaderData">The <see cref="CachedShader{T}"/> instance to return with the cached shader data.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private static void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader<T> shaderData)
{
@@ -158,41 +163,42 @@ namespace ComputeSharp.Shaders
// Render the loaded shader
string shaderSource = ShaderRenderer.Instance.Render(new ShaderInfo
{
BuffersList = shaderLoader.BuffersList,
FieldsList = shaderLoader.FieldsList,
BuffersList = shaderLoader.HslsBuffersInfo,
FieldsList = shaderLoader.FieldsInfo,
NumThreadsX = threadsX,
NumThreadsY = threadsY,
NumThreadsZ = threadsZ,
ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName,
ShaderBody = shaderLoader.MethodBody,
FunctionsList = shaderLoader.FunctionsList,
LocalFunctionsList = shaderLoader.LocalFunctionsList
FunctionsList = shaderLoader.FunctionsInfo,
LocalFunctionsList = shaderLoader.LocalFunctionsInfo
});
// Compile the loaded shader to HLSL bytecode
ShaderBytecode shaderBytecode = ShaderCompiler.CompileShader(shaderSource);
IDxcBlobObject shaderBytecode = new(ShaderCompiler.CompileShader(shaderSource));
// Get the cached shader data
shaderData = new CachedShader<T>(shaderLoader, shaderBytecode);
}
/// <summary>
/// Creates and caches a <see cref="PipelineState"/> instance for a given shader
/// Creates and caches a <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="shaderData">The <see cref="CachedShader{T}"/> instance with the data on the loaded shader</param>
/// <param name="pipelineState">The resulting <see cref="PipelineState"/> instance to use to run the shader</param>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="shaderData">The <see cref="CachedShader{T}"/> instance with the data on the loaded shader.</param>
/// <param name="pipelineData">The resulting <see cref="PipelineData"/> instance to use to run the shader.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private static void CreatePipelineState(GraphicsDevice device, in CachedShader<T> shaderData, out PipelineState pipelineState)
private static unsafe void CreatePipelineData(GraphicsDevice device, in CachedShader<T> shaderData, out PipelineData pipelineData)
{
// Create the root signature for the pipeline and get the pipeline state
RootSignatureDescription1 rootSignatureDescription = new RootSignatureDescription1(RootSignatureFlags.None, shaderData.Loader.RootParameters);
VersionedRootSignatureDescription versionedRootSignatureDescription = new VersionedRootSignatureDescription(rootSignatureDescription);
ID3D12RootSignature rootSignature = device.CreateRootSignature(versionedRootSignatureDescription);
pipelineState = new PipelineState(device, rootSignature, shaderData.Bytecode);
using ComPtr<ID3D12RootSignature> d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12DescriptorRanges1);
// Cache the pipeline state for the target device
shaderData.CachedPipelines.Add(device, pipelineState);
D3D12_SHADER_BYTECODE d3D12ShaderBytecode = new((ID3DBlob*)shaderData.Bytecode.DxcBlob);
using ComPtr<ID3D12PipelineState> d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), d3D12ShaderBytecode);
pipelineData = new PipelineData(d3D12RootSignature.Move(), d3D12PipelineState.Move());
shaderData.CachedPipelines.Add(device, pipelineData);
}
}
}
+5 -5
ファイルの表示
@@ -9,13 +9,13 @@ namespace ComputeSharp.Shaders.Translation.Models
/// A <see langword="struct"/> that contains info on a cached shader.
/// </summary>
/// <typeparam name="T">The type of compute shader in use.</typeparam>
internal readonly struct CachedShader2<T>
internal readonly struct CachedShader<T>
where T : struct, IComputeShader
{
/// <summary>
/// The <see cref="ShaderLoader2{T}"/> instance with the shader metadata.
/// The <see cref="ShaderLoader{T}"/> instance with the shader metadata.
/// </summary>
public readonly ShaderLoader2<T> Loader;
public readonly ShaderLoader<T> Loader;
/// <summary>
/// The compiled shader bytecode.
@@ -25,14 +25,14 @@ namespace ComputeSharp.Shaders.Translation.Models
/// <summary>
/// The map of cached <see cref="PipelineData"/> instances for each GPU in use.
/// </summary>
public readonly ConditionalWeakTable<GraphicsDevice2, PipelineData> CachedPipelines;
public readonly ConditionalWeakTable<GraphicsDevice, PipelineData> CachedPipelines;
/// <summary>
/// Creates a new <see cref="CachedShader{T}"/> instance with the specified parameters.
/// </summary>
/// <param name="loader">The <see cref="ShaderLoader{T}"/> instance with the shader metadata.</param>
/// <param name="bytecode">The compiled shader bytecode.</param>
public CachedShader2(ShaderLoader2<T> loader, IDxcBlobObject bytecode)
public CachedShader(ShaderLoader<T> loader, IDxcBlobObject bytecode)
{
Loader = loader;
Bytecode = bytecode;
-42
ファイルの表示
@@ -1,42 +0,0 @@
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Commands;
using Vortice.Direct3D12;
namespace ComputeSharp.Shaders.Translation.Models
{
/// <summary>
/// A <see langword="struct"/> that contains info on a cached shader
/// </summary>
/// <typeparam name="T">The type of compute shader in use</typeparam>
internal readonly struct CachedShader<T>
where T : struct, IComputeShader
{
/// <summary>
/// The <see cref="ShaderLoader{T}"/> instance with the shader metadata
/// </summary>
public readonly ShaderLoader<T> Loader;
/// <summary>
/// The compiled shader bytecode
/// </summary>
public readonly ShaderBytecode Bytecode;
/// <summary>
/// The map of cached <see cref="PipelineState"/> instances for each GPU in use.
/// </summary>
public readonly ConditionalWeakTable<GraphicsDevice, PipelineState> CachedPipelines;
/// <summary>
/// Creates a new <see cref="CachedShader{T}"/> instance with the specified parameters
/// </summary>
/// <param name="loader">The <see cref="ShaderLoader{T}"/> instance with the shader metadata</param>
/// <param name="bytecode">The compiled shader bytecode</param>
public CachedShader(ShaderLoader<T> loader, ShaderBytecode bytecode)
{
Loader = loader;
Bytecode = bytecode;
CachedPipelines = new ConditionalWeakTable<GraphicsDevice, PipelineState>();
}
}
}
+43 -37
ファイルの表示
@@ -3,80 +3,86 @@ using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Graphics.Buffers.Abstract;
using TerraFX.Interop;
namespace ComputeSharp.Shaders.Translation.Models
{
/// <summary>
/// A <see langword="struct"/> that contains all the captured data to dispatch a shader
/// A <see langword="struct"/> that contains all the captured data to dispatch a shader.
/// </summary>
internal readonly ref struct DispatchData
{
/// <summary>
/// The <see cref="GraphicsResource"/> array with the captured buffers
/// The <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> array with the captured buffers.
/// </summary>
private readonly GraphicsResource[] ResourcesArray;
private readonly D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray;
/// <summary>
/// The number of <see cref="GraphicsResource"/> instances in <see cref="ResourcesArray"/>
/// The number of <see cref="GraphicsResource"/> instances in <see cref="resourcesArray"/>.
/// </summary>
private readonly int ResourcesCount;
private readonly int resourcesCount;
/// <summary>
/// The <see cref="byte"/> array with all the captured variables, with proper padding
/// The <see cref="byte"/> array with all the captured variables, with proper padding.
/// </summary>
private readonly byte[] VariablesArray;
private readonly byte[] variablesArray;
/// <summary>
/// The actual size in bytes to use from <see cref="VariablesArray"/>
/// The actual size in bytes to use from <see cref="variablesArray"/>.
/// </summary>
private readonly int VariablesByteSize;
private readonly int variablesByteSize;
/// <summary>
/// Creates a new <see cref="DispatchData"/> instance with the specified parameters
/// Creates a new <see cref="DispatchData"/> instance with the specified parameters.
/// </summary>
/// <param name="resourcesArray">The <see cref="GraphicsResource"/> array with the captured buffers</param>
/// <param name="resourcesCount">The number of <see cref="GraphicsResource"/> 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(GraphicsResource[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize)
/// <param name="resourcesArray">The <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> 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(D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize)
{
ResourcesArray = resourcesArray;
VariablesArray = variablesArray;
ResourcesCount = resourcesCount;
VariablesByteSize = variablesByteSize;
this.resourcesArray = resourcesArray;
this.variablesArray = variablesArray;
this.resourcesCount = resourcesCount;
this.variablesByteSize = variablesByteSize;
}
/// <summary>
/// Gets a <see cref="Span{T}"/> with all the captured buffers
/// Gets a <see cref="ReadOnlySpan{T}"/> with all the captured buffers.
/// </summary>
public Span<GraphicsResource> Resources
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ResourcesArray.AsSpan(0, ResourcesCount);
}
/// <summary>
/// Gets a <see cref="Span{T}"/> with the padded data representing all the captured variables
/// </summary>
public Span<Int4> Variables
public ReadOnlySpan<D3D12_GPU_DESCRIPTOR_HANDLE> Resources
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ref Int4 r = ref Unsafe.As<byte, Int4>(ref VariablesArray[0]);
bool mod = (VariablesByteSize & 15) > 0;
int length = VariablesByteSize / 4 + Unsafe.As<bool, byte>(ref mod);
return MemoryMarshal.CreateSpan(ref r, length);
ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray);
return MemoryMarshal.CreateReadOnlySpan(ref r0, this.resourcesCount);
}
}
/// <summary>
/// Implements the <see cref="IDisposable.Dispose"/> method and returns the rented buffers
/// Gets a <see cref="ReadOnlySpan{T}"/> with the padded data representing all the captured variables.
/// </summary>
public ReadOnlySpan<Int4> Variables
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ref byte r0 = ref MemoryMarshal.GetArrayDataReference(this.variablesArray);
ref Int4 r1 = ref Unsafe.As<byte, Int4>(ref r0);
bool mod = (this.variablesByteSize & 15) > 0;
int length = variablesByteSize / 4 + Unsafe.As<bool, byte>(ref mod);
return MemoryMarshal.CreateReadOnlySpan(ref r1, length);
}
}
/// <inheritdoc cref="IDisposable.Dispose"/>
public void Dispose()
{
ArrayPool<GraphicsResource>.Shared.Return(ResourcesArray, true);
ArrayPool<byte>.Shared.Return(VariablesArray);
ArrayPool<D3D12_GPU_DESCRIPTOR_HANDLE>.Shared.Return(this.resourcesArray);
ArrayPool<byte>.Shared.Return(this.variablesArray);
}
}
}
-88
ファイルの表示
@@ -1,88 +0,0 @@
using System;
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Graphics.Buffers.Abstract;
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 DispatchData2
{
/// <summary>
/// The <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> array with the captured buffers.
/// </summary>
private readonly D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray;
/// <summary>
/// The number of <see cref="GraphicsResource"/> instances 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="D3D12_GPU_DESCRIPTOR_HANDLE"/> 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 DispatchData2(D3D12_GPU_DESCRIPTOR_HANDLE[] 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 D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray);
return MemoryMarshal.CreateReadOnlySpan(ref r0, this.resourcesCount);
}
}
/// <summary>
/// Gets a <see cref="ReadOnlySpan{T}"/> with the padded data representing all the captured variables.
/// </summary>
public ReadOnlySpan<Int4> Variables
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ref byte r0 = ref MemoryMarshal.GetArrayDataReference(this.variablesArray);
ref Int4 r1 = ref Unsafe.As<byte, Int4>(ref r0);
bool mod = (this.variablesByteSize & 15) > 0;
int length = variablesByteSize / 4 + Unsafe.As<bool, byte>(ref mod);
return MemoryMarshal.CreateReadOnlySpan(ref r1, length);
}
}
/// <inheritdoc cref="IDisposable.Dispose"/>
public void Dispose()
{
ArrayPool<D3D12_GPU_DESCRIPTOR_HANDLE>.Shared.Return(this.resourcesArray);
ArrayPool<byte>.Shared.Return(this.variablesArray);
}
}
}
+120 -22
ファイルの表示
@@ -1,42 +1,140 @@
using System.Diagnostics.Contracts;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.Exceptions;
using Vortice.Direct3D12;
using Vortice.Dxc;
using ComputeSharp.Graphics.Helpers;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> that uses the <see cref="DxcCompiler"/> APIs to compile compute shaders
/// A <see langword="class"/> that uses the DXC APIs to compile compute shaders.
/// </summary>
internal static class ShaderCompiler
internal static unsafe class ShaderCompiler
{
/// <summary>
/// The <see cref="IDxcLibrary"/> instance to use to create the bytecode for HLSL sources
/// The <see cref="IDxcCompiler"/> instance to use to create the bytecode for HLSL sources.
/// </summary>
private static readonly IDxcLibrary Library = Dxc.CreateDxcLibrary();
private static readonly ComPtr<IDxcCompiler> DxcCompiler;
/// <summary>
/// Compiles a new HLSL shader from the input source code
/// The <see cref="IDxcLibrary"/> instance to use to work with <see cref="DxcCompiler"/>.
/// </summary>
/// <param name="source">The HLSL source code to compile</param>
/// <returns>The bytecode for the compiled shader</returns>
[Pure]
public static ShaderBytecode CompileShader(string source)
private static readonly ComPtr<IDxcLibrary> DxcLibrary;
/// <summary>
/// The <see cref="IDxcIncludeHandler"/> instance used to compile shaders with <see cref="DxcCompiler"/>.
/// </summary>
private static readonly ComPtr<IDxcIncludeHandler> DxcIncludeHandler;
/// <summary>
/// Initializes <see cref="DxcCompiler"/>, <see cref="DxcLibrary"/> and <see cref="DxcIncludeHandler"/>
/// </summary>
static ShaderCompiler()
{
var result = DxcCompiler.Compile(DxcShaderStage.ComputeShader, source, "CSMain", string.Empty, new DxcCompilerOptions { ShaderModel = DxcShaderModel.Model6_1 });
using ComPtr<IDxcCompiler> dxcCompiler = default;
using ComPtr<IDxcLibrary> dxcLibrary = default;
using ComPtr<IDxcIncludeHandler> dxcIncludeHandler = default;
// Get the compiled bytecode in case of success
if (result.GetStatus() == 0)
Guid dxcCompilerCLGuid = FX.CLSID_DxcCompiler;
Guid dxcCompilerGuid = FX.IID_IDxcCompiler;
Guid dxcLibraryCLGuid = FX.CLSID_DxcLibrary;
Guid dxcLibraryGuid = FX.IID_IDxcLibrary;
FX.DxcCreateInstance(&dxcCompilerCLGuid, &dxcCompilerGuid, dxcCompiler.GetVoidAddressOf()).Assert();
FX.DxcCreateInstance(&dxcLibraryCLGuid, &dxcLibraryGuid, dxcLibrary.GetVoidAddressOf()).Assert();
dxcLibrary.Get()->CreateIncludeHandler(dxcIncludeHandler.GetAddressOf()).Assert();
DxcCompiler = dxcCompiler;
DxcLibrary = dxcLibrary;
DxcIncludeHandler = dxcIncludeHandler;
}
/// <summary>
/// Compiles a new HLSL shader from the input source code.
/// </summary>
/// <param name="source">The HLSL source code to compile.</param>
/// <returns>The bytecode for the compiled shader.</returns>
[Pure]
public static ComPtr<IDxcBlob> CompileShader(ReadOnlySpan<char> source)
{
using ComPtr<IDxcBlobEncoding> dxcBlobEncoding = default;
using ComPtr<IDxcOperationResult> dxcOperationResult = default;
using ComPtr<IDxcBlob> dxcBlobBytecode = default;
// Get the encoded blob from the source code
fixed (char* p = source)
{
IDxcBlob blob = result.GetResult();
byte[] bytecode = Dxc.GetBytesFromBlob(blob);
return bytecode;
DxcLibrary.Get()->CreateBlobWithEncodingOnHeapCopy(
p,
(uint)source.Length * 2,
1200,
dxcBlobEncoding.GetAddressOf()).Assert();
}
// Compile error
string resultText = Dxc.GetStringFromBlob(Library, result.GetErrors());
throw new HlslCompilationException(resultText);
// Try to compile the new compute shader
fixed (char* entryPoint = "CSMain")
fixed (char* shaderProfile = "cs_6_1")
fixed (char* optimization = "-O3")
{
char nullTerminator = '\0';
DxcCompiler.Get()->Compile(
dxcBlobEncoding.Upcast<IDxcBlobEncoding, IDxcBlob>().Get(),
(ushort*)&nullTerminator,
(ushort*)entryPoint,
(ushort*)shaderProfile,
(ushort**)&optimization,
1,
null,
0,
DxcIncludeHandler.Get(),
dxcOperationResult.GetAddressOf()).Assert();
}
int status;
dxcOperationResult.Get()->GetStatus(&status).Assert();
// The compilation was successful, so we can extract the shader bytecode
if (status == 0)
{
dxcOperationResult.Get()->GetResult(dxcBlobBytecode.GetAddressOf()).Assert();
return dxcBlobBytecode.Move();
}
return ThrowHslsCompilationException(dxcOperationResult);
}
/// <summary>
/// Throws an exception when a shader compilation fails.
/// </summary>
/// <param name="dxcOperationResult">The input (faulting) operation.</param>
/// <returns>This method always throws and never actually returs.</returns>
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
private static ComPtr<IDxcBlob> ThrowHslsCompilationException(ComPtr<IDxcOperationResult> dxcOperationResult)
{
using ComPtr<IDxcBlobEncoding> dxcBlobEncodingError = default;
dxcOperationResult.Get()->GetErrorBuffer(dxcBlobEncodingError.GetAddressOf()).Assert();
using ComPtr<IDxcBlobUtf16> dxcBlobUtf16Error = default;
DxcLibrary.Get()->GetBlobAsUtf16(
dxcBlobEncodingError.Upcast<IDxcBlobEncoding, IDxcBlob>().Get(),
dxcBlobUtf16Error.Upcast<IDxcBlobUtf16, IDxcBlobEncoding>().GetAddressOf()).Assert();
string message = new string(
(char*)dxcBlobUtf16Error.Get()->GetStringPointer(),
0,
checked((int)dxcBlobUtf16Error.Get()->GetStringLength()));
throw new HlslCompilationException(message);
}
}
}
-140
ファイルの表示
@@ -1,140 +0,0 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.Exceptions;
using ComputeSharp.Graphics.Helpers;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> that uses the DXC APIs to compile compute shaders.
/// </summary>
internal static unsafe class ShaderCompiler2
{
/// <summary>
/// The <see cref="IDxcCompiler"/> instance to use to create the bytecode for HLSL sources.
/// </summary>
private static readonly ComPtr<IDxcCompiler> DxcCompiler;
/// <summary>
/// The <see cref="IDxcLibrary"/> instance to use to work with <see cref="DxcCompiler"/>.
/// </summary>
private static readonly ComPtr<IDxcLibrary> DxcLibrary;
/// <summary>
/// The <see cref="IDxcIncludeHandler"/> instance used to compile shaders with <see cref="DxcCompiler"/>.
/// </summary>
private static readonly ComPtr<IDxcIncludeHandler> DxcIncludeHandler;
/// <summary>
/// Initializes <see cref="DxcCompiler"/>, <see cref="DxcLibrary"/> and <see cref="DxcIncludeHandler"/>
/// </summary>
static ShaderCompiler2()
{
using ComPtr<IDxcCompiler> dxcCompiler = default;
using ComPtr<IDxcLibrary> dxcLibrary = default;
using ComPtr<IDxcIncludeHandler> dxcIncludeHandler = default;
Guid dxcCompilerCLGuid = FX.CLSID_DxcCompiler;
Guid dxcCompilerGuid = FX.IID_IDxcCompiler;
Guid dxcLibraryCLGuid = FX.CLSID_DxcLibrary;
Guid dxcLibraryGuid = FX.IID_IDxcLibrary;
FX.DxcCreateInstance(&dxcCompilerCLGuid, &dxcCompilerGuid, dxcCompiler.GetVoidAddressOf()).Assert();
FX.DxcCreateInstance(&dxcLibraryCLGuid, &dxcLibraryGuid, dxcLibrary.GetVoidAddressOf()).Assert();
dxcLibrary.Get()->CreateIncludeHandler(dxcIncludeHandler.GetAddressOf()).Assert();
DxcCompiler = dxcCompiler;
DxcLibrary = dxcLibrary;
DxcIncludeHandler = dxcIncludeHandler;
}
/// <summary>
/// Compiles a new HLSL shader from the input source code.
/// </summary>
/// <param name="source">The HLSL source code to compile.</param>
/// <returns>The bytecode for the compiled shader.</returns>
[Pure]
public static ComPtr<IDxcBlob> CompileShader(ReadOnlySpan<char> source)
{
using ComPtr<IDxcBlobEncoding> dxcBlobEncoding = default;
using ComPtr<IDxcOperationResult> dxcOperationResult = default;
using ComPtr<IDxcBlob> dxcBlobBytecode = default;
// Get the encoded blob from the source code
fixed (char* p = source)
{
DxcLibrary.Get()->CreateBlobWithEncodingOnHeapCopy(
p,
(uint)source.Length * 2,
1200,
dxcBlobEncoding.GetAddressOf()).Assert();
}
// Try to compile the new compute shader
fixed (char* entryPoint = "CSMain")
fixed (char* shaderProfile = "cs_6_1")
fixed (char* optimization = "-O3")
{
char nullTerminator = '\0';
DxcCompiler.Get()->Compile(
dxcBlobEncoding.Upcast<IDxcBlobEncoding, IDxcBlob>().Get(),
(ushort*)&nullTerminator,
(ushort*)entryPoint,
(ushort*)shaderProfile,
(ushort**)&optimization,
1,
null,
0,
DxcIncludeHandler.Get(),
dxcOperationResult.GetAddressOf()).Assert();
}
int status;
dxcOperationResult.Get()->GetStatus(&status).Assert();
// The compilation was successful, so we can extract the shader bytecode
if (status == 0)
{
dxcOperationResult.Get()->GetResult(dxcBlobBytecode.GetAddressOf()).Assert();
return dxcBlobBytecode.Move();
}
return ThrowHslsCompilationException(dxcOperationResult);
}
/// <summary>
/// Throws an exception when a shader compilation fails.
/// </summary>
/// <param name="dxcOperationResult">The input (faulting) operation.</param>
/// <returns>This method always throws and never actually returs.</returns>
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
private static ComPtr<IDxcBlob> ThrowHslsCompilationException(ComPtr<IDxcOperationResult> dxcOperationResult)
{
using ComPtr<IDxcBlobEncoding> dxcBlobEncodingError = default;
dxcOperationResult.Get()->GetErrorBuffer(dxcBlobEncodingError.GetAddressOf()).Assert();
using ComPtr<IDxcBlobUtf16> dxcBlobUtf16Error = default;
DxcLibrary.Get()->GetBlobAsUtf16(
dxcBlobEncodingError.Upcast<IDxcBlobEncoding, IDxcBlob>().Get(),
dxcBlobUtf16Error.Upcast<IDxcBlobUtf16, IDxcBlobEncoding>().GetAddressOf()).Assert();
string message = new string(
(char*)dxcBlobUtf16Error.Get()->GetStringPointer(),
0,
checked((int)dxcBlobUtf16Error.Get()->GetStringLength()));
throw new HlslCompilationException(message);
}
}
}
-144
ファイルの表示
@@ -1,144 +0,0 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Graphics.Buffers;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Translation.Models;
using TerraFX.Interop;
namespace ComputeSharp.Shaders.Translation
{
/// <inheritdoc cref="ShaderLoader2{T}"/>
internal sealed partial class ShaderLoader2<T>
{
/// <summary>
/// A <see langword="delegate"/> that loads all the captured members from a shader instance.
/// </summary>
/// <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.</param>
/// <param name="r1">A reference to the buffer to use to store all the captured value types.</param>
private delegate void DispatchDataLoader(in T shader, ref D3D12_GPU_DESCRIPTOR_HANDLE r0, ref byte r1);
/// <summary>
/// The number of captured graphics resources (buffers).
/// </summary>
private int totalResourceCount;
/// <summary>
/// The size in bytes of the buffer with the captured variables.
/// </summary>
/// <remarks>Initially set to 3 <see cref="int"/> values for X, Y and Z threads counts.</remarks>
private int totalVariablesByteSize = 3 * sizeof(int);
/// <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="ReadableMember"/> instances mapping the captured variables in the current shader.
/// </summary>
private readonly List<ReadableMember> capturedMembers = new();
/// <summary>
/// Gets a new <see cref="DispatchData2"/> instance with all the captured data for the current shader instance.
/// </summary>
/// <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 DispatchData2 GetDispatchData(in T shader, int x, int y, int z)
{
// Resources and variables buffers
D3D12_GPU_DESCRIPTOR_HANDLE[] resources = ArrayPool<D3D12_GPU_DESCRIPTOR_HANDLE>.Shared.Rent(this.totalResourceCount);
byte[] variables = ArrayPool<byte>.Shared.Rent(this.totalVariablesByteSize);
ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(resources);
ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables);
// Set the x, y and z counters
Unsafe.As<byte, int>(ref r1) = x;
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 1) = y;
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 2) = z;
// Invoke the dynamic method to extract the captured data
this.dispatchDataLoader!(shader, ref r0, ref r1);
return new DispatchData2(resources, this.totalResourceCount, variables, this.totalVariablesByteSize);
}
/// <summary>
/// Builds a new <see cref="DispatchDataLoader"/> instance that loads the dispatch data for the current shader type.
/// </summary>
private void BuildDispatchDataLoader()
{
this.dispatchDataLoader = DynamicMethod<DispatchDataLoader>.New(il =>
{
foreach (ReadableMember member in this.capturedMembers)
{
if (HlslKnownTypes.IsKnownBufferType(member.MemberType))
{
// Load the offset address into the resource buffers
il.Emit(OpCodes.Ldarg_1);
if (totalResourceCount > 0)
{
il.EmitAddOffset<D3D12_GPU_DESCRIPTOR_HANDLE>(this.totalResourceCount);
}
il.Emit(OpCodes.Ldarg_0);
il.EmitReadMember(member);
// Access Buffer<T>.D3D12GpuDescriptorHandle
FieldInfo gpuDescriptorInfo = member.MemberType.GetField(
nameof(Buffer2<byte>.D3D12GpuDescriptorHandle),
BindingFlags.NonPublic | BindingFlags.Instance)!;
il.EmitReadMember(gpuDescriptorInfo);
il.EmitStoreToAddress(member.MemberType);
this.totalResourceCount++;
}
else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) ||
HlslKnownTypes.IsKnownVectorType(member.MemberType))
{
// Calculate the right offset with 16-bytes padding (HLSL constant buffer)
int size = member.MemberType == typeof(bool)
? sizeof(uint)
: Marshal.SizeOf(member.MemberType); // bool is 4 bytes in HLSL
if (this.totalVariablesByteSize % 16 > 16 - size)
{
this.totalVariablesByteSize += 16 - this.totalVariablesByteSize % 16;
}
// Load the target address into the variables buffer
il.Emit(OpCodes.Ldarg_2);
il.EmitAddOffset(totalVariablesByteSize);
this.totalVariablesByteSize += size;
}
else throw new InvalidOperationException($"Invalid captured member of type {member.MemberType}");
// Load the reference to the input delegate if the member is not static
if (!member.IsStatic)
{
il.Emit(OpCodes.Ldarg_0);
}
// Read the current member and store it to the target address
il.EmitReadMember(member);
il.EmitStoreToAddress(member.MemberType);
}
il.Emit(OpCodes.Ret);
});
}
}
}
-355
ファイルの表示
@@ -1,355 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Renderer.Models.Fields;
using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
using ComputeSharp.Shaders.Renderer.Models.Functions;
using ComputeSharp.Shaders.Translation.Enums;
using ComputeSharp.Shaders.Translation.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_DESCRIPTOR_RANGE_TYPE;
using ParameterInfo = ComputeSharp.Shaders.Renderer.Models.Functions.ParameterInfo;
#pragma warning disable CS8618 // Non-nullable field is uninitialized
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> responsible for loading and processing shaders of a given type.
/// </summary>
/// <typeparam name="T">The type of compute shader currently in use.</typeparam>
internal sealed partial class ShaderLoader2<T>
where T : struct, IComputeShader
{
/// <summary>
/// The number of constant buffers to define in the shader.
/// </summary>
private uint constantBuffersCount;
/// <summary>
/// The number of readonly buffers to define in the shader.
/// </summary>
private uint readOnlyBuffersCount;
/// <summary>
/// The number of read write buffers to define in the shader.
/// </summary>
private uint readWriteBuffersCount;
/// <summary>
/// The <see cref="List{T}"/> of <see cref="D3D12_DESCRIPTOR_RANGE1"/> items that are required to load the captured values.
/// </summary>
private readonly List<D3D12_DESCRIPTOR_RANGE1> d3D12DescriptorRanges1 = new();
/// <summary>
/// The <see cref="List{T}"/> with the <see cref="HlslBufferInfo"/> items for the shader fields.
/// </summary>
private readonly List<HlslBufferInfo> hlslBuffersInfo = new();
/// <summary>
/// The <see cref="List{T}"/> with the <see cref="CapturedFieldInfo"/> items for the shader fields.
/// </summary>
private readonly List<CapturedFieldInfo> fieldsInfo = new();
/// <summary>
/// The <see cref="List{T}"/> with the <see cref="FunctionInfo"/> items for the shader functions.
/// </summary>
private readonly List<FunctionInfo> functionsInfo = new();
/// <summary>
/// The <see cref="List{T}"/> with the <see cref="FunctionInfo"/> items for the shader local functions.
/// </summary>
private readonly List<LocalFunctionInfo> localFunctionsInfo = new();
/// <summary>
/// Creates a new <see cref="ShaderLoader2{T}"/> instance.
/// </summary>
private ShaderLoader2()
{
}
/// <summary>
/// Gets a <see cref="Span{T}"/> with the loaded <see cref="D3D12_DESCRIPTOR_RANGE1"/> items for the shader.
/// </summary>
public ReadOnlySpan<D3D12_DESCRIPTOR_RANGE1> D3D12DescriptorRanges1
{
get => CollectionsMarshal.AsSpan(this.d3D12DescriptorRanges1);
}
/// <summary>
/// Gets the name of the <see cref="ThreadIds"/> variable used as input for the shader method.
/// </summary>
public string ThreadsIdsVariableName { get; private set; }
/// <summary>
/// Gets the generated source code for the method in the current shader.
/// </summary>
public string MethodBody { get; private set; }
/// <summary>
/// Gets the collection of <see cref="HlslBufferInfo"/> items for the shader fields.
/// </summary>
public IReadOnlyList<HlslBufferInfo> HslsBuffersInfo => this.hlslBuffersInfo;
/// <summary>
/// Gets the collection of <see cref="CapturedFieldInfo"/> items for the shader fields.
/// </summary>
public IReadOnlyList<CapturedFieldInfo> FieldsInfo => this.fieldsInfo;
/// <summary>
/// Gets the collection of <see cref="FunctionInfo"/> items for the shader.
/// </summary>
public IReadOnlyList<FunctionInfo> FunctionsInfo => this.functionsInfo;
/// <summary>
/// Gets the collection of <see cref="LocalFunctionInfo"/> items for the shader.
/// </summary>
public IReadOnlyList<LocalFunctionInfo> LocalFunctionsInfo => this.localFunctionsInfo;
/// <summary>
/// Loads and processes an input<typeparamref name="T"/> shadeer
/// </summary>
/// <param name="shader">The <typeparamref name="T"/> instance to use to build the shader</param>
/// <returns>A new <see cref="ShaderLoader"/> instance representing the input shader</returns>
[Pure]
public static ShaderLoader2<T> Load(in T shader)
{
ShaderLoader2<T> @this = new ShaderLoader2<T>();
// Reading members through reflection requires an object parameter,
// so here we're just boxing the input shader once to avoid allocating
// it multiple times in the managed heap while processing the shader.
object box = shader;
@this.LoadFieldsInfo(box);
@this.LoadMethodSource(box);
@this.BuildDispatchDataLoader();
return @this;
}
/// <summary>
/// Loads the fields info for the current shader being loaded
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
private void LoadFieldsInfo(object shader)
{
IReadOnlyList<FieldInfo> shaderFields = typeof(T).GetFields(
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic).ToArray();
if (shaderFields.Count == 0) throw new InvalidOperationException("Empty shader body");
// Descriptor for the buffer for captured scalar/vector variables
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_CBV,
1,
this.constantBuffersCount++);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
// Inspect the captured fields
foreach (FieldInfo fieldInfo in shaderFields)
{
LoadFieldInfo(shader, fieldInfo);
}
}
/// <summary>
/// Loads a specified <see cref="ReadableMember"/> and adds it to the shader model
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
/// <param name="memberInfo">The target <see cref="ReadableMember"/> to load</param>
/// <param name="name">The optional explicit name to use for the field</param>
private void LoadFieldInfo(object shader, ReadableMember memberInfo, string? name = null)
{
Type fieldType = memberInfo.MemberType;
string fieldName = HlslKnownKeywords.GetMappedName(name ?? memberInfo.Name);
// Constant buffer
if (HlslKnownTypes.IsConstantBufferType(fieldType))
{
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_CBV,
1,
this.constantBuffersCount++);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]);
this.hlslBuffersInfo.Add(new ConstantBufferFieldInfo(fieldType, typeName, fieldName, (int)this.constantBuffersCount));
}
else if (HlslKnownTypes.IsReadOnlyBufferType(fieldType))
{
// Root parameter for a readonly buffer
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
1,
this.readOnlyBuffersCount++);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
this.hlslBuffersInfo.Add(new ReadOnlyBufferFieldInfo(fieldType, typeName, fieldName, (int)this.readOnlyBuffersCount));
}
else if (HlslKnownTypes.IsReadWriteBufferType(fieldType))
{
// Root parameter for a read write buffer
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_UAV,
1,
this.readWriteBuffersCount++);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
this.hlslBuffersInfo.Add(new ReadWriteBufferFieldInfo(fieldType, typeName, fieldName, (int)this.readWriteBuffersCount));
}
else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType))
{
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
this.fieldsInfo.Add(new CapturedFieldInfo(fieldType, typeName, fieldName));
}
else if (fieldType.IsDelegate() &&
memberInfo.GetValue(shader) is Delegate func &&
(func.Method.IsStatic || func.Method.DeclaringType!.IsStatelessDelegateContainer()) &&
(HlslKnownTypes.IsKnownScalarType(func.Method.ReturnType) || HlslKnownTypes.IsKnownVectorType(func.Method.ReturnType)) &&
fieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) ||
HlslKnownTypes.IsKnownVectorType(type)))
{
// Captured static delegates with a return type
LoadStaticMethodSource(shader, fieldName, func.Method);
}
else throw new ArgumentException($"Invalid captured variable of type {fieldType} with name \"{memberInfo.Name}\"");
}
/// <summary>
/// Loads the entry method for the current shader being loaded
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
private void LoadMethodSource(object shader)
{
// Decompile the shader method
MethodInfo methodInfo = typeof(T).GetMethod(nameof(IComputeShader.Execute))!;
MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Execute, out MethodDeclarationSyntax root, out SemanticModel semanticModel);
// Rewrite the shader method (eg. to fix the type declarations)
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, typeof(T));
root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root);
// Extract the implicit local functions
var locals = root.DescendantNodes().OfType<LocalFunctionStatementSyntax>().ToArray();
root = root.RemoveNodes(locals, SyntaxRemoveOptions.KeepNoTrivia)!;
foreach (var local in locals)
{
string alignedLocal = local.ToFullString().RemoveLeftPadding().Trim(' ', '\r', '\n');
alignedLocal = Regex.Replace(alignedLocal, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
alignedLocal = HlslKnownKeywords.GetMappedText(alignedLocal);
this.localFunctionsInfo.Add(new LocalFunctionInfo(alignedLocal));
}
// Register the captured static members
foreach (var member in syntaxRewriter.StaticMembers)
{
LoadFieldInfo(shader, member.Value, member.Key);
}
// Register the captured static methods
foreach (var method in syntaxRewriter.StaticMethods)
{
LoadStaticMethodSource(shader, method.Key, method.Value);
}
// Get the thread ids identifier name and shader method body
ThreadsIdsVariableName = root.ParameterList.Parameters.First().Identifier.Text;
MethodBody = root.Body!.ToFullString();
// Additional preprocessing
MethodBody = Regex.Replace(MethodBody, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
MethodBody = MethodBody.TrimEnd('\n', '\r', ' ');
MethodBody = HlslKnownKeywords.GetMappedText(MethodBody);
}
/// <summary>
/// Loads additional static methods used by the shader
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
/// <param name="name">The HLSL name of the new method to load</param>
/// <param name="methodInfo">The <see cref="MethodInfo"/> instance for the method to load</param>
private void LoadStaticMethodSource(object shader, string name, MethodInfo methodInfo)
{
// Decompile the target method
MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Static, out MethodDeclarationSyntax root, out SemanticModel semanticModel);
// Rewrite the method
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, methodInfo.DeclaringType!);
root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root);
// Register the captured static members
foreach (var member in syntaxRewriter.StaticMembers)
{
LoadFieldInfo(shader, member.Value, member.Key);
}
// Register the captured static methods
foreach (var method in syntaxRewriter.StaticMethods)
{
LoadStaticMethodSource(shader, method.Key, method.Value);
}
// Get the function parameters
IReadOnlyList<ParameterInfo> parameters = (
from parameter in root.ParameterList.Parameters.Select((p, i) => (Node: p, Index: i))
let modifiers = parameter.Node.Modifiers
let type = parameter.Node.Type!.ToFullString()
let parameterName = parameter.Node.Identifier.ToFullString()
let last = parameter.Index == root.ParameterList.Parameters.Count - 1
select new ParameterInfo(modifiers, type, parameterName, last)).ToArray();
// Get the function body
string body = root.Body!.ToFullString();
body = Regex.Replace(body, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
body = body.TrimEnd('\n', '\r', ' ');
body = HlslKnownKeywords.GetMappedText(body);
// Get the final function info instance
FunctionInfo functionInfo = new FunctionInfo(
methodInfo.ReturnType,
$"{methodInfo.DeclaringType!.FullName}{Type.Delimiter}{methodInfo.Name}",
string.Join(", ", methodInfo.GetParameters().Select(p => $"{p.ParameterType.ToFriendlyString()} {p.Name}")),
root.ReturnType.ToString(),
name,
parameters,
body);
this.functionsInfo.Add(functionInfo);
}
}
}
+70 -37
ファイルの表示
@@ -2,12 +2,14 @@
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Buffers;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Translation.Models;
using TerraFX.Interop;
namespace ComputeSharp.Shaders.Translation
{
@@ -15,46 +17,50 @@ namespace ComputeSharp.Shaders.Translation
internal sealed partial class ShaderLoader<T>
{
/// <summary>
/// The number of captured graphics resources (buffers)
/// A <see langword="delegate"/> that loads all the captured members from a shader instance.
/// </summary>
private int _ResourcesCount;
/// <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.</param>
/// <param name="r1">A reference to the buffer to use to store all the captured value types.</param>
private delegate void DispatchDataLoader(in T shader, ref D3D12_GPU_DESCRIPTOR_HANDLE r0, ref byte r1);
/// <summary>
/// The size in bytes of the buffer with the captured variables
/// The number of captured graphics resources (buffers).
/// </summary>
private int _VariablesByteSize = 3 * sizeof(int); // X, Y and Z threads count
// The cached loader method
private DispatchDataLoader? _DispatchDataLoader;
private int totalResourceCount;
/// <summary>
/// The <see cref="List{T}"/> of <see cref="ReadableMember"/> instances mapping the captured variables in the current shader
/// The size in bytes of the buffer with the captured variables.
/// </summary>
private readonly List<ReadableMember> _CapturedMembers = new List<ReadableMember>();
/// <remarks>Initially set to 3 <see cref="int"/> values for X, Y and Z threads counts.</remarks>
private int totalVariablesByteSize = 3 * sizeof(int);
/// <summary>
/// A <see langword="delegate"/> that loads all the captured members from a shader instance
/// The cached <see cref="DispatchDataLoader"/> instance to load dispatch data before execution.
/// </summary>
/// <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="GraphicsResource"/> instances</param>
/// <param name="r1">A reference to the buffer to use to store all the captured value types</param>
private delegate void DispatchDataLoader(in T shader, ref GraphicsResource r0, ref byte r1);
private DispatchDataLoader? dispatchDataLoader;
/// <summary>
/// Gets a new <see cref="DispatchData"/> instance with all the captured data for the current shader instance
/// The <see cref="List{T}"/> of <see cref="ReadableMember"/> instances mapping the captured variables in the current shader.
/// </summary>
/// <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>
private readonly List<ReadableMember> capturedMembers = new();
/// <summary>
/// Gets a new <see cref="DispatchData"/> instance with all the captured data for the current shader instance.
/// </summary>
/// <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(in T shader, int x, int y, int z)
{
// Resources and variables buffers
GraphicsResource[] resources = ArrayPool<GraphicsResource>.Shared.Rent(_ResourcesCount);
byte[] variables = ArrayPool<byte>.Shared.Rent(_VariablesByteSize);
ref GraphicsResource r0 = ref resources[0];
ref byte r1 = ref variables[0];
D3D12_GPU_DESCRIPTOR_HANDLE[] resources = ArrayPool<D3D12_GPU_DESCRIPTOR_HANDLE>.Shared.Rent(this.totalResourceCount);
byte[] variables = ArrayPool<byte>.Shared.Rent(this.totalVariablesByteSize);
ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(resources);
ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables);
// Set the x, y and z counters
Unsafe.As<byte, int>(ref r1) = x;
@@ -62,42 +68,69 @@ namespace ComputeSharp.Shaders.Translation
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 2) = z;
// Invoke the dynamic method to extract the captured data
_DispatchDataLoader!(shader, ref r0, ref r1);
this.dispatchDataLoader!(shader, ref r0, ref r1);
return new DispatchData(resources, _ResourcesCount, variables, _VariablesByteSize);
return new DispatchData(resources, this.totalResourceCount, variables, this.totalVariablesByteSize);
}
/// <summary>
/// Builds a new <see cref="DispatchDataLoader"/> instance that loads the dispatch data for the current shader type
/// Builds a new <see cref="DispatchDataLoader"/> instance that loads the dispatch data for the current shader type.
/// </summary>
private void BuildDispatchDataLoader()
{
_DispatchDataLoader = DynamicMethod<DispatchDataLoader>.New(il =>
this.dispatchDataLoader = DynamicMethod<DispatchDataLoader>.New(il =>
{
foreach (ReadableMember member in _CapturedMembers)
foreach (ReadableMember member in this.capturedMembers)
{
if (HlslKnownTypes.IsKnownBufferType(member.MemberType))
{
// Load the offset address into the resource buffers
il.Emit(OpCodes.Ldarg_1);
if (_ResourcesCount > 0) il.EmitAddOffset<GraphicsResource>(_ResourcesCount);
_ResourcesCount++;
if (totalResourceCount > 0)
{
il.EmitAddOffset<D3D12_GPU_DESCRIPTOR_HANDLE>(this.totalResourceCount);
}
il.Emit(OpCodes.Ldarg_0);
il.EmitReadMember(member);
// Access Buffer<T>.D3D12GpuDescriptorHandle
FieldInfo gpuDescriptorInfo = member.MemberType.GetField(
nameof(Buffer<byte>.D3D12GpuDescriptorHandle),
BindingFlags.NonPublic | BindingFlags.Instance)!;
il.EmitReadMember(gpuDescriptorInfo);
il.EmitStoreToAddress(member.MemberType);
this.totalResourceCount++;
}
else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) || HlslKnownTypes.IsKnownVectorType(member.MemberType))
else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) ||
HlslKnownTypes.IsKnownVectorType(member.MemberType))
{
// Calculate the right offset with 16-bytes padding (HLSL constant buffer)
int size = member.MemberType == typeof(bool) ? sizeof(uint) : Marshal.SizeOf(member.MemberType); // bool is 4 bytes in HLSL
if (_VariablesByteSize % 16 > 16 - size) _VariablesByteSize += 16 - _VariablesByteSize % 16;
int size = member.MemberType == typeof(bool)
? sizeof(uint)
: Marshal.SizeOf(member.MemberType); // bool is 4 bytes in HLSL
if (this.totalVariablesByteSize % 16 > 16 - size)
{
this.totalVariablesByteSize += 16 - this.totalVariablesByteSize % 16;
}
// Load the target address into the variables buffer
il.Emit(OpCodes.Ldarg_2);
il.EmitAddOffset(_VariablesByteSize);
_VariablesByteSize += size;
il.EmitAddOffset(totalVariablesByteSize);
this.totalVariablesByteSize += size;
}
else throw new InvalidOperationException($"Invalid captured member of type {member.MemberType}");
// Load the reference to the input delegate if the member is not static
if (!member.IsStatic) il.Emit(OpCodes.Ldarg_0);
if (!member.IsStatic)
{
il.Emit(OpCodes.Ldarg_0);
}
// Read the current member and store it to the target address
il.EmitReadMember(member);
+96 -51
ファイルの表示
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.Shaders.Mappings;
@@ -13,7 +14,8 @@ using ComputeSharp.Shaders.Translation.Enums;
using ComputeSharp.Shaders.Translation.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Vortice.Direct3D12;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_DESCRIPTOR_RANGE_TYPE;
using ParameterInfo = ComputeSharp.Shaders.Renderer.Models.Functions.ParameterInfo;
#pragma warning disable CS8618 // Non-nullable field is uninitialized
@@ -21,81 +23,96 @@ using ParameterInfo = ComputeSharp.Shaders.Renderer.Models.Functions.ParameterIn
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> responsible for loading and processing shaders of a given type
/// A <see langword="class"/> responsible for loading and processing shaders of a given type.
/// </summary>
/// <typeparam name="T">The type of compute shader currently in use</typeparam>
/// <typeparam name="T">The type of compute shader currently in use.</typeparam>
internal sealed partial class ShaderLoader<T>
where T : struct, IComputeShader
{
/// <summary>
/// Creates a new <see cref="ShaderLoader{T}"/> instance
/// The number of constant buffers to define in the shader.
/// </summary>
private ShaderLoader() { }
private uint constantBuffersCount;
/// <summary>
/// The number of constant buffers to define in the shader
/// The number of readonly buffers to define in the shader.
/// </summary>
private int _ConstantBuffersCount;
private uint readOnlyBuffersCount;
/// <summary>
/// The number of readonly buffers to define in the shader
/// The number of read write buffers to define in the shader.
/// </summary>
private int _ReadOnlyBuffersCount;
private uint readWriteBuffersCount;
/// <summary>
/// The number of read write buffers to define in the shader
/// The <see cref="List{T}"/> of <see cref="D3D12_DESCRIPTOR_RANGE1"/> items that are required to load the captured values.
/// </summary>
private int _ReadWriteBuffersCount;
private readonly List<D3D12_DESCRIPTOR_RANGE1> d3D12DescriptorRanges1 = new();
/// <summary>
/// The <see cref="List{T}"/> of <see cref="DescriptorRange1"/> items that are required to load the captured values
/// The <see cref="List{T}"/> with the <see cref="HlslBufferInfo"/> items for the shader fields.
/// </summary>
private readonly List<DescriptorRange1> DescriptorRanges = new List<DescriptorRange1>();
private RootParameter1[]? _RootParameters;
private readonly List<HlslBufferInfo> hlslBuffersInfo = new();
/// <summary>
/// Gets the <see cref="RootParameter1"/> array for the current shader
/// The <see cref="List{T}"/> with the <see cref="CapturedFieldInfo"/> items for the shader fields.
/// </summary>
public RootParameter1[] RootParameters => _RootParameters ??= DescriptorRanges.Select(range => new RootParameter1(new RootDescriptorTable1(range), ShaderVisibility.All)).ToArray();
private readonly List<HlslBufferInfo> _BuffersList = new List<HlslBufferInfo>();
private readonly List<CapturedFieldInfo> fieldsInfo = new();
/// <summary>
/// Gets the collection of <see cref="HlslBufferInfo"/> items for the shader fields
/// The <see cref="List{T}"/> with the <see cref="FunctionInfo"/> items for the shader functions.
/// </summary>
public IReadOnlyList<HlslBufferInfo> BuffersList => _BuffersList;
private readonly List<CapturedFieldInfo> _FieldsList = new List<CapturedFieldInfo>();
private readonly List<FunctionInfo> functionsInfo = new();
/// <summary>
/// Gets the collection of <see cref="CapturedFieldInfo"/> items for the shader fields
/// The <see cref="List{T}"/> with the <see cref="FunctionInfo"/> items for the shader local functions.
/// </summary>
public IReadOnlyList<CapturedFieldInfo> FieldsList => _FieldsList;
private readonly List<LocalFunctionInfo> localFunctionsInfo = new();
/// <summary>
/// Gets the name of the <see cref="ThreadIds"/> variable used as input for the shader method
/// Creates a new <see cref="ShaderLoader{T}"/> instance.
/// </summary>
private ShaderLoader()
{
}
/// <summary>
/// Gets a <see cref="Span{T}"/> with the loaded <see cref="D3D12_DESCRIPTOR_RANGE1"/> items for the shader.
/// </summary>
public ReadOnlySpan<D3D12_DESCRIPTOR_RANGE1> D3D12DescriptorRanges1
{
get => CollectionsMarshal.AsSpan(this.d3D12DescriptorRanges1);
}
/// <summary>
/// Gets the name of the <see cref="ThreadIds"/> variable used as input for the shader method.
/// </summary>
public string ThreadsIdsVariableName { get; private set; }
/// <summary>
/// Gets the generated source code for the method in the current shader
/// Gets the generated source code for the method in the current shader.
/// </summary>
public string MethodBody { get; private set; }
private readonly List<FunctionInfo> _FunctionsList = new List<FunctionInfo>();
/// <summary>
/// Gets the collection of <see cref="HlslBufferInfo"/> items for the shader fields.
/// </summary>
public IReadOnlyList<HlslBufferInfo> HslsBuffersInfo => this.hlslBuffersInfo;
/// <summary>
/// Gets the collection of <see cref="FunctionInfo"/> items for the shader
/// Gets the collection of <see cref="CapturedFieldInfo"/> items for the shader fields.
/// </summary>
public IReadOnlyList<FunctionInfo> FunctionsList => _FunctionsList;
private readonly List<LocalFunctionInfo> _LocalFunctionsList = new List<LocalFunctionInfo>();
public IReadOnlyList<CapturedFieldInfo> FieldsInfo => this.fieldsInfo;
/// <summary>
/// Gets the collection of <see cref="LocalFunctionInfo"/> items for the shader
/// Gets the collection of <see cref="FunctionInfo"/> items for the shader.
/// </summary>
public IReadOnlyList<LocalFunctionInfo> LocalFunctionsList => _LocalFunctionsList;
public IReadOnlyList<FunctionInfo> FunctionsInfo => this.functionsInfo;
/// <summary>
/// Gets the collection of <see cref="LocalFunctionInfo"/> items for the shader.
/// </summary>
public IReadOnlyList<LocalFunctionInfo> LocalFunctionsInfo => this.localFunctionsInfo;
/// <summary>
/// Loads and processes an input<typeparamref name="T"/> shadeer
@@ -107,9 +124,9 @@ namespace ComputeSharp.Shaders.Translation
{
ShaderLoader<T> @this = new ShaderLoader<T>();
/* Reading members through reflection requires an object parameter,
* so here we're just boxing the input shader once to avoid allocating
* it multiple times in the managed heap while processing the shader. */
// Reading members through reflection requires an object parameter,
// so here we're just boxing the input shader once to avoid allocating
// it multiple times in the managed heap while processing the shader.
object box = shader;
@this.LoadFieldsInfo(box);
@@ -134,7 +151,13 @@ namespace ComputeSharp.Shaders.Translation
if (shaderFields.Count == 0) throw new InvalidOperationException("Empty shader body");
// Descriptor for the buffer for captured scalar/vector variables
DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount++));
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_CBV,
1,
this.constantBuffersCount++);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
// Inspect the captured fields
foreach (FieldInfo fieldInfo in shaderFields)
@@ -157,39 +180,61 @@ namespace ComputeSharp.Shaders.Translation
// Constant buffer
if (HlslKnownTypes.IsConstantBufferType(fieldType))
{
DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount));
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_CBV,
1,
this.constantBuffersCount++);
_CapturedMembers.Add(memberInfo);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]);
_BuffersList.Add(new ConstantBufferFieldInfo(fieldType, typeName, fieldName, _ConstantBuffersCount++));
this.hlslBuffersInfo.Add(new ConstantBufferFieldInfo(fieldType, typeName, fieldName, (int)this.constantBuffersCount));
}
else if (HlslKnownTypes.IsReadOnlyBufferType(fieldType))
{
// Root parameter for a readonly buffer
DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ShaderResourceView, 1, _ReadOnlyBuffersCount));
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
1,
this.readOnlyBuffersCount++);
_CapturedMembers.Add(memberInfo);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
_BuffersList.Add(new ReadOnlyBufferFieldInfo(fieldType, typeName, fieldName, _ReadOnlyBuffersCount++));
this.hlslBuffersInfo.Add(new ReadOnlyBufferFieldInfo(fieldType, typeName, fieldName, (int)this.readOnlyBuffersCount));
}
else if (HlslKnownTypes.IsReadWriteBufferType(fieldType))
{
// Root parameter for a read write buffer
DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.UnorderedAccessView, 1, _ReadWriteBuffersCount));
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_UAV,
1,
this.readWriteBuffersCount++);
_CapturedMembers.Add(memberInfo);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
_BuffersList.Add(new ReadWriteBufferFieldInfo(fieldType, typeName, fieldName, _ReadWriteBuffersCount++));
this.hlslBuffersInfo.Add(new ReadWriteBufferFieldInfo(fieldType, typeName, fieldName, (int)this.readWriteBuffersCount));
}
else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType))
{
_CapturedMembers.Add(memberInfo);
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
_FieldsList.Add(new CapturedFieldInfo(fieldType, typeName, fieldName));
this.fieldsInfo.Add(new CapturedFieldInfo(fieldType, typeName, fieldName));
}
else if (fieldType.IsDelegate() &&
memberInfo.GetValue(shader) is Delegate func &&
@@ -227,7 +272,7 @@ namespace ComputeSharp.Shaders.Translation
alignedLocal = Regex.Replace(alignedLocal, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
alignedLocal = HlslKnownKeywords.GetMappedText(alignedLocal);
_LocalFunctionsList.Add(new LocalFunctionInfo(alignedLocal));
this.localFunctionsInfo.Add(new LocalFunctionInfo(alignedLocal));
}
// Register the captured static members
@@ -304,7 +349,7 @@ namespace ComputeSharp.Shaders.Translation
parameters,
body);
_FunctionsList.Add(functionInfo);
this.functionsInfo.Add(functionInfo);
}
}
}