From 640e612464ca43e635487c2062ba8fc28a235bd9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 10 May 2021 18:05:54 +0200 Subject: [PATCH] Initial draft support for 2D texture sampling --- .../IComputeShaderSourceGenerator.cs | 12 +++- .../Mappings/HlslKnownMembers.cs | 23 +++++++ .../SyntaxRewriters/HlslSourceRewriter.cs | 69 ++++++++++++++----- .../IComputeShaderSourceAttribute.cs | 8 +++ .../Interfaces/IReadOnlyTexture2D{TPixel}.cs | 15 ++++ .../Resources/ReadOnlyTexture2D{T,TPixel}.cs | 8 ++- .../Resources/ReadOnlyTexture3D{T,TPixel}.cs | 2 +- .../Resources/ReadWriteTexture2D{T,TPixel}.cs | 2 +- .../Resources/ReadWriteTexture3D{T,TPixel}.cs | 2 +- .../Extensions/ID3D12DeviceExtensions.cs | 22 +++++- .../Shaders/Renderer/HlslShaderRenderer.cs | 31 ++++++--- .../Renderer/Models/HlslResourceInfo.cs | 30 ++++---- src/ComputeSharp/Shaders/ShaderRunner{T}.cs | 2 +- .../Shaders/Translation/ShaderLoader{T}.cs | 20 ++++++ 14 files changed, 194 insertions(+), 52 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index 5c2b85ae..37362f1b 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -86,7 +86,8 @@ namespace ComputeSharp.SourceGenerators var implicitTextureField = isComputeShader ? default((string, string)?) : (HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!), "__outputTexture"); var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray(); var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); - var (entryPoint, processedMethods, forwardDeclarations) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); + var (entryPoint, processedMethods, forwardDeclarations, isSamplerUsed) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); + var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); var processedConstants = GetProcessedConstants(constantDefinitions); var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); @@ -100,6 +101,7 @@ namespace ComputeSharp.SourceGenerators AttributeArgument(TypeOfExpression(IdentifierName(structDeclarationSymbol.ToDisplayString()))), AttributeArgument(ArrayExpression(processedTypes)), AttributeArgument(ArrayExpression(implicitTextureField)), + AttributeArgument(ArrayExpression(implicitSamplerField)), AttributeArgument(NestedArrayExpression(processedMembers)), AttributeArgument(ArrayExpression(forwardDeclarations)), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(entryPoint))), @@ -319,7 +321,7 @@ namespace ComputeSharp.SourceGenerators /// Indicates whether or not represents a compute shader. /// A sequence of processed methods in , and the entry point. [Pure] - private static (string EntryPoint, IEnumerable Methods, IEnumerable Declarations) GetProcessedMethods( + private static (string EntryPoint, IEnumerable Methods, IEnumerable Declarations, bool IsSamplerUser) GetProcessedMethods( GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, @@ -338,6 +340,7 @@ namespace ComputeSharp.SourceGenerators string? entryPoint = null; List methods = new(); List declarations = new(); + bool isSamplerUsed = false; foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) { @@ -367,6 +370,9 @@ namespace ComputeSharp.SourceGenerators // Rewrite the method syntax tree MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); + // Track the implicit sampler, if used + isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed; + // Emit the extracted local functions first foreach (var localFunction in shaderSourceRewriter.LocalFunctions) { @@ -399,7 +405,7 @@ namespace ComputeSharp.SourceGenerators declarations.Add(staticMethod.AsDefinition().NormalizeWhitespace().ToFullString()); } - return (entryPoint!, methods, declarations); + return (entryPoint!, methods, declarations, isSamplerUsed); } /// diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs index 97011619..8c6b0ebb 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs @@ -33,6 +33,17 @@ namespace ComputeSharp.SourceGenerators.Mappings [$"ComputeSharp.IReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3" }; + /// + /// The mapping of supported known samplers to HLSL resource type names. + /// + private static readonly IReadOnlyDictionary KnownResourceSamplers = new Dictionary + { + [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", + [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(Float2).FullName}]"] = null, + [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", + [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(Float2).FullName}]"] = null + }; + /// /// The mapping of supported known size accessors for HLSL resource types. /// @@ -389,6 +400,18 @@ namespace ComputeSharp.SourceGenerators.Mappings return KnownResourceIndexers.TryGetValue(name, out mapped); } + /// + /// Tries to get the mapped HLSL-compatible sampler resource type name for the input indexer name. + /// + /// The input fully qualified indexer name. + /// The mapped type name, if one is found. + /// The HLSL-compatible type name that can be used in an HLSL shader for the given sampler. + [Pure] + public static bool TryGetMappedResourceSamplerAccessType(string name, out string? mapped) + { + return KnownResourceSamplers.TryGetValue(name, out mapped); + } + /// /// Tries to get the mapped HLSL-compatible indexer vector type name for the input indexer name. /// diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs index 2156d71c..2fae4740 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs @@ -21,6 +21,26 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter { + /// + /// The instance with semantic info on the target syntax tree. + /// + protected readonly SemanticModelProvider SemanticModel; + + /// + /// The collection of discovered custom types. + /// + protected readonly ICollection DiscoveredTypes; + + /// + /// The collection of discovered constant definitions. + /// + protected readonly IDictionary ConstantDefinitions; + + /// + /// The current generator context in use. + /// + protected readonly GeneratorExecutionContext Context; + /// /// Creates a new instance with the specified parameters. /// @@ -41,24 +61,9 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters } /// - /// The instance with semantic info on the target syntax tree. + /// Gets whether or not the shader uses a texture sampler at least once. /// - protected readonly SemanticModelProvider SemanticModel; - - /// - /// The collection of discovered custom types. - /// - protected readonly ICollection DiscoveredTypes; - - /// - /// The collection of discovered constant definitions. - /// - protected readonly IDictionary ConstantDefinitions; - - /// - /// The current generator context in use. - /// - protected readonly GeneratorExecutionContext Context; + public bool IsSamplerUsed { get; private set; } /// public override SyntaxNode VisitCastExpression(CastExpressionSyntax node) @@ -201,8 +206,8 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { string propertyName = operation.Property.GetFullMetadataName(); - // Rewrite texture resource indices taking vectors into individual indices as per HLSL spec. - // For instance: texture[ThreadIds.XY] will be rewritten as texture[ThreadIds.X, ThreadIds.Y]. + // Rewrite texture resource indices taking individual indices a vector argument, as per HLSL spec. + // For instance: texture[ThreadIds.X, ThreadIds.Y] will be rewritten as texture[int2(ThreadIds.X, ThreadIds.Y)]. if (HlslKnownMembers.TryGetMappedResourceIndexerTypeName(propertyName, out string? mapping)) { var index = InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments)); @@ -210,6 +215,32 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return updatedNode.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(Argument(index)))); } + // Rewrite texture resource sampled accesses, if needed + if (HlslKnownMembers.TryGetMappedResourceSamplerAccessType(propertyName, out mapping)) + { + IsSamplerUsed = true; + + // Get the syntax for the argument syntax transformation as described above + ArgumentSyntax coordinateSyntax = mapping switch + { + not null => Argument(InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments))), + null => updatedNode.ArgumentList.Arguments[0] + }; + + // Transform an indexer syntax into a sampling call with the implicit static linear sampler. + // For instance: texture[uv] will be rewritten as texture.SampleLevel(__sampler, uv, 0). + return + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + updatedNode.Expression, + IdentifierName("SampleLevel"))) + .AddArgumentListArguments( + Argument(IdentifierName("__sampler")), + coordinateSyntax, + Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))); + } + // If the current property is a swizzled matrix indexer, ensure all the arguments are constants, and rewrite // the property access to the corresponding HLSL syntax. For instance, m[M11, M12] will become m._m00_m01. if (HlslKnownMembers.IsKnownMatrixIndexer(propertyName)) diff --git a/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs b/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs index 169f78cb..d33a491b 100644 --- a/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs +++ b/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs @@ -23,6 +23,7 @@ namespace ComputeSharp.__Internals /// The type of the current shader. /// The collection of custom types. /// The implicit texture field info, if present. + /// The implicit texture sampler field info, if present. /// The mapped collection of shader fields. /// The forward declarations for static methods. /// The source code for the method. @@ -34,6 +35,7 @@ namespace ComputeSharp.__Internals Type shaderType, string[] types, string[]? implicitTextureField, + string[]? implicitSamplerFields, object[] fields, string[] forwardDeclarations, string executeMethod, @@ -45,6 +47,7 @@ namespace ComputeSharp.__Internals ShaderType = shaderType; Types = types; ImplicitTextureField = implicitTextureField is null ? null : (implicitTextureField[0], implicitTextureField[1]); + ImplicitSamplerField = implicitSamplerFields is null ? null : (implicitSamplerFields[0], implicitSamplerFields[1]); Fields = fields.Cast().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2])); ForwardDeclarations = forwardDeclarations; ExecuteMethod = executeMethod; @@ -69,6 +72,11 @@ namespace ComputeSharp.__Internals /// internal (string Name, string Type)? ImplicitTextureField { get; } + /// + /// Gets the mapping for the implicit sampler field, if necessary. + /// + internal (string Name, string Type)? ImplicitSamplerField { get; } + /// /// Gets the mapping of field names. /// diff --git a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs index d0504e42..c668331f 100644 --- a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs @@ -32,5 +32,20 @@ /// The coordinates of the value to get. /// This API can only be used from a compute shader, and will always throw if used anywhere else. TPixel this[Int2 xy] { get; } + + /// + /// Gets a single value from the current readonly texture with linear sampling. + /// + /// The horizontal normalized offset of the value to get. + /// The vertical normalized offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + TPixel this[float u, float v] { get; } + + /// + /// Gets a single value from the current readonly texture with linear sampling. + /// + /// The normalized coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + TPixel this[Float2 uv] { get; } } } diff --git a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs index 47b8b62e..42b5c06b 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs @@ -39,10 +39,16 @@ namespace ComputeSharp /// public TPixel this[Int2 xy] => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture2D)}[{typeof(Int2)}]"); + /// + public TPixel this[float u, float v] => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture2D)}[{typeof(float)}, {typeof(float)}]"); + + /// + public TPixel this[Float2 uv] => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture2D)}[{typeof(Float2)}]"); + /// public override string ToString() { - return $"ComputeSharp.ReadOnlyTexture2D<{typeof(T)},{typeof(TPixel)}>[{Width}, {Height}]"; + return $"ComputeSharp.ReadOnlyTexture2D<{typeof(T)}, {typeof(TPixel)}>[{Width}, {Height}]"; } } } diff --git a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs index 95ba8bc7..29ea0ff1 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs @@ -43,7 +43,7 @@ namespace ComputeSharp /// public override string ToString() { - return $"ComputeSharp.ReadOnlyTexture3D<{typeof(T)},{nameof(TPixel)}>[{Width}, {Height}, {Depth}]"; + return $"ComputeSharp.ReadOnlyTexture3D<{typeof(T)}, {nameof(TPixel)}>[{Width}, {Height}, {Depth}]"; } } } diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs index f8238ac1..84acb879 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs @@ -42,7 +42,7 @@ namespace ComputeSharp /// public override string ToString() { - return $"ComputeSharp.ReadWriteTexture2D<{typeof(T)},{typeof(TPixel)}>[{Width}, {Height}]"; + return $"ComputeSharp.ReadWriteTexture2D<{typeof(T)}, {typeof(TPixel)}>[{Width}, {Height}]"; } } } diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs index b836afd6..cb452315 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs @@ -43,7 +43,7 @@ namespace ComputeSharp /// public override string ToString() { - return $"ComputeSharp.ReadWriteTexture3D<{typeof(T)},{nameof(TPixel)}>[{Width}, {Height}, {Depth}]"; + return $"ComputeSharp.ReadWriteTexture3D<{typeof(T)}, {nameof(TPixel)}>[{Width}, {Height}, {Depth}]"; } } } diff --git a/src/ComputeSharp/Shaders/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp/Shaders/Extensions/ID3D12DeviceExtensions.cs index fe254f94..c1fa6237 100644 --- a/src/ComputeSharp/Shaders/Extensions/ID3D12DeviceExtensions.cs +++ b/src/ComputeSharp/Shaders/Extensions/ID3D12DeviceExtensions.cs @@ -17,12 +17,14 @@ namespace ComputeSharp.Shaders.Extensions /// The target to use to create the root signature. /// The number of 32 bit root constants to load. /// The input descriptor ranges for the signature to create. + /// Indicates whether or not a static sampler is used. /// A pointer to the newly allocated instance. /// Thrown when the creation of the root signature fails. public static ComPtr CreateRootSignature( this ref ID3D12Device d3D12Device, int d3D12Root32BitConstantsCount, - ReadOnlySpan d3D12DescriptorRanges1) + ReadOnlySpan d3D12DescriptorRanges1, + bool isStaticSamplerUsed) { using ComPtr d3D3Blob = default; using ComPtr d3D3BlobError = default; @@ -42,11 +44,25 @@ namespace ComputeSharp.Shaders.Extensions D3D12_ROOT_PARAMETER1.InitAsDescriptorTable(out d3D12RootParameters1[i + 1], 1, d3D12DescriptorRange1 + i); } + D3D12_STATIC_SAMPLER_DESC d3D12SamplerDescription; + + // Create the linear static sampler if needed + if (isStaticSamplerUsed) + { + D3D12_STATIC_SAMPLER_DESC.Init( + out d3D12SamplerDescription, + shaderRegister: 0, + filter: D3D12_FILTER.D3D12_FILTER_MIN_MAG_MIP_LINEAR, + comparisonFunc: D3D12_COMPARISON_FUNC.D3D12_COMPARISON_FUNC_NEVER); + } + // Root signature description wrapping the packed collection of root parameters D3D12_VERSIONED_ROOT_SIGNATURE_DESC.Init_1_1( out D3D12_VERSIONED_ROOT_SIGNATURE_DESC d3D12VersionedRootSignatureDescription, - (uint)d3D12DescriptorRanges1.Length + 1, - d3D12RootParameters1); + numParameters: (uint)d3D12DescriptorRanges1.Length + 1, + _pParameters: d3D12RootParameters1, + numStaticSamplers: isStaticSamplerUsed ? 1u : 0u, + _pStaticSamplers: isStaticSamplerUsed ? &d3D12SamplerDescription : null); // Serialize the root signature from the data just computed. When this is done // we just work with the resulting blobs, so the input data can be unpinned. diff --git a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs index 3af11b8e..754709ee 100644 --- a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs +++ b/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs @@ -102,25 +102,25 @@ namespace ComputeSharp.Shaders.Renderer builder.AppendLine('}'); - // Buffers - foreach (var buffer in info.HlslResourceInfo) + // Resources + foreach (var resource in info.HlslResourceInfo) { builder.AppendLine(); - switch (buffer) + switch (resource) { // Constant buffer go to cbuffer fields with a dummy local case HlslResourceInfo.Constant _: builder.Append("cbuffer _"); - builder.Append(buffer.FieldName); + builder.Append(resource.FieldName); builder.Append(" : register(b"); - builder.Append(buffer.BufferIndex.ToString()); + builder.Append(resource.RegisterIndex.ToString()); builder.AppendLine(')'); builder.AppendLine('{'); builder.Append(" "); - builder.Append(buffer.FieldType); + builder.Append(resource.FieldType); builder.Append(' '); - builder.Append(buffer.FieldName); + builder.Append(resource.FieldName); builder.AppendLine("[2];"); builder.AppendLine('}'); break; @@ -132,12 +132,23 @@ namespace ComputeSharp.Shaders.Renderer case HlslResourceInfo.ReadWrite _: registerId = 'u'; StructuredBuffer: - builder.Append(buffer.FieldType); + builder.Append(resource.FieldType); builder.Append(' '); - builder.Append(buffer.FieldName); + builder.Append(resource.FieldName); builder.Append(" : register("); builder.Append(registerId); - builder.Append(buffer.BufferIndex.ToString()); + builder.Append(resource.RegisterIndex.ToString()); + builder.AppendLine(");"); + break; + + // Texture samplers + case HlslResourceInfo.Sampler _: + builder.Append(resource.FieldType); + builder.Append(' '); + builder.Append(resource.FieldName); + builder.Append(" : register("); + builder.Append('s'); + builder.Append(resource.RegisterIndex.ToString()); builder.AppendLine(");"); break; } diff --git a/src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs b/src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs index 455b287d..af71a082 100644 --- a/src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs +++ b/src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs @@ -1,37 +1,43 @@ -#pragma warning disable CS1572, CS1573 - -namespace ComputeSharp.Shaders.Renderer.Models +namespace ComputeSharp.Shaders.Renderer.Models { /// - /// A model that contains info on a shader typed resource field. + /// A model that contains info on a shader resource field. /// /// The type of the current field in the HLSL shader. /// The name to use for the current field. - /// The register index to bind the resource to. - internal abstract record HlslResourceInfo(string FieldType, string FieldName, int BufferIndex) + /// The register index to bind the resource to. + internal abstract record HlslResourceInfo(string FieldType, string FieldName, int RegisterIndex) : CapturedFieldInfo(FieldType, FieldName) { /// /// A model that represents a captured constant buffer in a shader. /// /// - public sealed record Constant(string FieldType, string FieldName, int BufferIndex) - : HlslResourceInfo(FieldType, FieldName, BufferIndex); + public sealed record Constant(string FieldType, string FieldName, int RegisterIndex) + : HlslResourceInfo(FieldType, FieldName, RegisterIndex); /// /// A model that represents a captured readonly typed resource in a shader. /// Maps to either or . /// /// - public sealed record ReadOnly(string FieldType, string FieldName, int BufferIndex) - : HlslResourceInfo(FieldType, FieldName, BufferIndex); + public sealed record ReadOnly(string FieldType, string FieldName, int RegisterIndex) + : HlslResourceInfo(FieldType, FieldName, RegisterIndex); /// /// A model that represents a captured writeable buffer in a shader. /// Maps to either or . /// /// - public sealed record ReadWrite(string FieldType, string FieldName, int BufferIndex) - : HlslResourceInfo(FieldType, FieldName, BufferIndex); + public sealed record ReadWrite(string FieldType, string FieldName, int RegisterIndex) + : HlslResourceInfo(FieldType, FieldName, RegisterIndex); + + /// + /// A model that represents a captured sampler in a shader. + /// This resource type doesn't have a mapping to a public API. + /// + /// + public sealed record Sampler(string FieldType, string FieldName, int RegisterIndex) + : HlslResourceInfo(FieldType, FieldName, RegisterIndex); } } diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs index 908c0c67..dc2e4ddc 100644 --- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs @@ -287,7 +287,7 @@ namespace ComputeSharp.Shaders [MethodImpl(MethodImplOptions.NoInlining)] private static unsafe void CreatePipelineData(GraphicsDevice device, in CachedShader shaderData, out PipelineData pipelineData) { - using ComPtr d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12Root32BitConstantsCount, shaderData.Loader.D3D12DescriptorRanges1); + using ComPtr d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12Root32BitConstantsCount, shaderData.Loader.D3D12DescriptorRanges1, shaderData.Loader.IsStaticSamplerUsed); using ComPtr d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), shaderData.Bytecode.D3D12ShaderBytecode); pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get()); diff --git a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs index d46ee25a..a13586e1 100644 --- a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs @@ -45,6 +45,11 @@ namespace ComputeSharp.Shaders.Translation /// private uint readWriteBuffersCount; + /// + /// The number of samplers to define in the shader. + /// + private uint samplersCount; + /// /// The array of items that are required to load the captured values. /// @@ -101,6 +106,11 @@ namespace ComputeSharp.Shaders.Translation /// public bool IsComputeShader { get; private set; } + /// + /// Gets whether or not the current shader requires access to a static sampler. + /// + public bool IsStaticSamplerUsed { get; private set; } + /// public IReadOnlyList HlslResourceInfo => this.hlslResourceInfo; @@ -205,6 +215,16 @@ namespace ComputeSharp.Shaders.Translation ThrowHelper.ThrowInvalidOperationException("The shader body must contain at least one field"); } + // Add the implicit sampler descriptor if necessary + if (Attribute.ImplicitSamplerField is not null) + { + (string hlslType, string hlslName) = Attribute.ImplicitSamplerField!.Value; + + this.hlslResourceInfo.Add(new HlslResourceInfo.Sampler(hlslType, hlslName, (int)this.samplersCount++)); + + IsStaticSamplerUsed = true; + } + // Inspect the captured fields foreach (FieldInfo fieldInfo in shaderFields) {