From 5b8113c2ce18d13bc1172e546cfb13005447cadc Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 14 Oct 2023 09:58:16 +0200 Subject: [PATCH 1/7] Switch IShader.BuildHlslSource to a property --- .../Shaders/Interop/ReflectionServices.cs | 2 +- ...erator.CreateBuildHlslSourceMethod.Syntax.cs | 17 ++++++----------- .../Core/Interfaces/__Internals/IShader.cs | 13 +++++-------- 3 files changed, 12 insertions(+), 20 deletions(-) diff --git a/src/ComputeSharp.Dynamic/Shaders/Interop/ReflectionServices.cs b/src/ComputeSharp.Dynamic/Shaders/Interop/ReflectionServices.cs index b31d8c38..7ebb877f 100644 --- a/src/ComputeSharp.Dynamic/Shaders/Interop/ReflectionServices.cs +++ b/src/ComputeSharp.Dynamic/Shaders/Interop/ReflectionServices.cs @@ -104,7 +104,7 @@ public static class ReflectionServices private static unsafe ShaderInfo GetNonGenericShaderInfo(in T shader) where T : struct, IShader { - Unsafe.AsRef(in shader).BuildHlslSource(out string hlslSource); + string hlslSource = Unsafe.AsRef(in shader).HlslSource; using ComPtr dxcBlobBytecode = Shaders.Translation.ShaderCompiler.Instance.Compile(hlslSource); diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs index 1f86db7d..555652a0 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -19,17 +19,12 @@ partial class IShaderGenerator { writer.WriteLine("/// "); writer.WriteGeneratedAttributes(GeneratorName); - writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.BuildHlslSource(out string hlslSource)"); - - using (writer.WriteBlock()) - { - writer.WriteLine("hlslSource ="); - writer.IncreaseIndent(); - writer.WriteLine("\"\"\""); - writer.Write(info.HlslInfoKey.HlslSource, isMultiline: true); - writer.WriteLine("\"\"\";"); - writer.DecreaseIndent(); - } + writer.WriteLine($"readonly string global::ComputeSharp.__Internals.IShader.HlslSource =>"); + writer.IncreaseIndent(); + writer.WriteLine("\"\"\""); + writer.Write(info.HlslInfoKey.HlslSource, isMultiline: true); + writer.WriteLine("\"\"\";"); + writer.DecreaseIndent(); } } } \ No newline at end of file diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs index 2a0e128c..dc110632 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs @@ -25,6 +25,11 @@ public interface IShader /// int ThreadsZ { get; } + /// + /// Gets the HLSL source code for the current shader instance. + /// + string HlslSource { get; } + /// /// Gets the HLSL bytecode for the current shader. /// @@ -54,12 +59,4 @@ public interface IShader [Obsolete("This method is not intended to be called directly by user code")] void LoadDispatchMetadata(ref TLoader loader, out IntPtr result) where TLoader : struct, IDispatchMetadataLoader; - - /// - /// Builds the HLSL source code for the current shader instance. - /// - /// The resulting HLSL source. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] - void BuildHlslSource(out string hlslSource); } \ No newline at end of file From d90266fc61821333f552426089495f3f3df88b83 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 14 Oct 2023 10:20:31 +0200 Subject: [PATCH 2/7] Add and generate IShader.ConstantBufferSize API --- ...enerator.CreateLoadDispatchDataMethod.Syntax.cs | 2 +- ...ShaderGenerator.CreateLoadDispatchDataMethod.cs | 10 +++++----- ...ator.CreateLoadDispatchMetadataMethod.Syntax.cs | 14 +++++++++++++- .../IShaderGenerator.cs | 9 +++++---- .../Models/ShaderInfo.cs | 8 ++++---- .../Core/Interfaces/__Internals/IShader.cs | 10 ++++++++++ 6 files changed, 38 insertions(+), 15 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index 6c272144..a6a3cd5b 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -24,7 +24,7 @@ partial class IShaderGenerator using (writer.WriteBlock()) { - writer.WriteLine($"global::System.Span span0 = stackalloc uint[{info.Root32BitConstantCount}];"); + writer.WriteLine($"global::System.Span span0 = stackalloc uint[{info.ConstantBufferSizeInBytes}];"); writer.WriteLineIf($"global::System.Span span1 = stackalloc ulong[{info.ResourceCount}];", info.ResourceCount > 0); writer.WriteLine("ref uint r0 = ref span0[0];"); writer.WriteLineIf("ref ulong r1 = ref span1[0];", info.ResourceCount > 0); diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs index 0636ebc0..a026863c 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -27,16 +27,16 @@ partial class IShaderGenerator /// /// The collection of produced instances. /// The current shader type being explored. + /// The size of the shader constant buffer. /// Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture. /// The total number of captured resources in the shader. - /// The total number of needed 32 bit constants in the shader root signature. /// The sequence of instances for all captured resources and values. public static ImmutableArray GetInfo( ImmutableArrayBuilder diagnostics, ITypeSymbol structDeclarationSymbol, bool isPixelShaderLike, - out int resourceCount, - out int root32BitConstantCount) + out int constantBufferSizeInBytes, + out int resourceCount) { // Helper method that uses boxes instead of ref-s (illegal in enumerators) static IEnumerable GetCapturedFieldInfos( @@ -108,7 +108,7 @@ partial class IShaderGenerator // the local variables is padded to a multiple of a 32 bit value. This is necessary to // enable loading all the dispatch data after reinterpreting it to a sequence of values // of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds. - root32BitConstantCount = AlignmentHelper.Pad(rawDataOffsetAsBox.Value, sizeof(int)) / sizeof(int); + constantBufferSizeInBytes = AlignmentHelper.Pad(rawDataOffsetAsBox.Value, sizeof(int)) / sizeof(int); // A shader root signature has a maximum size of 64 DWORDs, so 256 bytes. // Loaded values in the root signature have the following costs: @@ -118,7 +118,7 @@ partial class IShaderGenerator // So here we check whether the current signature respects that constraint, // and emit a build error otherwise. For more info on this, see the docs here: // https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits. - int rootSignatureDwordSize = root32BitConstantCount + resourceCount; + int rootSignatureDwordSize = constantBufferSizeInBytes + resourceCount; if (rootSignatureDwordSize > 64) { diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs index 2faed681..22881355 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs @@ -11,6 +11,18 @@ partial class IShaderGenerator /// partial class LoadDispatchMetadata { + /// + /// Writes the ConstantBufferSize property. + /// + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteConstantBufferSizeSyntax(ShaderInfo info, IndentedTextWriter writer) + { + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(GeneratorName); + writer.WriteLine($"readonly int global::ComputeSharp.__Internals.IShader.ConstantBufferSize => {info.ConstantBufferSizeInBytes};"); + } + /// /// Writes the LoadDispatchMetadata method. /// @@ -34,7 +46,7 @@ partial class IShaderGenerator writer.WriteLine("ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0];"); // Write the serialized shader metadata - writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {info.Root32BitConstantCount});"); + writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {info.ConstantBufferSizeInBytes});"); writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {info.IsSamplerUsed.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()});"); // Populate the sequence of resource descriptors diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index d7c41ae6..49144cbd 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -59,8 +59,8 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator diagnostics, typeSymbol, isPixelShaderLike, - out int resourceCount, - out int root32BitConstantCount); + out int root32BitConstantCount, + out int resourceCount); token.ThrowIfCancellationRequested(); @@ -123,10 +123,10 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator ThreadsZ: threadsZ, IsPixelShaderLike: isPixelShaderLike, IsSamplerUsed: isSamplerUsed, + ConstantBufferSizeInBytes: root32BitConstantCount, + ResourceCount: resourceCount, Fields: fieldInfos, ResourceDescriptors: resourceDescriptors, - ResourceCount: resourceCount, - Root32BitConstantCount: root32BitConstantCount, HlslInfoKey: hlslInfoKey, HlslInfo: hlslInfo, Diagnostcs: diagnostics.ToImmutable()); @@ -148,6 +148,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator declaredMembers.Add(LoadBytecode.WriteThreadsXSyntax); declaredMembers.Add(LoadBytecode.WriteThreadsYSyntax); declaredMembers.Add(LoadBytecode.WriteThreadsZSyntax); + declaredMembers.Add(LoadDispatchMetadata.WriteConstantBufferSizeSyntax); declaredMembers.Add(LoadBytecode.WriteHlslBytecodeSyntax); declaredMembers.Add(LoadDispatchData.WriteSyntax); declaredMembers.Add(LoadDispatchMetadata.WriteSyntax); diff --git a/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs index cb51e35d..70370257 100644 --- a/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs @@ -12,10 +12,10 @@ namespace ComputeSharp.SourceGenerators.Models; /// The thread ids value for the Z axis. /// Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture. /// Whether or not the static sampler is used. +/// /// The size of the shader constant buffer. +/// The total number of captured resources in the shader. /// The description on shader instance fields. /// The sequence of resource descriptors for the shader. -/// The total number of captured resources in the shader. -/// The size of the shader root signature, in 32 bit constants. /// The key with processed info on the shader. /// The value with processed info on the shader. /// The discovered diagnostics, if any. @@ -26,10 +26,10 @@ internal sealed record ShaderInfo( int ThreadsZ, bool IsPixelShaderLike, bool IsSamplerUsed, + int ConstantBufferSizeInBytes, + int ResourceCount, EquatableArray Fields, EquatableArray ResourceDescriptors, - int ResourceCount, - int Root32BitConstantCount, HlslBytecodeInfoKey HlslInfoKey, HlslBytecodeInfo HlslInfo, EquatableArray Diagnostcs); \ No newline at end of file diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs index dc110632..b1fa6a4e 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs @@ -25,6 +25,16 @@ public interface IShader /// int ThreadsZ { get; } + /// + /// Gets the size in bytes of the constant buffer for the current shader. + /// + /// + /// Constant buffer data is bound to shaders via 32 bit root constants, and loaded before dispatching via + /// ID3D12GraphicsCommandList::SetComputeRoot32BitConstants, + /// so the size must be a multiple of 4. + /// + int ConstantBufferSize { get; } + /// /// Gets the HLSL source code for the current shader instance. /// From 30414faf405cc0440fd07c3dba71706191f0fe4e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 14 Oct 2023 10:28:57 +0200 Subject: [PATCH 3/7] Add and generate IShader.IsStaticSamplerRequired API --- ...erator.CreateLoadDispatchMetadataMethod.Syntax.cs | 12 ++++++++++++ .../IShaderGenerator.cs | 3 ++- .../Core/Interfaces/__Internals/IShader.cs | 8 ++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs index 22881355..0f1117e2 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs @@ -23,6 +23,18 @@ partial class IShaderGenerator writer.WriteLine($"readonly int global::ComputeSharp.__Internals.IShader.ConstantBufferSize => {info.ConstantBufferSizeInBytes};"); } + /// + /// Writes the IsStaticSamplerRequired property. + /// + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteIsStaticSamplerRequiredSyntax(ShaderInfo info, IndentedTextWriter writer) + { + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(GeneratorName); + writer.WriteLine($"readonly bool global::ComputeSharp.__Internals.IShader.IsStaticSamplerRequired => {info.IsSamplerUsed.ToString().ToLowerInvariant()};"); + } + /// /// Writes the LoadDispatchMetadata method. /// diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 49144cbd..511845f3 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -149,10 +149,11 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator declaredMembers.Add(LoadBytecode.WriteThreadsYSyntax); declaredMembers.Add(LoadBytecode.WriteThreadsZSyntax); declaredMembers.Add(LoadDispatchMetadata.WriteConstantBufferSizeSyntax); + declaredMembers.Add(LoadDispatchMetadata.WriteIsStaticSamplerRequiredSyntax); + declaredMembers.Add(BuildHlslSource.WriteSyntax); declaredMembers.Add(LoadBytecode.WriteHlslBytecodeSyntax); declaredMembers.Add(LoadDispatchData.WriteSyntax); declaredMembers.Add(LoadDispatchMetadata.WriteSyntax); - declaredMembers.Add(BuildHlslSource.WriteSyntax); using ImmutableArrayBuilder> additionalTypes = new(); using ImmutableHashSetBuilder usingDirectives = new(); diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs index b1fa6a4e..089c3e94 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs @@ -35,6 +35,14 @@ public interface IShader /// int ConstantBufferSize { get; } + /// + /// Gets whether the shader requires a static sampler being declared and initialized. + /// + /// + /// When requested, a static sampler with linear sampling and mirror addressing will be bound to register(s). + /// + bool IsStaticSamplerRequired { get; } + /// /// Gets the HLSL source code for the current shader instance. /// From 104f216c6109da01b5334becc22ef1addb194c00 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 14 Oct 2023 10:44:06 +0200 Subject: [PATCH 4/7] Refactor ResourceDescriptor, add ResourceDescriptorRangeType --- .../Shaders/Interop/D2D1InputDescription.cs | 29 ++--------- .../Interop/D2D1ResourceTextureDescription.cs | 19 ++----- .../__Internals/IDispatchMetadataLoader.cs | 2 +- .../Interop/ResourceDescriptorRange.cs | 38 ++++++++++++++ .../Interop/ResourceDescriptorRangeType.cs | 28 +++++++++++ .../Interop/__Internals/ResourceDescriptor.cs | 50 ------------------- .../ShaderDispatchMetadataLoader.cs | 4 +- 7 files changed, 78 insertions(+), 92 deletions(-) create mode 100644 src/ComputeSharp/Graphics/Interop/ResourceDescriptorRange.cs create mode 100644 src/ComputeSharp/Graphics/Interop/ResourceDescriptorRangeType.cs delete mode 100644 src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InputDescription.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InputDescription.cs index 0a403fd8..9a563844 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InputDescription.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InputDescription.cs @@ -12,21 +12,6 @@ namespace ComputeSharp.D2D1.Interop; [StructLayout(LayoutKind.Sequential)] public readonly struct D2D1InputDescription { - /// - /// The index of the resource the description belongs to. - /// - private readonly int index; - - /// - /// The type of filter to apply to the input texture. - /// - private readonly D2D1Filter filter; - - /// - /// The mip level to retrieve from the upstream transform, if specified. - /// - private readonly int levelOfDetailCount; - /// /// Creates a new instance with the specified parameters. /// @@ -34,26 +19,22 @@ public readonly struct D2D1InputDescription /// The type of filter to apply to the input texture. public D2D1InputDescription(int index, D2D1Filter filter) { - this.index = index; - this.filter = filter; + Index = index; + Filter = filter; } /// /// Gets the index of the resource the description belongs to. /// - public int Index => this.index; + public int Index { get; } /// /// Gets the type of filter to apply to the input texture. /// - public D2D1Filter Filter => this.filter; + public D2D1Filter Filter { get; } /// /// Gets the mip level to retrieve from the upstream transform, if specified. /// - public int LevelOfDetailCount - { - get => this.levelOfDetailCount; - init => this.levelOfDetailCount = value; - } + public int LevelOfDetailCount { get; init; } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureDescription.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureDescription.cs index ce924f0a..93977ca7 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureDescription.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureDescription.cs @@ -8,17 +8,6 @@ namespace ComputeSharp.D2D1.Interop; [StructLayout(LayoutKind.Sequential)] public readonly struct D2D1ResourceTextureDescription { - /// - /// The index of the resource texture the description belongs to. - /// - /// See notes in for why explicit fields are used here. - private readonly int index; - - /// - /// The number of dimensions of the resource texture the description belongs to. - /// - private readonly int dimensions; - /// /// Creates a new instance with the specified parameters. /// @@ -26,17 +15,17 @@ public readonly struct D2D1ResourceTextureDescription /// The number of dimensions of the resource texture the description belongs to. public D2D1ResourceTextureDescription(int index, int dimensions) { - this.index = index; - this.dimensions = dimensions; + Index = index; + Dimensions = dimensions; } /// /// Gets the index of the resource texture the description belongs to. /// - public int Index => this.index; + public int Index { get; } /// /// Gets the rank of the resource texture the description belongs to. /// - public int Dimensions => this.dimensions; + public int Dimensions { get; } } \ No newline at end of file diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs index 0e455379..0ae91753 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs @@ -16,5 +16,5 @@ public interface IDispatchMetadataLoader /// The serialized metadata for the current shader. /// The sequence of resource descriptors for the current shader. /// The resulting opaque metadata handle. - void LoadMetadataHandle(ReadOnlySpan serializedMetadata, ReadOnlySpan resourceDescriptors, out IntPtr result); + void LoadMetadataHandle(ReadOnlySpan serializedMetadata, ReadOnlySpan resourceDescriptors, out IntPtr result); } \ No newline at end of file diff --git a/src/ComputeSharp/Graphics/Interop/ResourceDescriptorRange.cs b/src/ComputeSharp/Graphics/Interop/ResourceDescriptorRange.cs new file mode 100644 index 00000000..ed5dc8dc --- /dev/null +++ b/src/ComputeSharp/Graphics/Interop/ResourceDescriptorRange.cs @@ -0,0 +1,38 @@ +using System.Runtime.InteropServices; + +namespace ComputeSharp.Interop; + +/// +/// A type containing info on a descriptor for a given D3D12 shader resource range. +/// +/// +/// This type exposes a subset of values from +/// D3D12_DESCRIPTOR_RANGE1. +/// +[StructLayout(LayoutKind.Sequential)] +public readonly struct ResourceDescriptorRange +{ + /// + /// Creates a new instance with the specified parameters. + /// + /// The type of the descriptor range. + /// The shader register in the range. + public ResourceDescriptorRange(ResourceDescriptorRangeType type, uint register) + { + Type = type; + Register = register; + } + + /// + /// Gets the type of the descriptor range. + /// + public ResourceDescriptorRangeType Type { get; } + + /// + /// Gets the shader register in the range. + /// + /// + /// For example, for shader-resource views (SRVs), 3 maps to register(t3) in HLSL. + /// + public uint Register { get; } +} \ No newline at end of file diff --git a/src/ComputeSharp/Graphics/Interop/ResourceDescriptorRangeType.cs b/src/ComputeSharp/Graphics/Interop/ResourceDescriptorRangeType.cs new file mode 100644 index 00000000..9e6640bc --- /dev/null +++ b/src/ComputeSharp/Graphics/Interop/ResourceDescriptorRangeType.cs @@ -0,0 +1,28 @@ +using static TerraFX.Interop.DirectX.D3D12_DESCRIPTOR_RANGE_TYPE; + +namespace ComputeSharp.Interop; + +/// +/// A type containing info on a descriptor type for a given D3D12 shader resource range. +/// +/// +/// This type exposes the available values in +/// D3D12_DESCRIPTOR_RANGE_TYPE. +/// +public enum ResourceDescriptorRangeType +{ + /// + /// Specifies a range of SRVs. + /// + ShaderResourceView = D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + + /// + /// Specifies a range of unordered-access views (UAVs). + /// + UnorderedAccessView = D3D12_DESCRIPTOR_RANGE_TYPE_UAV, + + /// + /// Specifies a range of constant-buffer views (CBVs). + /// + ConstantBufferView = D3D12_DESCRIPTOR_RANGE_TYPE_CBV +} \ No newline at end of file diff --git a/src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs b/src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs deleted file mode 100644 index 803ef761..00000000 --- a/src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.ComponentModel; -using TerraFX.Interop.DirectX; -using static TerraFX.Interop.DirectX.D3D12_DESCRIPTOR_RANGE_FLAGS; - -#pragma warning disable IDE0052, IDE1006, CS0414 - -namespace ComputeSharp.__Internals; - -/// -/// An opaque type describing a captured resource to be used in a shader. -/// -[EditorBrowsable(EditorBrowsableState.Never)] -[Obsolete("This type is not intended to be used directly by user code")] -public struct ResourceDescriptor -{ - /// - private D3D12_DESCRIPTOR_RANGE_TYPE RangeType; - - /// - private uint NumDescriptors; - - /// - private uint BaseShaderRegister; - - /// - private uint RegisterSpace; - - /// - private D3D12_DESCRIPTOR_RANGE_FLAGS Flags; - - /// - private uint OffsetInDescriptorsFromTableStart; - - /// - /// Initializes a new instance. - /// - /// The type of resource to create the descriptor for. - /// The offset in the resource from the start of the shader mapping. - /// The resulting instance. - public static void Create(int type, uint offset, out ResourceDescriptor descriptor) - { - descriptor.RangeType = (D3D12_DESCRIPTOR_RANGE_TYPE)type; - descriptor.NumDescriptors = 1; - descriptor.BaseShaderRegister = offset; - descriptor.RegisterSpace = 0; - descriptor.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE; - descriptor.OffsetInDescriptorsFromTableStart = D3D12.D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - } -} \ No newline at end of file diff --git a/src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs b/src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs index eb92cd8a..c43be70d 100644 --- a/src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs +++ b/src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs @@ -31,7 +31,7 @@ internal readonly unsafe struct ShaderDispatchMetadataLoader : IDispatchMetadata } /// - public unsafe void LoadMetadataHandle(ReadOnlySpan serializedMetadata, ReadOnlySpan resourceDescriptors, out IntPtr result) + public unsafe void LoadMetadataHandle(ReadOnlySpan serializedMetadata, ReadOnlySpan resourceDescriptors, out IntPtr result) { default(ArgumentException).ThrowIf(serializedMetadata.Length != 5, nameof(serializedMetadata)); @@ -39,7 +39,7 @@ internal readonly unsafe struct ShaderDispatchMetadataLoader : IDispatchMetadata { *(ComPtr*)p = this.d3D12Device->CreateRootSignature( MemoryMarshal.Read(serializedMetadata), - MemoryMarshal.Cast(resourceDescriptors), + MemoryMarshal.Cast(resourceDescriptors), MemoryMarshal.Read(serializedMetadata.Slice(4))); } } From 4f53b3e6869b66d108574e2e6d8c7e0dc80d08f3 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 14 Oct 2023 11:06:18 +0200 Subject: [PATCH 5/7] Implement generation of IShader.ResourceDescriptorRanges --- ...iptorGenerator.InputDescriptions.Syntax.cs | 4 +- ...CreateLoadDispatchMetadataMethod.Syntax.cs | 94 ++++++++++++++----- ...erator.CreateLoadDispatchMetadataMethod.cs | 9 +- .../IShaderGenerator.cs | 3 +- .../Models/ResourceDescriptor.cs | 5 +- .../Core/Interfaces/__Internals/IShader.cs | 6 ++ 6 files changed, 85 insertions(+), 36 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputDescriptions.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputDescriptions.Syntax.cs index e90e3eae..d1f19417 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputDescriptions.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputDescriptions.Syntax.cs @@ -96,7 +96,7 @@ partial class D2DPixelShaderDescriptorGenerator /// /// The input instance with gathered shader info. /// The using directives needed by the generated code. - public static void AddAdditionalDataMemberUsingDirectives(D2D1ShaderInfo info, ImmutableHashSetBuilder usingDirectives) + private static void AddAdditionalDataMemberUsingDirectives(D2D1ShaderInfo info, ImmutableHashSetBuilder usingDirectives) { if (info.InputDescriptions.IsEmpty) { @@ -112,7 +112,7 @@ partial class D2DPixelShaderDescriptorGenerator /// /// The input instance with gathered shader info. /// The registered callbacks to generate additional data members. - public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) + private static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) { // If there are no input descriptions, there is nothing to di if (info.InputDescriptions.IsEmpty) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs index 0f1117e2..5e3a9eca 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs @@ -1,4 +1,3 @@ -using System.Globalization; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGenerators.Models; @@ -36,7 +35,7 @@ partial class IShaderGenerator } /// - /// Writes the LoadDispatchMetadata method. + /// Writes the ResourceDescriptorRanges property. /// /// The input instance with gathered shader info. /// The instance to write into. @@ -44,32 +43,77 @@ partial class IShaderGenerator { writer.WriteLine("/// "); writer.WriteGeneratedAttributes(GeneratorName); - writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]"); - writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata(ref TLoader loader, out global::System.IntPtr result)"); + writer.Write($"readonly global::System.ReadOnlyMemory global::ComputeSharp.__Internals.IShader.ResourceDescriptorRanges => "); - using (writer.WriteBlock()) + // If there are no declared resources, just return an empty collection + if (info.ResourceDescriptors.IsEmpty) { - // Compute the total number of resources - int totalResourcesCount = info.ResourceDescriptors.Length; - - writer.WriteLine("global::System.Span span0 = stackalloc byte[5];"); - writer.WriteLine($"global::System.Span span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[{totalResourcesCount}];"); - writer.WriteLine("ref byte r0 = ref span0[0];"); - writer.WriteLine("ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0];"); - - // Write the serialized shader metadata - writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {info.ConstantBufferSizeInBytes});"); - writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {info.IsSamplerUsed.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()});"); - - // Populate the sequence of resource descriptors - foreach (ResourceDescriptor descriptor in info.ResourceDescriptors) - { - writer.WriteLine($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));"); - } - - // Invoke the value delegate to create the opaque root signature handle - writer.WriteLine("loader.LoadMetadataHandle(span0, span1, out result);"); + writer.WriteLine("default;"); } + else + { + writer.WriteLine("global::ComputeSharp.Generated.Data.ResourceDescriptorRanges;"); + } + } + + /// + /// Registers a callback to generate an additional data member, if needed. + /// + /// The input instance with gathered shader info. + /// The registered callbacks to generate additional data members. + /// The using directives needed by the generated code. + public static void RegisterAdditionalDataMemberSyntax( + ShaderInfo info, + ImmutableArrayBuilder> callbacks, + ImmutableHashSetBuilder usingDirectives) + { + // If there are no declared resources, there is nothing to di + if (info.ResourceDescriptors.IsEmpty) + { + return; + } + + usingDirectives.Add("global::System.CodeDom.Compiler"); + usingDirectives.Add("global::System.Diagnostics"); + usingDirectives.Add("global::System.Diagnostics.CodeAnalysis"); + usingDirectives.Add("global::ComputeSharp.Interop"); + + // Declare the additional data type and the shared array with resource descriptor ranges + static void Callback(ShaderInfo info, IndentedTextWriter writer) + { + writer.WriteLine($$"""/// """); + writer.WriteLine($$"""/// A container type for additional data needed by the shader."""); + writer.WriteLine($$"""/// """); + writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false); + writer.WriteLine($$"""file static class Data"""); + + using (writer.WriteBlock()) + { + writer.WriteLine("""/// The singleton array instance."""); + writer.WriteLine("""public static readonly ResourceDescriptorRange[] ResourceDescriptorRanges ="""); + writer.WriteLine("""{"""); + writer.IncreaseIndent(); + + // Initialize all resource descriptor ranges + writer.WriteInitializationExpressions(info.ResourceDescriptors.AsSpan(), static (description, writer) => + { + string rangeTypeName = description.TypeId switch + { + 0 => "ShaderResourceView", + 1 => "UnorderedAccessView", + _ => "ConstantBufferView" + }; + + writer.Write($"new ResourceDescriptorRange(ResourceDescriptorRangeType.{rangeTypeName}, {description.Register})"); + }); + + writer.DecreaseIndent(); + writer.WriteLine(); + writer.WriteLine("};"); + } + } + + callbacks.Add(Callback); } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs index 96fe4ebf..4e448bdc 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs @@ -32,12 +32,11 @@ partial class IShaderGenerator int constantBufferOffset = 1; int readOnlyResourceOffset = 0; int readWriteResourceOffset = 0; - int resourceOffset = 0; // Add the implicit texture descriptor, if needed if (isImplicitTextureUsed) { - descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++)); + descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++)); } // Populate the sequence of resource descriptors @@ -45,15 +44,15 @@ partial class IShaderGenerator { if (HlslKnownTypes.IsConstantBufferType(resource.TypeName)) { - descriptors.Add(new ResourceDescriptor(2, constantBufferOffset++, resourceOffset++)); + descriptors.Add(new ResourceDescriptor(2, constantBufferOffset++)); } else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource.TypeName)) { - descriptors.Add(new ResourceDescriptor(0, readOnlyResourceOffset++, resourceOffset++)); + descriptors.Add(new ResourceDescriptor(0, readOnlyResourceOffset++)); } else { - descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++)); + descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++)); } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 511845f3..27f554a0 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -150,14 +150,15 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator declaredMembers.Add(LoadBytecode.WriteThreadsZSyntax); declaredMembers.Add(LoadDispatchMetadata.WriteConstantBufferSizeSyntax); declaredMembers.Add(LoadDispatchMetadata.WriteIsStaticSamplerRequiredSyntax); + declaredMembers.Add(LoadDispatchMetadata.WriteSyntax); declaredMembers.Add(BuildHlslSource.WriteSyntax); declaredMembers.Add(LoadBytecode.WriteHlslBytecodeSyntax); declaredMembers.Add(LoadDispatchData.WriteSyntax); - declaredMembers.Add(LoadDispatchMetadata.WriteSyntax); using ImmutableArrayBuilder> additionalTypes = new(); using ImmutableHashSetBuilder usingDirectives = new(); + LoadDispatchMetadata.RegisterAdditionalDataMemberSyntax(item, additionalTypes, usingDirectives); LoadBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives); using IndentedTextWriter writer = new(); diff --git a/src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs b/src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs index 791af20a..805b537c 100644 --- a/src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs +++ b/src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs @@ -4,6 +4,5 @@ namespace ComputeSharp.SourceGenerators.Models; /// A resource descriptor for a captured resource in a shader. /// /// The type id for the resource. -/// The offset of the resource in its containing register. -/// The offset of the resource descriptor in the shader root signature. -internal sealed record ResourceDescriptor(int TypeId, int RegisterOffset, int Offset); \ No newline at end of file +/// The register offset for the resource descriptor. +internal sealed record ResourceDescriptor(int TypeId, int Register); \ No newline at end of file diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs index 089c3e94..2d00eb1b 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs @@ -1,5 +1,6 @@ using System; using System.ComponentModel; +using ComputeSharp.Interop; namespace ComputeSharp.__Internals; @@ -43,6 +44,11 @@ public interface IShader /// bool IsStaticSamplerRequired { get; } + /// + /// Gets the resource descriptor ranges for all resources that should be bound to this shader. + /// + ReadOnlyMemory ResourceDescriptorRanges { get; } + /// /// Gets the HLSL source code for the current shader instance. /// From 4f872c661ed95d574245279550c516e5c51d6afc Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 14 Oct 2023 11:38:47 +0200 Subject: [PATCH 6/7] Update PipelineDataLoader to use new descriptor ranges --- .../__Internals/IDispatchMetadataLoader.cs | 20 ------ .../Core/Interfaces/__Internals/IShader.cs | 11 ---- .../ShaderDispatchMetadataLoader.cs | 46 -------------- .../Shaders/Loading/PipelineDataLoader{T}.cs | 61 ++++++++++++++++--- 4 files changed, 54 insertions(+), 84 deletions(-) delete mode 100644 src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs delete mode 100644 src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs deleted file mode 100644 index 0ae91753..00000000 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.ComponentModel; - -namespace ComputeSharp.__Internals; - -/// -/// A base representing a metadatadata loader for a shader being dispatched. -/// -[EditorBrowsable(EditorBrowsableState.Never)] -[Obsolete("This interface is not intended to be used directly by user code")] -public interface IDispatchMetadataLoader -{ - /// - /// Loads an opaque metadata handle from the given shader metadata. - /// - /// The serialized metadata for the current shader. - /// The sequence of resource descriptors for the current shader. - /// The resulting opaque metadata handle. - void LoadMetadataHandle(ReadOnlySpan serializedMetadata, ReadOnlySpan resourceDescriptors, out IntPtr result); -} \ No newline at end of file diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs index 2d00eb1b..df79288c 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs @@ -72,15 +72,4 @@ public interface IShader [Obsolete("This method is not intended to be called directly by user code")] void LoadDispatchData(ref TLoader loader, GraphicsDevice device, int x, int y, int z) where TLoader : struct, IDispatchDataLoader; - - /// - /// Loads an opaque metadata handle from the metadata of the current shader. - /// - /// The type of data loader being used. - /// The instance to use to load the data. - /// The resulting opaque metadata handle. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] - void LoadDispatchMetadata(ref TLoader loader, out IntPtr result) - where TLoader : struct, IDispatchMetadataLoader; } \ No newline at end of file diff --git a/src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs b/src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs deleted file mode 100644 index c43be70d..00000000 --- a/src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using ComputeSharp.Shaders.Extensions; -using ComputeSharp.__Internals; -using TerraFX.Interop.DirectX; -using TerraFX.Interop.Windows; - -#pragma warning disable CS0618 - -namespace ComputeSharp.Shaders.Dispatching; - -/// -/// A data loader for compute shaders. -/// -internal readonly unsafe struct ShaderDispatchMetadataLoader : IDispatchMetadataLoader -{ - /// - /// The object in use. - /// - private readonly ID3D12Device* d3D12Device; - - /// - /// Creates a new instance. - /// - /// The object to use. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal ShaderDispatchMetadataLoader(ID3D12Device* d3D12Device) - { - this.d3D12Device = d3D12Device; - } - - /// - public unsafe void LoadMetadataHandle(ReadOnlySpan serializedMetadata, ReadOnlySpan resourceDescriptors, out IntPtr result) - { - default(ArgumentException).ThrowIf(serializedMetadata.Length != 5, nameof(serializedMetadata)); - - fixed (IntPtr* p = &result) - { - *(ComPtr*)p = this.d3D12Device->CreateRootSignature( - MemoryMarshal.Read(serializedMetadata), - MemoryMarshal.Cast(resourceDescriptors), - MemoryMarshal.Read(serializedMetadata.Slice(4))); - } - } -} \ No newline at end of file diff --git a/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs b/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs index 59846b79..b9883cf6 100644 --- a/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs +++ b/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs @@ -1,10 +1,12 @@ using System; +using System.Buffers; using System.Runtime.CompilerServices; -using ComputeSharp.Shaders.Dispatching; using ComputeSharp.Shaders.Extensions; +using ComputeSharp.Interop; using ComputeSharp.__Internals; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; +using static TerraFX.Interop.DirectX.D3D12_DESCRIPTOR_RANGE_FLAGS; #pragma warning disable CS0618 @@ -14,7 +16,7 @@ namespace ComputeSharp.Shaders.Loading; /// A responsible for performing all the necessary operations to compile and load shader data. /// /// The type of compute shader to load. -internal static class PipelineDataLoader +internal static unsafe class PipelineDataLoader where T : struct, IShader { /// @@ -37,19 +39,16 @@ internal static class PipelineDataLoader /// /// The to use to run the shader. /// The resulting instance to use to run the shader. - [MethodImpl(MethodImplOptions.NoInlining)] - private static unsafe PipelineData CreatePipelineData(GraphicsDevice device) + private static PipelineData CreatePipelineData(GraphicsDevice device) { PipelineData pipelineData; using (ComPtr d3D12RootSignature = default) { - ShaderDispatchMetadataLoader metadataLoader = new(device.D3D12Device); + CreateD3D12RootSignature(device.D3D12Device, d3D12RootSignature.GetAddressOf()); Unsafe.SkipInit(out T shader); - shader.LoadDispatchMetadata(ref metadataLoader, out *(IntPtr*)&d3D12RootSignature); - ReadOnlyMemory hlslBytecode = shader.HlslBytecode; fixed (byte* hlslBytecodePtr = hlslBytecode.Span) @@ -70,4 +69,52 @@ internal static class PipelineDataLoader return pipelineData; } + + /// + /// Creates a D3D12 root signature for the current shader type. + /// + /// The target to use to create the root signature. + /// The allocated instance. + private static void CreateD3D12RootSignature(ID3D12Device* d3D12Device, ID3D12RootSignature** d3D12RootSignature) + { + Unsafe.SkipInit(out T shader); + + ReadOnlySpan resourceDescriptorRanges = shader.ResourceDescriptorRanges.Span; + + D3D12_DESCRIPTOR_RANGE1[]? d3D12DescriptorRangesArray = null; + + // Create the span and optional array of D3D12_DESCRIPTOR_RANGE1 objects + Span d3D12DescriptorRanges = resourceDescriptorRanges.Length <= 8 + ? stackalloc D3D12_DESCRIPTOR_RANGE1[8] + : d3D12DescriptorRangesArray = ArrayPool.Shared.Rent(resourceDescriptorRanges.Length); + + // Ensure the size has the right length to match the available descriptor ranges + d3D12DescriptorRanges = d3D12DescriptorRanges.Slice(0, resourceDescriptorRanges.Length); + + // Initialize the D3D12_DESCRIPTOR_RANGE1 values from the shader descriptor ranges + for (int i = 0; i < resourceDescriptorRanges.Length; i++) + { + ref readonly ResourceDescriptorRange resourceDescriptorRange = ref resourceDescriptorRanges[i]; + ref D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange = ref d3D12DescriptorRanges[i]; + + d3D12DescriptorRange.RangeType = (D3D12_DESCRIPTOR_RANGE_TYPE)resourceDescriptorRange.Type; + d3D12DescriptorRange.NumDescriptors = 1; + d3D12DescriptorRange.BaseShaderRegister = resourceDescriptorRange.Register; + d3D12DescriptorRange.RegisterSpace = 0; + d3D12DescriptorRange.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE; + d3D12DescriptorRange.OffsetInDescriptorsFromTableStart = D3D12.D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; + } + + // Create the D3D12 root signature + *d3D12RootSignature = d3D12Device->CreateRootSignature( + shader.ConstantBufferSize, + d3D12DescriptorRanges, + shader.IsStaticSamplerRequired).Get(); + + // Return the array to the pool if no exceptions have been thrown + if (d3D12DescriptorRangesArray is not null) + { + ArrayPool.Shared.Return(d3D12DescriptorRangesArray); + } + } } \ No newline at end of file From f63d47f62b012c267eaaa5175e3b0b5ea5d03207 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 14 Oct 2023 11:42:32 +0200 Subject: [PATCH 7/7] Minor code refactoring to PipelineDataLoader --- .../Shaders/Loading/PipelineDataLoader{T}.cs | 33 ++++++++++++------- 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs b/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs index b9883cf6..aa24d6ff 100644 --- a/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs +++ b/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs @@ -44,21 +44,12 @@ internal static unsafe class PipelineDataLoader PipelineData pipelineData; using (ComPtr d3D12RootSignature = default) + using (ComPtr d3D12PipelineState = default) { CreateD3D12RootSignature(device.D3D12Device, d3D12RootSignature.GetAddressOf()); + CreateD3D12PipelineState(device.D3D12Device, d3D12RootSignature.Get(), d3D12PipelineState.GetAddressOf()); - Unsafe.SkipInit(out T shader); - - ReadOnlyMemory hlslBytecode = shader.HlslBytecode; - - fixed (byte* hlslBytecodePtr = hlslBytecode.Span) - { - D3D12_SHADER_BYTECODE d3D12ShaderBytecode = new(hlslBytecodePtr, (nuint)hlslBytecode.Length); - - using ComPtr d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), d3D12ShaderBytecode); - - pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get()); - } + pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get()); } // Add the pipeline to the cache for this type @@ -117,4 +108,22 @@ internal static unsafe class PipelineDataLoader ArrayPool.Shared.Return(d3D12DescriptorRangesArray); } } + + /// + /// Creates a D3D12 pipeline state for the current shader type. + /// + /// The target to use to create the root signature. + /// The input value to use. + /// The resulting instance. + private static void CreateD3D12PipelineState(ID3D12Device* d3D12Device, ID3D12RootSignature* d3D12RootSignature, ID3D12PipelineState** d3D12PipelineState) + { + Unsafe.SkipInit(out T shader); + + fixed (byte* hlslBytecodePtr = shader.HlslBytecode.Span) + { + D3D12_SHADER_BYTECODE d3D12ShaderBytecode = new(hlslBytecodePtr, (nuint)shader.HlslBytecode.Length); + + *d3D12PipelineState = d3D12Device->CreateComputePipelineState(d3D12RootSignature, d3D12ShaderBytecode); + } + } } \ No newline at end of file