Move dynamic shader types to ComputeSharp.Dynamic
このコミットが含まれているのは:
1 親
5f8196716b
コミット
3bbf7754ba
13ファイル変更
+7
-1
検索条件に一致するファイルはありません
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
|
||||
namespace ComputeSharp;
|
||||
|
||||
/// <summary>
|
||||
/// An attribute that indicates that a method will be indirectly used in a compute shader.
|
||||
/// This method is necessary for methods that are captured and used within a given shader
|
||||
/// through a <see cref="Delegate"/> field (of some custom type). In order to be processed
|
||||
/// correctly, wrapped methods need to have this attribute manually applied to them.
|
||||
/// Methods also need to be static, though this can only be tested at runtime.
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
|
||||
public sealed class ShaderMethodAttribute : Attribute
|
||||
{
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace ComputeSharp.__Internals;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class ShaderMethodSourceAttribute : Attribute
|
||||
{
|
||||
/// <summary>
|
||||
/// Appends the mapped source code for the current method.
|
||||
/// </summary>
|
||||
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
|
||||
/// <param name="mapping">The mapping of already discovered constant names.</param>
|
||||
public void AppendConstants(ref ArrayPoolStringBuilder builder, HashSet<string> mapping)
|
||||
{
|
||||
foreach (KeyValuePair<string, string> constant in this.constants)
|
||||
{
|
||||
if (mapping.Add(constant.Key))
|
||||
{
|
||||
builder.Append("#define ");
|
||||
builder.Append(constant.Key);
|
||||
builder.Append(' ');
|
||||
builder.Append(constant.Value);
|
||||
builder.Append('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends the discovered types for the current method.
|
||||
/// </summary>
|
||||
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
|
||||
/// <param name="mapping">The mapping of already discovered type names.</param>
|
||||
public void AppendTypes(ref ArrayPoolStringBuilder builder, HashSet<string> mapping)
|
||||
{
|
||||
foreach (KeyValuePair<string, string> type in this.types)
|
||||
{
|
||||
if (mapping.Add(type.Key))
|
||||
{
|
||||
builder.Append('\n');
|
||||
builder.Append(type.Value);
|
||||
builder.Append('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends the discovered forward declarations for the current method.
|
||||
/// </summary>
|
||||
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
|
||||
/// <param name="mapping">The mapping of already discovered type names.</param>
|
||||
public void AppendForwardDeclarations(ref ArrayPoolStringBuilder builder, HashSet<string> mapping)
|
||||
{
|
||||
foreach (KeyValuePair<string, string> method in this.methods)
|
||||
{
|
||||
if (mapping.Add(method.Key))
|
||||
{
|
||||
builder.Append('\n');
|
||||
builder.Append(method.Key);
|
||||
builder.Append('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends the discovered methods for the current method.
|
||||
/// </summary>
|
||||
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
|
||||
/// <param name="mapping">The mapping of already discovered type names.</param>
|
||||
public void AppendMethods(ref ArrayPoolStringBuilder builder, HashSet<string> mapping)
|
||||
{
|
||||
foreach (KeyValuePair<string, string> method in this.methods)
|
||||
{
|
||||
if (mapping.Remove(method.Key))
|
||||
{
|
||||
builder.Append('\n');
|
||||
builder.Append(method.Value);
|
||||
builder.Append('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends the mapped source code for the current method.
|
||||
/// </summary>
|
||||
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
|
||||
/// <param name="name">The name to bind the method to.</param>
|
||||
public void AppendMappedInvokeMethod(ref ArrayPoolStringBuilder builder, string name)
|
||||
{
|
||||
builder.Append(this.invokeMethod.Replace(InvokeMethodIdentifier, name));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using ComputeSharp.Core.Extensions;
|
||||
|
||||
namespace ComputeSharp.__Internals;
|
||||
|
||||
/// <summary>
|
||||
/// An attribute that contains info on a processed shader method that can be executed within a shader.
|
||||
/// Instances of this attribute are generated from method annotated with <see cref="ShaderMethodAttribute"/>.
|
||||
/// </summary>
|
||||
/// <remarks>This attribute is not meant to be directly used by applications using ComputeSharp.</remarks>
|
||||
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
[Obsolete("This attribute is not intended to be used directly by user code")]
|
||||
public sealed partial class ShaderMethodSourceAttribute : Attribute
|
||||
{
|
||||
/// <summary>
|
||||
/// The identifier for the invoke method, for late binding.
|
||||
/// </summary>
|
||||
internal const string InvokeMethodIdentifier = "__<NAME>__";
|
||||
|
||||
/// <summary>
|
||||
/// The fully qualified name of the current method.
|
||||
/// </summary>
|
||||
private readonly string methodName;
|
||||
|
||||
/// <summary>
|
||||
/// The source code for the target entry point method.
|
||||
/// </summary>
|
||||
private readonly string invokeMethod;
|
||||
|
||||
/// <summary>
|
||||
/// The collection of custom types.
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, string> types;
|
||||
|
||||
/// <summary>
|
||||
/// The collection of processed methods.
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, string> methods;
|
||||
|
||||
/// <summary>
|
||||
/// The collection of discovered constants.
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, string> constants;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ShaderMethodSourceAttribute"/> instance with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="methodName">The fully qualified name of the current method.</param>
|
||||
/// <param name="invokeMethod">The source code for the target entry point method.</param>
|
||||
/// <param name="types">The collection of custom types.</param>
|
||||
/// <param name="methods">The collection of processed methods.</param>
|
||||
/// <param name="constants">The collection of discovered constants.</param>
|
||||
public ShaderMethodSourceAttribute(string methodName, string invokeMethod, object[] types, object[] methods, object[] constants)
|
||||
{
|
||||
this.methodName = methodName;
|
||||
this.invokeMethod = invokeMethod;
|
||||
this.types = types.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
|
||||
this.methods = methods.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
|
||||
this.constants = constants.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the associated <see cref="ShaderMethodSourceAttribute"/> instance for a specified delegate.
|
||||
/// </summary>
|
||||
/// <param name="function">The input <see cref="Delegate"/> instance to get info for.</param>
|
||||
/// <param name="name">The name of the shader field containing <paramref name="function"/>.</param>
|
||||
/// <returns>The associated <see cref="ShaderMethodSourceAttribute"/> instance for the given delegate.</returns>
|
||||
[Pure]
|
||||
public static ShaderMethodSourceAttribute GetForDelegate(Delegate function, string name)
|
||||
{
|
||||
if (!function.Method.IsStatic)
|
||||
{
|
||||
return ThrowArgumentExceptionForNonStaticMethod(name);
|
||||
}
|
||||
|
||||
var attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes<ShaderMethodSourceAttribute>();
|
||||
string methodName = function.Method.GetFullName();
|
||||
|
||||
foreach (var attribute in attributes)
|
||||
{
|
||||
if (attribute.methodName.Equals(methodName))
|
||||
{
|
||||
return attribute;
|
||||
}
|
||||
}
|
||||
|
||||
return ThrowArgumentExceptionForMissingShaderMethodAttribute(name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Throws an <see cref="ArgumentException"/> when a given <see cref="Delegate"/> is not static.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the shader field containing the invalid method.</param>
|
||||
private static ShaderMethodSourceAttribute ThrowArgumentExceptionForNonStaticMethod(string name)
|
||||
{
|
||||
throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a non static method (only static methods are supported for captured delegates).", name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Throws an <see cref="ArgumentException"/> when a given <see cref="Delegate"/> doesn't have <see cref="ShaderMethodAttribute"/> applied to it.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the shader field containing the invalid method.</param>
|
||||
private static ShaderMethodSourceAttribute ThrowArgumentExceptionForMissingShaderMethodAttribute(string name)
|
||||
{
|
||||
throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a method without the [ShaderMethod] attribute applied to it.", name);
|
||||
}
|
||||
}
|
||||
@@ -68,4 +68,8 @@
|
||||
</ItemGroup>
|
||||
</Otherwise>
|
||||
</Choose>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ComputeSharp\ComputeSharp.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,40 @@
|
||||
using System;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Text;
|
||||
|
||||
namespace ComputeSharp.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// A custom <see cref="Exception"/> type that indicates when a shader compilation with the DXC compiler has failed.
|
||||
/// </summary>
|
||||
public sealed class HlslCompilationException : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="HlslCompilationException"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="error">The error message produced by the DXC compiler.</param>
|
||||
internal HlslCompilationException(string error)
|
||||
: base(GetExceptionMessage(error))
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a formatted exception message for a given compilation error.
|
||||
/// </summary>
|
||||
/// <param name="error">The input compilatin error message from the DXC compiler.</param>
|
||||
/// <returns>A formatted error message for a new <see cref="HlslCompilationException"/> instance.</returns>
|
||||
[Pure]
|
||||
private static string GetExceptionMessage(string error)
|
||||
{
|
||||
StringBuilder builder = new(512);
|
||||
|
||||
builder.AppendLine("The DXC compiler encountered one or more errors while trying to compile the shader:");
|
||||
builder.AppendLine();
|
||||
builder.AppendLine(error.Trim());
|
||||
builder.AppendLine();
|
||||
builder.AppendLine("Make sure to only be using supported features by checking the README file in the ComputeSharp repository: https://github.com/Sergio0694/ComputeSharp.");
|
||||
builder.Append("If you're sure that your C# shader code is valid, please open an issue an include a working repro and this error message.");
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
using System;
|
||||
#if !DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT
|
||||
using System.Runtime.CompilerServices;
|
||||
#endif
|
||||
using ComputeSharp.__Internals;
|
||||
#if !DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT
|
||||
using ComputeSharp.Core.Extensions;
|
||||
using ComputeSharp.Shaders.Translation;
|
||||
#else
|
||||
using Microsoft.Toolkit.Diagnostics;
|
||||
#endif
|
||||
#if !DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
#endif
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.Interop;
|
||||
|
||||
/// <summary>
|
||||
/// Provides methods to extract reflection info on compute shaders generated using this library.
|
||||
/// </summary>
|
||||
public static class ReflectionServices
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the shader info associated with a given compute shader.
|
||||
/// <para>
|
||||
/// This overload can be used for simplicity when the compute shader being inspected does not rely on captured
|
||||
/// objects to be processed correctly. This is the case when it does not contain any <see cref="Delegate"/>-s.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of compute shader to retrieve info for.</typeparam>
|
||||
/// <param name="shaderInfo">The resulting <see cref="ShaderInfo"/> instance.</param>
|
||||
/// <remarks>
|
||||
/// The thread group sizes will always be set to (1, 1, 1) in the returned shader. This is done to
|
||||
/// avoid having to compiler multiple shaders just to get reflection info for them. When using any of
|
||||
/// 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
|
||||
{
|
||||
GetNonGenericShaderInfo(default(T), out shaderInfo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the shader info associated with a given compute shader.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of compute shader to retrieve info for.</typeparam>
|
||||
/// <param name="shader">The input compute shader to retrieve info for.</param>
|
||||
/// <param name="shaderInfo">The resulting <see cref="ShaderInfo"/> instance.</param>
|
||||
/// <remarks>
|
||||
/// The thread group sizes will always be set to (1, 1, 1) in the returned shader. This is done to
|
||||
/// avoid having to compiler multiple shaders just to get reflection info for them. When using any of
|
||||
/// 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
|
||||
{
|
||||
GetNonGenericShaderInfo(in shader, out shaderInfo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the shader info associated with a given pixel shader.
|
||||
/// <para>
|
||||
/// This overload can be used for simplicity when the pixel shader being inspected does not rely on captured
|
||||
/// objects to be processed correctly. This is the case when it does not contain any <see cref="Delegate"/>-s.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of pixel shader to retrieve info for.</typeparam>
|
||||
/// <typeparam name="TPixel">The type of pixels being processed by the shader.</typeparam>
|
||||
/// <param name="shaderInfo">The resulting <see cref="ShaderInfo"/> instance.</param>
|
||||
/// <remarks>
|
||||
/// The thread group sizes will always be set to (1, 1, 1) in the returned shader. This is done to
|
||||
/// avoid having to compiler multiple shaders just to get reflection info for them. When using any of
|
||||
/// 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 TPixel : unmanaged
|
||||
{
|
||||
GetNonGenericShaderInfo(default(T), out shaderInfo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the shader info associated with a given pixel shader.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of pixel shader to retrieve info for.</typeparam>
|
||||
/// <typeparam name="TPixel">The type of pixels being processed by the shader.</typeparam>
|
||||
/// <param name="shader">The input pixel shader to retrieve info for.</param>
|
||||
/// <param name="shaderInfo">The resulting <see cref="ShaderInfo"/> instance.</param>
|
||||
/// <remarks>
|
||||
/// The thread group sizes will always be set to (1, 1, 1) in the returned shader. This is done to
|
||||
/// avoid having to compiler multiple shaders just to get reflection info for them. When using any of
|
||||
/// 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 TPixel : unmanaged
|
||||
{
|
||||
GetNonGenericShaderInfo(in shader, out shaderInfo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the shader info associated with a given shader of any type.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of shader to retrieve info for.</typeparam>
|
||||
/// <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, IShader
|
||||
{
|
||||
#if DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT
|
||||
ThrowHelper.ThrowNotSupportedException("Runtime shader compilation is not supported by the current configuration.");
|
||||
|
||||
shaderInfo = default;
|
||||
#else
|
||||
Unsafe.AsRef(in shader).BuildHlslString(out ArrayPoolStringBuilder shaderSource, 1, 1, 1);
|
||||
|
||||
using ComPtr<IDxcBlob> dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(shaderSource.WrittenSpan);
|
||||
|
||||
shaderSource.Dispose();
|
||||
|
||||
using ComPtr<IDxcUtils> dxcUtils = default;
|
||||
|
||||
DirectX.DxcCreateInstance(
|
||||
(Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_DxcLibrary)),
|
||||
Windows.__uuidof<IDxcUtils>(),
|
||||
dxcUtils.GetVoidAddressOf()).Assert();
|
||||
|
||||
using ComPtr<ID3D12ShaderReflection> d3D12ShaderReflection = default;
|
||||
|
||||
DxcBuffer dxcBuffer = default;
|
||||
dxcBuffer.Ptr = dxcBlobBytecode.Get()->GetBufferPointer();
|
||||
dxcBuffer.Size = dxcBlobBytecode.Get()->GetBufferSize();
|
||||
|
||||
dxcUtils.Get()->CreateReflection(
|
||||
&dxcBuffer,
|
||||
Windows.__uuidof<ID3D12ShaderReflection>(),
|
||||
d3D12ShaderReflection.GetVoidAddressOf()).Assert();
|
||||
|
||||
D3D12_SHADER_DESC d3D12ShaderDescription;
|
||||
|
||||
d3D12ShaderReflection.Get()->GetDesc(&d3D12ShaderDescription).Assert();
|
||||
|
||||
shaderInfo = default;
|
||||
Unsafe.AsRef(shaderInfo.CompilerVersion) = new string(d3D12ShaderDescription.Creator);
|
||||
Unsafe.AsRef(shaderInfo.HlslSource) = shaderSource.WrittenSpan.ToString();
|
||||
Unsafe.AsRef(shaderInfo.ConstantBufferCount) = d3D12ShaderDescription.ConstantBuffers;
|
||||
Unsafe.AsRef(shaderInfo.BoundResourceCount) = d3D12ShaderDescription.BoundResources;
|
||||
Unsafe.AsRef(shaderInfo.InstructionCount) = d3D12ShaderDescription.InstructionCount;
|
||||
Unsafe.AsRef(shaderInfo.TemporaryRegisterCount) = d3D12ShaderDescription.TempRegisterCount;
|
||||
Unsafe.AsRef(shaderInfo.TemporaryArrayCount) = d3D12ShaderDescription.TempArrayCount;
|
||||
Unsafe.AsRef(shaderInfo.ConstantDefineCount) = d3D12ShaderDescription.DefCount;
|
||||
Unsafe.AsRef(shaderInfo.DeclarationCount) = d3D12ShaderDescription.DclCount;
|
||||
Unsafe.AsRef(shaderInfo.TextureNormalInstructions) = d3D12ShaderDescription.TextureNormalInstructions;
|
||||
Unsafe.AsRef(shaderInfo.TextureLoadInstructionCount) = d3D12ShaderDescription.TextureLoadInstructions;
|
||||
Unsafe.AsRef(shaderInfo.TextureStoreInstructionCount) = d3D12ShaderDescription.cTextureStoreInstructions;
|
||||
Unsafe.AsRef(shaderInfo.FloatInstructionCount) = d3D12ShaderDescription.FloatInstructionCount;
|
||||
Unsafe.AsRef(shaderInfo.IntInstructionCount) = d3D12ShaderDescription.IntInstructionCount;
|
||||
Unsafe.AsRef(shaderInfo.UIntInstructionCount) = d3D12ShaderDescription.UintInstructionCount;
|
||||
Unsafe.AsRef(shaderInfo.StaticFlowControlInstructionCount) = d3D12ShaderDescription.StaticFlowControlCount;
|
||||
Unsafe.AsRef(shaderInfo.DynamicFlowControlInstructionCount) = d3D12ShaderDescription.DynamicFlowControlCount;
|
||||
Unsafe.AsRef(shaderInfo.EmitInstructionCount) = d3D12ShaderDescription.EmitInstructionCount;
|
||||
Unsafe.AsRef(shaderInfo.BarrierInstructionCount) = d3D12ShaderDescription.cBarrierInstructions;
|
||||
Unsafe.AsRef(shaderInfo.InterlockedInstructionCount) = d3D12ShaderDescription.cInterlockedInstructions;
|
||||
Unsafe.AsRef(shaderInfo.BitwiseInstructionCount) = d3D12ShaderReflection.Get()->GetBitwiseInstructionCount();
|
||||
Unsafe.AsRef(shaderInfo.MovcInstructionCount) = d3D12ShaderReflection.Get()->GetMovcInstructionCount();
|
||||
Unsafe.AsRef(shaderInfo.MovInstructionCount) = d3D12ShaderReflection.Get()->GetMovInstructionCount();
|
||||
Unsafe.AsRef(shaderInfo.InterfaceSlotCount) = d3D12ShaderReflection.Get()->GetNumInterfaceSlots();
|
||||
Unsafe.AsRef(shaderInfo.RequiresDoublePrecisionSupport) = (d3D12ShaderReflection.Get()->GetRequiresFlags() & (D3D.D3D_SHADER_REQUIRES_DOUBLES | D3D.D3D_SHADER_REQUIRES_11_1_DOUBLE_EXTENSIONS)) != 0;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
namespace ComputeSharp.Interop;
|
||||
|
||||
/// <summary>
|
||||
/// A model representing reflection info for a given compute shader.
|
||||
/// </summary>
|
||||
public readonly struct ShaderInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// The compiler version used to build the shader.
|
||||
/// </summary>
|
||||
public readonly string CompilerVersion;
|
||||
|
||||
/// <summary>
|
||||
/// The HLSL source code the shader was built from.
|
||||
/// </summary>
|
||||
public readonly string HlslSource;
|
||||
|
||||
/// <summary>
|
||||
/// The number of shader constant buffers.
|
||||
/// </summary>
|
||||
public readonly uint ConstantBufferCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of resource (textures and buffers) bound to a shader.
|
||||
/// </summary>
|
||||
public readonly uint BoundResourceCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of intermediate-language instructions in the compiled shader.
|
||||
/// </summary>
|
||||
public readonly uint InstructionCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of temporary registers in the compiled shader.
|
||||
/// </summary>
|
||||
public readonly uint TemporaryRegisterCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of temporary arrays used.
|
||||
/// </summary>
|
||||
public readonly uint TemporaryArrayCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of constant defines.
|
||||
/// </summary>
|
||||
public readonly uint ConstantDefineCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of declarations (input + output).
|
||||
/// </summary>
|
||||
public readonly uint DeclarationCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of non-categorized texture instructions.
|
||||
/// </summary>
|
||||
public readonly uint TextureNormalInstructions;
|
||||
|
||||
/// <summary>
|
||||
/// The number of texture load instructions.
|
||||
/// </summary>
|
||||
public readonly uint TextureLoadInstructionCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of texture write instructions.
|
||||
/// </summary>
|
||||
public readonly uint TextureStoreInstructionCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of floating point arithmetic instructions used.
|
||||
/// </summary>
|
||||
public readonly uint FloatInstructionCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of signed integer arithmetic instructions used.
|
||||
/// </summary>
|
||||
public readonly uint IntInstructionCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of unsigned integer arithmetic instructions used.
|
||||
/// </summary>
|
||||
public readonly uint UIntInstructionCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of static flow control instructions used.
|
||||
/// </summary>
|
||||
public readonly uint StaticFlowControlInstructionCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of dynamic flow control instructions used.
|
||||
/// </summary>
|
||||
public readonly uint DynamicFlowControlInstructionCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of emit instructions used.
|
||||
/// </summary>
|
||||
public readonly uint EmitInstructionCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of barrier instructions used.
|
||||
/// </summary>
|
||||
public readonly uint BarrierInstructionCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of interlocked instructions used.
|
||||
/// </summary>
|
||||
public readonly uint InterlockedInstructionCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of bitwise instructions used.
|
||||
/// </summary>
|
||||
public readonly uint BitwiseInstructionCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of <c>movc</c> instructions used.
|
||||
/// </summary>
|
||||
public readonly uint MovcInstructionCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of <c>mov</c> instructions used.
|
||||
/// </summary>
|
||||
public readonly uint MovInstructionCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of interface slots used.
|
||||
/// </summary>
|
||||
public readonly uint InterfaceSlotCount;
|
||||
|
||||
/// <summary>
|
||||
/// Indicates whether support for double precision floating point numbers is required.
|
||||
/// </summary>
|
||||
public readonly bool RequiresDoublePrecisionSupport;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
#if !DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT && NET6_0_OR_GREATER
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Toolkit.Diagnostics;
|
||||
using TerraFX.Interop.Windows;
|
||||
|
||||
namespace ComputeSharp.Shaders.Translation;
|
||||
|
||||
/// <inheritdoc cref="ShaderCompiler"/>
|
||||
internal sealed unsafe partial class ShaderCompiler
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes the DLL resolvers for the dxcompiler.dll and dxil.dll libraries.
|
||||
/// </summary>
|
||||
static ShaderCompiler()
|
||||
{
|
||||
// Register a custom library resolver for the two DXC libraries. We need to either manually load the two
|
||||
// libraries from the NuGet directory, if an RID is not in use, or we need to ensure that dxil.dll is
|
||||
// loaded correctly in case the program was executed with the host being in another directory.
|
||||
// This happens when doing eg. "dotnet bin\Debug\net5.0\MyApp.dll", which would crash at runtime.
|
||||
Windows.ResolveLibrary += static (libraryName, assembly, searchPath) =>
|
||||
{
|
||||
if (libraryName is not "dxcompiler") return IntPtr.Zero;
|
||||
|
||||
string rid = RuntimeInformation.ProcessArchitecture switch
|
||||
{
|
||||
Architecture.X64 => "win-x64",
|
||||
Architecture.Arm64 => "win-arm64",
|
||||
_ => ThrowHelper.ThrowNotSupportedException<string>("Invalid process architecture")
|
||||
};
|
||||
|
||||
// Test whether the native libraries are present in the same folder of the executable
|
||||
// (which is the case when the program was built with a runtime identifier), or whether
|
||||
// they are in the "runtimes\win-x64\native" folder in the executable directory.
|
||||
string nugetNativeLibsPath = Path.Combine(AppContext.BaseDirectory, $@"runtimes\{rid}\native");
|
||||
bool isNuGetRuntimeLibrariesDirectoryPresent = Directory.Exists(nugetNativeLibsPath);
|
||||
|
||||
if (isNuGetRuntimeLibrariesDirectoryPresent)
|
||||
{
|
||||
string dxcompilerPath = Path.Combine(AppContext.BaseDirectory, $@"runtimes\{rid}\native\dxcompiler.dll");
|
||||
string dxilPath = Path.Combine(AppContext.BaseDirectory, $@"runtimes\{rid}\native\dxil.dll");
|
||||
|
||||
// Load DXIL first so that DXC doesn't fail to load it, and then DXIL, both from the NuGet path
|
||||
if (NativeLibrary.TryLoad(dxilPath, out _) &&
|
||||
NativeLibrary.TryLoad(dxcompilerPath, out IntPtr handle))
|
||||
{
|
||||
return handle;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Even when the two libraries are correctly copied next to the executable in use, we load them
|
||||
// manually to ensure the operation is successful. This is to avoid failures in cases such as when
|
||||
// doing "dotnet bin\MyApp.dll", ie. when the host is in another path than the executable in use.
|
||||
// This is probably because DXIL is a native dependency for DXC, but the way Windows loads these
|
||||
// libraries doesn't take into account the .NET concepts of "app directory": neither the current "bin"
|
||||
// directory nor the "process directory", which is "C:\Program Files\dotnet", actually contain the
|
||||
// native library we need, hence the runtime crash. Manually loading the library this way solves this.
|
||||
if (NativeLibrary.TryLoad("dxil", assembly, searchPath, out _) &&
|
||||
NativeLibrary.TryLoad("dxcompiler", assembly, searchPath, out IntPtr handle))
|
||||
{
|
||||
return handle;
|
||||
}
|
||||
}
|
||||
|
||||
return IntPtr.Zero;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,159 @@
|
||||
#if !DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT
|
||||
|
||||
using System;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Runtime.CompilerServices;
|
||||
using ComputeSharp.Core.Extensions;
|
||||
using ComputeSharp.Exceptions;
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
|
||||
namespace ComputeSharp.Shaders.Translation;
|
||||
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that uses the DXC APIs to compile compute shaders.
|
||||
/// </summary>
|
||||
internal sealed unsafe partial class ShaderCompiler
|
||||
{
|
||||
/// <summary>
|
||||
/// The thread local <see cref="ShaderCompiler"/> instance.
|
||||
/// This is necessary because the DXC library is strictly single-threaded.
|
||||
/// </summary>
|
||||
[ThreadStatic]
|
||||
private static ShaderCompiler? instance;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="IDxcCompiler"/> instance to use to create the bytecode for HLSL sources.
|
||||
/// </summary>
|
||||
private readonly ComPtr<IDxcCompiler> DxcCompiler;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="IDxcLibrary"/> instance to use to work with <see cref="DxcCompiler"/>.
|
||||
/// </summary>
|
||||
private readonly ComPtr<IDxcLibrary> DxcLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="IDxcIncludeHandler"/> instance used to compile shaders with <see cref="DxcCompiler"/>.
|
||||
/// </summary>
|
||||
private readonly ComPtr<IDxcIncludeHandler> DxcIncludeHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ShaderCompiler"/> instance.
|
||||
/// </summary>
|
||||
private ShaderCompiler()
|
||||
{
|
||||
using ComPtr<IDxcCompiler> dxcCompiler = default;
|
||||
using ComPtr<IDxcLibrary> dxcLibrary = default;
|
||||
using ComPtr<IDxcIncludeHandler> dxcIncludeHandler = default;
|
||||
|
||||
DirectX.DxcCreateInstance(
|
||||
(Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_DxcCompiler)),
|
||||
Windows.__uuidof<IDxcCompiler>(),
|
||||
dxcCompiler.GetVoidAddressOf()).Assert();
|
||||
|
||||
DirectX.DxcCreateInstance(
|
||||
(Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_DxcLibrary)),
|
||||
Windows.__uuidof<IDxcLibrary>(),
|
||||
dxcLibrary.GetVoidAddressOf()).Assert();
|
||||
|
||||
dxcLibrary.Get()->CreateIncludeHandler(dxcIncludeHandler.GetAddressOf()).Assert();
|
||||
|
||||
DxcCompiler = dxcCompiler.Move();
|
||||
DxcLibrary = dxcLibrary.Move();
|
||||
DxcIncludeHandler = dxcIncludeHandler.Move();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Destroys the current <see cref="ShaderCompiler"/> instance.
|
||||
/// </summary>
|
||||
~ShaderCompiler()
|
||||
{
|
||||
DxcCompiler.Dispose();
|
||||
DxcLibrary.Dispose();
|
||||
DxcIncludeHandler.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="ShaderCompiler"/> instance to use.
|
||||
/// </summary>
|
||||
public static ShaderCompiler Instance => instance ??= new();
|
||||
|
||||
/// <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 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* shaderName = "")
|
||||
fixed (char* entryPoint = nameof(IComputeShader.Execute))
|
||||
fixed (char* shaderProfile = "cs_6_0")
|
||||
fixed (char* optimization = "-O3")
|
||||
fixed (char* rowMajor = "-Zpr")
|
||||
fixed (char* warningsAsErrors = "-Werror")
|
||||
{
|
||||
char** arguments = stackalloc char*[3] { optimization, rowMajor, warningsAsErrors };
|
||||
|
||||
DxcCompiler.Get()->Compile(
|
||||
(IDxcBlob*)dxcBlobEncoding.Get(),
|
||||
(ushort*)shaderName,
|
||||
(ushort*)entryPoint,
|
||||
(ushort*)shaderProfile,
|
||||
(ushort**)arguments,
|
||||
3,
|
||||
null,
|
||||
0,
|
||||
DxcIncludeHandler.Get(),
|
||||
dxcOperationResult.GetAddressOf()).Assert();
|
||||
}
|
||||
|
||||
HRESULT 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>
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private static ComPtr<IDxcBlob> ThrowHslsCompilationException(IDxcOperationResult* dxcOperationResult)
|
||||
{
|
||||
using ComPtr<IDxcBlobEncoding> dxcBlobEncodingError = default;
|
||||
|
||||
dxcOperationResult->GetErrorBuffer(dxcBlobEncodingError.GetAddressOf()).Assert();
|
||||
|
||||
string message = new((sbyte*)dxcBlobEncodingError.Get()->GetBufferPointer());
|
||||
|
||||
throw new HlslCompilationException(message);
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,161 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace ComputeSharp.__Internals;
|
||||
|
||||
/// <summary>
|
||||
/// A helper type that implements a pooled buffer writer for <see cref="char"/> values.
|
||||
/// </summary>
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
[Obsolete("This type is not intended to be used directly by user code")]
|
||||
[DebuggerTypeProxy(typeof(DebugView))]
|
||||
public ref struct ArrayPoolStringBuilder
|
||||
{
|
||||
/// <summary>
|
||||
/// The underlying <see cref="char"/> array.
|
||||
/// </summary>
|
||||
private char[] array;
|
||||
|
||||
/// <summary>
|
||||
/// The starting offset within <see cref="array"/>.
|
||||
/// </summary>
|
||||
private int index;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ArrayPoolStringBuilder"/> instance ready to use.
|
||||
/// </summary>
|
||||
/// <param name="sizeHint">The size hint for the internal buffer to allocate.</param>
|
||||
/// <returns>A new <see cref="ArrayPoolStringBuilder"/> instance with default values.</returns>
|
||||
[Pure]
|
||||
public static ArrayPoolStringBuilder Create(int sizeHint)
|
||||
{
|
||||
ArrayPoolStringBuilder builder;
|
||||
|
||||
builder.array = ArrayPool<char>.Shared.Rent(sizeHint);
|
||||
builder.index = 0;
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public ReadOnlySpan<char> WrittenSpan
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get => new(this.array, 0, this.index);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends the input character to the current buffer.
|
||||
/// </summary>
|
||||
/// <param name="value">The input character to write.</param>
|
||||
public void Append(char value)
|
||||
{
|
||||
EnsureCapacity(1);
|
||||
|
||||
this.array[this.index++] = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends the input sequence of characters to the current buffer.
|
||||
/// </summary>
|
||||
/// <param name="value">The input characters to write.</param>
|
||||
public void Append(string value)
|
||||
{
|
||||
EnsureCapacity(value.Length);
|
||||
|
||||
#if NET6_0_OR_GREATER
|
||||
value.CopyTo(this.array.AsSpan(this.index));
|
||||
#else
|
||||
value.AsSpan().CopyTo(this.array.AsSpan(this.index));
|
||||
#endif
|
||||
|
||||
this.index += value.Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends the text representation of the input value to the current buffer.
|
||||
/// </summary>
|
||||
/// <param name="value">The input value to write.</param>
|
||||
public void Append(int value)
|
||||
{
|
||||
#if NET6_0_OR_GREATER
|
||||
int charsWritten;
|
||||
|
||||
while (!value.TryFormat(this.array.AsSpan(this.index), out charsWritten))
|
||||
{
|
||||
EnsureCapacity(10);
|
||||
}
|
||||
|
||||
this.index += charsWritten;
|
||||
#else
|
||||
Append(value.ToString());
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ensures that <see cref="array"/> has enough free space to contain a given number of new items.
|
||||
/// </summary>
|
||||
/// <param name="requestedSize">The minimum number of items to ensure space for in <see cref="array"/>.</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void EnsureCapacity(int requestedSize)
|
||||
{
|
||||
if (requestedSize > this.array.Length - this.index)
|
||||
{
|
||||
ResizeBuffer(requestedSize);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resizes <see cref="array"/> to ensure it can fit the specified number of new items.
|
||||
/// </summary>
|
||||
/// <param name="sizeHint">The minimum number of items to ensure space for in <see cref="array"/>.</param>
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private void ResizeBuffer(int sizeHint)
|
||||
{
|
||||
int minimumSize = this.index + sizeHint;
|
||||
|
||||
// Rent a new array with the specified size, and copy as many items from the current array
|
||||
// as possible to the new array. This mirrors the behavior of the Array.Resize API from
|
||||
// the BCL: if the new size is greater than the length of the current array, copy all the
|
||||
// items from the original array into the new one. Otherwise, copy as many items as possible,
|
||||
// until the new array is completely filled, and ignore the remaining items in the first array.
|
||||
char[] newArray = ArrayPool<char>.Shared.Rent(minimumSize);
|
||||
int itemsToCopy = Math.Min(this.array.Length, minimumSize);
|
||||
|
||||
Array.Copy(this.array, 0, newArray, 0, itemsToCopy);
|
||||
|
||||
ArrayPool<char>.Shared.Return(array);
|
||||
|
||||
this.array = newArray;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Dispose()
|
||||
{
|
||||
ArrayPool<char>.Shared.Return(this.array);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A debug proxy used for displaying debug info.
|
||||
/// </summary>
|
||||
internal sealed class DebugView
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DebugView"/> class with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="builder">The input <see cref="ArrayPoolStringBuilder"/> instance to display.</param>
|
||||
public DebugView(ArrayPoolStringBuilder builder)
|
||||
{
|
||||
Text = builder.WrittenSpan.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the text to display for the current instance.
|
||||
/// </summary>
|
||||
public string Text { get; }
|
||||
}
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする