From e432a197a0080e4ad2232011f46751cc565d2494 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 9 Jul 2021 16:36:30 +0200 Subject: [PATCH] Added initial BuildHlslString source generator implementation Not actually working yet, pending other changes to pipeline creation --- .../IComputeShaderSourceGenerator.cs | 353 +++++++++++++++++- .../Mappings/HlslKnownTypes.cs | 31 ++ .../ShaderMethodSourceGenerator.cs | 5 +- .../Interfaces/__Internals/IShader{TSelf}.cs | 13 +- .../Shaders/Renderer/HlslShaderRenderer.cs | 168 +-------- .../__Internals/ArrayPoolStringBuilder.cs | 169 +++++++++ src/ComputeSharp/Shaders/ShaderRunner{T}.cs | 18 +- .../Translation/Interop/IDxcBlobObject.cs | 4 +- .../Shaders/Translation/ShaderLoader{T}.cs | 9 - 9 files changed, 561 insertions(+), 209 deletions(-) create mode 100644 src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index e1d257a2..abc54d44 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; @@ -16,6 +17,7 @@ using Microsoft.CodeAnalysis.Text; using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper; using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; #pragma warning disable CS0618 @@ -83,7 +85,7 @@ namespace ComputeSharp.SourceGenerators // Explore the syntax tree and extract the processed info var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); var isComputeShader = pixelShaderSymbol is null; - var implicitTextureField = isComputeShader ? default((string, string)?) : (HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!), "__outputTexture"); + var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray(); var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); var (entryPoint, processedMethods, forwardDeclarations, isSamplerUsed) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); @@ -92,6 +94,22 @@ namespace ComputeSharp.SourceGenerators var processedConstants = GetProcessedConstants(constantDefinitions); var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); + GenerateRenderMethod( + context, + structDeclaration, + structDeclarationSymbol, + processedConstants, + staticFields, + processedTypes, + isComputeShader, + processedMembers, + implicitTextureType, + isSamplerUsed, + sharedBuffers, + forwardDeclarations, + processedMethods, + entryPoint); + // Create the compilation unit with the source attribute var source = CompilationUnit().AddUsings( @@ -99,16 +117,16 @@ namespace ComputeSharp.SourceGenerators AttributeList(SingletonSeparatedList( Attribute(IdentifierName(typeof(IComputeShaderSourceAttribute).FullName)).AddArgumentListArguments( 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))), - AttributeArgument(ArrayExpression(processedMethods)), - AttributeArgument(NestedArrayExpression(processedConstants)), - AttributeArgument(NestedArrayExpression(staticFields)), - AttributeArgument(NestedArrayExpression(sharedBuffers))))) + AttributeArgument(ArrayExpression(Array.Empty())), // TODO + AttributeArgument(ArrayExpression(Array.Empty())), // TODO + AttributeArgument(ArrayExpression(Array.Empty())), // TODO + AttributeArgument(NestedArrayExpression(Array.Empty())), // TODO + AttributeArgument(ArrayExpression(Array.Empty())), // TODO + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(""))), // TODO + AttributeArgument(ArrayExpression(Array.Empty())), // TODO + AttributeArgument(NestedArrayExpression(Array.Empty())), // TODO + AttributeArgument(NestedArrayExpression(Array.Empty())), // TODO + AttributeArgument(NestedArrayExpression(Array.Empty()))))) // TODO .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) .NormalizeWhitespace() @@ -127,7 +145,7 @@ namespace ComputeSharp.SourceGenerators /// Indicates whether or not represents a compute shader. /// A sequence of captured fields in . [Pure] - private static IEnumerable> GetProcessedFields( + private static IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> GetProcessedFields( GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, ICollection types, @@ -176,7 +194,8 @@ namespace ComputeSharp.SourceGenerators continue; } - else if (!HlslKnownTypes.IsKnownHlslType(metadataName)) + else if (typeSymbol.IsUnmanagedType && + !HlslKnownTypes.IsKnownHlslType(metadataName)) { // Track the type if it's a custom struct types.Add(typeSymbol); @@ -187,7 +206,7 @@ namespace ComputeSharp.SourceGenerators _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); // Yield back the current mapping for the name (if the name used a reserved keyword) - yield return new[] { fieldSymbol.Name, mapping ?? fieldSymbol.Name, typeName }; + yield return (fieldSymbol, mapping ?? fieldSymbol.Name, typeName); } // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource @@ -208,7 +227,7 @@ namespace ComputeSharp.SourceGenerators /// The collection of discovered constant definitions. /// A sequence of static constant fields in . [Pure] - private static IEnumerable> GetStaticFields( + private static IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( GeneratorExecutionContext context, SemanticModelProvider semanticModel, StructDeclarationSyntax structDeclaration, @@ -256,7 +275,7 @@ namespace ComputeSharp.SourceGenerators string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace().ToFullString(); - yield return new[] { mapping ?? fieldSymbol.Name, typeDeclaration, assignment }; + yield return (mapping ?? fieldSymbol.Name, typeDeclaration, assignment); } } } @@ -295,7 +314,7 @@ namespace ComputeSharp.SourceGenerators continue; } - + int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); @@ -414,14 +433,14 @@ namespace ComputeSharp.SourceGenerators /// The collection of discovered constant definitions. /// A sequence of discovered constants to declare in the shader. [Pure] - internal static IEnumerable> GetProcessedConstants(IReadOnlyDictionary constantDefinitions) + internal static IEnumerable<(string Name, string Value)> GetProcessedConstants(IReadOnlyDictionary constantDefinitions) { foreach (var constant in constantDefinitions) { var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; - yield return new string[] { constantName, constant.Value }; + yield return (constantName, constant.Value); } } @@ -475,6 +494,300 @@ namespace ComputeSharp.SourceGenerators context.ReportDiagnostic(DiagnosticDescriptors.PropertyDeclaration, propertySymbol); } } + + private static void GenerateRenderMethod( + GeneratorExecutionContext context, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + IEnumerable<(string Name, string Value)> definedConstants, + IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields, + IEnumerable declaredTypes, + bool isComputeShader, + IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields, + string? implicitTextureType, + bool isSamplerUsed, + IEnumerable<(string Name, string Type, int? Count)> sharedBuffers, + IEnumerable? forwardDeclarations, + IEnumerable processedMethods, + string executeMethod) + { + string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); + string structName = structDeclaration.Identifier.Text; + SyntaxTokenList structModifiers = structDeclaration.Modifiers; + IEnumerable bodyStatements = GenerateRenderMethodBody( + definedConstants, + staticFields, + declaredTypes, + isComputeShader, + instanceFields, + implicitTextureType, + isSamplerUsed, + sharedBuffers, + forwardDeclarations, + processedMethods, + executeMethod); + + // Create the partial shader type declaration with the hashcode interface method implementation. + // This code produces a struct declaration as follows: + // + // public struct ShaderType : IShader + // { + // [GeneratedCode("...", "...")] + // [DebuggerNonUserCode] + // [ExcludeFromCodeCoverage] + // [EditorBrowsable(EditorBrowsableState.Never)] + // [Obsolete("This method is not intended to be called directly by user code")] + // public readonly void BuildHlslString(ref ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) + // { + // + // } + // } + var structDeclarationSyntax = + StructDeclaration(structName).WithModifiers(structModifiers) + .AddBaseListTypes(SimpleBaseType( + GenericName(Identifier("IShader")) + .AddTypeArgumentListArguments(IdentifierName(structName)))).AddMembers( + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("BuildHlslString")) + .AddAttributeLists( + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderHashCodeGenerator).FullName))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderHashCodeGenerator).Assembly.GetName().Version.ToString())))))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( + AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( + AttributeArgument(LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal("This method is not intended to be used directly by user code"))))))) + .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword)) + .AddParameterListParameters( + Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("ArrayPoolStringBuilder")), + Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) + .WithBody(Block(bodyStatements))); + + TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; + + // Add all parent types in ascending order, if any + foreach (var parentType in structDeclaration.Ancestors().OfType()) + { + typeDeclarationSyntax = parentType + .WithMembers(SingletonList(typeDeclarationSyntax)) + .WithConstraintClauses(List()) + .WithBaseList(null) + .WithAttributeLists(List()) + .WithoutTrivia(); + } + + // Create a static method to create the combined hashcode for a given shader type. + // This code takes a block syntax and produces a compilation unit as follows: + // + // using System; + // using System.CodeDom.Compiler; + // using System.ComponentModel; + // using System.Diagnostics; + // using System.Diagnostics.CodeAnalysis; + // using ComputeSharp.__Internals; + // + // #pragma warning disable + // + // namespace + // { + // + // } + var source = + CompilationUnit().AddUsings( + UsingDirective(IdentifierName("System")), + UsingDirective(IdentifierName("System.CodeDom.Compiler")), + UsingDirective(IdentifierName("System.ComponentModel")), + UsingDirective(IdentifierName("System.Diagnostics")), + UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")), + UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddMembers( + NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax) + .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) + .NormalizeWhitespace() + .ToFullString(); + + // Add the method source attribute + context.AddSource("PREVIEW" + structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); + } + + private static IEnumerable GenerateRenderMethodBody( + IEnumerable<(string Name, string Value)> definedConstants, + IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields, + IEnumerable declaredTypes, + bool isComputeShader, + IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields, + string? implicitTextureType, + bool isSamplerUsed, + IEnumerable<(string Name, string Type, int? Count)> sharedBuffers, + IEnumerable? forwardDeclarations, + IEnumerable processedMethods, + string executeMethod) + { + // Header + yield return ParseStatement("builder.AppendLine(\"// ================================================\");"); + yield return ParseStatement("builder.AppendLine(\"// AUTO GENERATED\");"); + yield return ParseStatement("builder.AppendLine(\"// ================================================\");"); + yield return ParseStatement("builder.AppendLine(\"// This shader was created by ComputeSharp.\");"); + yield return ParseStatement("builder.AppendLine(\"// See: https://github.com/Sergio0694/ComputeSharp.\");"); + + // Group size constants + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement("builder.Append(\"#define __GroupSize__get_X \");"); + yield return ParseStatement("builder.AppendLine(threadsX.ToString());"); + yield return ParseStatement("builder.Append(\"#define __GroupSize__get_Y \");"); + yield return ParseStatement("builder.AppendLine(threadsY.ToString());"); + yield return ParseStatement("builder.Append(\"#define __GroupSize__get_Z \");"); + yield return ParseStatement("builder.AppendLine(threadsZ.ToString());"); + + // Define declarations + foreach (var (name, value) in definedConstants) + { + yield return ParseStatement($"builder.AppendLine(\"#define {name} {value}\");"); + } + + // Static fields + if (staticFields.Any()) + { + yield return ParseStatement("builder.AppendLine();"); + + foreach (var field in staticFields) + { + if (field.Assignment is string assignment) + { + yield return ParseStatement($"builder.AppendLine(\"{field.TypeDeclaration} {field.Name} = {assignment};\");"); + } + else + { + yield return ParseStatement($"builder.AppendLine(\"{field.TypeDeclaration} {field.Name};\");"); + } + } + } + + // Declared types + foreach (var type in declaredTypes) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"{type}\");"); + } + + // Captured variables + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement("builder.AppendLine(\"cbuffer _ : register(b0)\");"); + yield return ParseStatement("builder.AppendLine('{');"); + yield return ParseStatement("builder.AppendLine(\" uint __x;\");"); + yield return ParseStatement("builder.AppendLine(\" uint __y;\");"); + + if (isComputeShader) + { + yield return ParseStatement("builder.AppendLine(\" uint __z;\");"); + } + + // User-defined values + foreach (var instanceField in instanceFields) + { + if (instanceField.Symbol.Type.IsUnmanagedType) + { + yield return ParseStatement($"builder.AppendLine(\" {instanceField.HlslType} {instanceField.HlslName};\");"); + } + } + + yield return ParseStatement("builder.AppendLine('}');"); + + int + constantBuffersCount = 0, + readOnlyBuffersCount = 0, + readWriteBuffersCount = 0; + + // Optional implicit texture field + if (!isComputeShader) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});\");"); + } + + // Optional sampler field + if (isSamplerUsed) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement("builder.AppendLine(\"SamplerState __sampler : register(s);\");"); + } + + // Resources + foreach (var instanceField in instanceFields) + { + string metadataName = instanceField.Symbol.GetFullMetadataName(); + + if (HlslKnownTypes.IsConstantBufferType(metadataName)) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"cbuffer _{instanceField.HlslName} : register(b{constantBuffersCount++})\");"); + yield return ParseStatement("builder.AppendLine('{');"); + yield return ParseStatement($"builder.AppendLine(\" {instanceField.HlslType} {instanceField.HlslName}[2];\");"); + yield return ParseStatement("builder.AppendLine('}');"); + } + else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName)) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"{instanceField.HlslType} : register(t{readOnlyBuffersCount++});\");"); + } + else if (HlslKnownTypes.IsTypedResourceType(metadataName)) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"{instanceField.HlslType} : register(u{readWriteBuffersCount++});\");"); + } + } + + // Shared buffers + foreach (var sharedBuffer in sharedBuffers) + { + object count = (object?)sharedBuffer.Count ?? "threadsX * threadsY * threadsZ"; + + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"groupshared {sharedBuffer.Type} {sharedBuffer.Name} [{count}];\");"); + } + + // Forward declarations + if (forwardDeclarations is not null) + { + foreach (var forwardDeclaration in forwardDeclarations) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"{forwardDeclaration}\");"); + } + } + + // Captured methods + if (processedMethods is not null) + { + foreach (var method in processedMethods) + { + yield return ParseStatement("builder.AppendLine();"); + yield return + ExpressionStatement( + InvocationExpression( + MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("AppendLine"))) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(method))))); + } + } + + // Entry point + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement("builder.AppendLine(\"[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]\");"); + yield return + ExpressionStatement( + InvocationExpression( + MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("AppendLine"))) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(executeMethod))))); + } } } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 1c7a0751..468a1e56 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -101,6 +101,16 @@ namespace ComputeSharp.SourceGenerators.Mappings return knownTypes; } + /// + /// Checks whether or not a given type name matches a constant buffer type. + /// + /// The input type name to check. + /// Whether or not represents a constant buffer type. + public static bool IsConstantBufferType(string typeName) + { + return typeName == "ComputeSharp.ConstantBuffer`1"; + } + /// /// Checks whether or not a given type name matches a structured buffer type. /// @@ -118,6 +128,27 @@ namespace ComputeSharp.SourceGenerators.Mappings }; } + /// + /// Checks whether or not a given type name matches a readonly typed resource type. + /// + /// The input type name to check. + /// Whether or not represents a readonly typed resource type. + public static bool IsReadOnlyTypedResourceType(string typeName) + { + switch (typeName) + { + case "ComputeSharp.ReadOnlyBuffer`1": + case "ComputeSharp.ReadOnlyTexture2D`1": + case "ComputeSharp.ReadOnlyTexture2D`2": + case "ComputeSharp.ReadOnlyTexture3D`1": + case "ComputeSharp.ReadOnlyTexture3D`2": + case "ComputeSharp.IReadOnlyTexture2D`1": + case "ComputeSharp.IReadOnlyTexture3D`1": + return true; + default: return false; + }; + } + /// /// Checks whether or not a given type name matches a typed resource type. /// diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 7ea87bdf..a9f4f412 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Text; @@ -83,7 +84,7 @@ namespace ComputeSharp.SourceGenerators AttributeArgument(ArrayExpression(processedTypes)), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))), AttributeArgument(ArrayExpression(processedMethods)), - AttributeArgument(NestedArrayExpression(processedConstants))))) + AttributeArgument(NestedArrayExpression(Array.Empty()))))) // TODO .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) .NormalizeWhitespace() diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs index d3389bf0..b81e424c 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs @@ -17,7 +17,7 @@ namespace ComputeSharp.__Internals /// /// The unique dispatch identifier for the shader. [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This interface is not intended to be used directly by user code")] + [Obsolete("This method is not intended to be used directly by user code")] int GetDispatchId(); /// @@ -33,5 +33,16 @@ namespace ComputeSharp.__Internals [Obsolete("This method is not intended to be called directly by user code")] void LoadDispatchData(in TDataLoader dataLoader, GraphicsDevice device, int x, int y, int z) where TDataLoader : struct, IDispatchDataLoader; + + /// + /// Builds the HLSL source code for the current shader instance. + /// + /// The target instance to write the HLSL source to. + /// The number of threads in each thread group for the X axis. + /// The number of threads in each thread group for the Y axis. + /// The number of threads in each thread group for the Z axis. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + void BuildHlslString(ref ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ); } } diff --git a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs index 754709ee..b0d797c3 100644 --- a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs +++ b/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs @@ -1,8 +1,5 @@ -using System; -using System.Buffers; -using System.Diagnostics; -using System.Diagnostics.Contracts; -using System.Runtime.CompilerServices; +using System.Diagnostics.Contracts; +using ComputeSharp.__Internals; using ComputeSharp.Shaders.Renderer.Models; using ComputeSharp.Shaders.Translation; @@ -191,166 +188,5 @@ namespace ComputeSharp.Shaders.Renderer return builder; } - - /// - /// A helper type that implements a pooled buffer writer for values. - /// - [DebuggerTypeProxy(typeof(DebugView))] - public ref struct ArrayPoolStringBuilder - { - /// - /// The underlying array. - /// - private char[] array; - - /// - /// The starting offset within . - /// - private int index; - - /// - /// Creates a new instance ready to use. - /// - /// A new instance with default values. - [Pure] - public static ArrayPoolStringBuilder Create() - { - ArrayPoolStringBuilder builder; - - builder.array = ArrayPool.Shared.Rent(1024); - builder.index = 0; - - return builder; - } - - /// - public ReadOnlySpan WrittenSpan - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => new(this.array, 0, this.index); - } - - /// - /// Appends the input sequence of characters to the current buffer. - /// - /// The input characters to write. - public void Append(string value) - { - EnsureCapacity(value.Length); - - value.AsSpan().CopyTo(this.array.AsSpan(this.index)); - - this.index += value.Length; - } - - /// - /// Appends a character to the current buffer. - /// - public void Append(char character) - { - EnsureCapacity(1); - - this.array[this.index++] = character; - } - - /// - /// Appends the input sequence of characters to the current buffer, with a trailing new line. - /// - /// The input characters to write. - public void AppendLine(string value) - { - EnsureCapacity(value.Length + 1); - - value.AsSpan().CopyTo(this.array.AsSpan(this.index)); - - this.index += value.Length; - - this.array[this.index++] = '\n'; - } - - /// - /// Appends a character and a new line to the current buffer. - /// - public void AppendLine(char character) - { - EnsureCapacity(2); - - this.array[this.index++] = character; - this.array[this.index++] = '\n'; - } - - /// - /// Appends a new line to the current buffer. - /// - public void AppendLine() - { - EnsureCapacity(1); - - this.array[this.index++] = '\n'; - } - - /// - /// Ensures that has enough free space to contain a given number of new items. - /// - /// The minimum number of items to ensure space for in . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void EnsureCapacity(int requestedSize) - { - if (requestedSize > this.array.Length - this.index) - { - ResizeBuffer(requestedSize); - } - } - - /// - /// Resizes to ensure it can fit the specified number of new items. - /// - /// The minimum number of items to ensure space for in . - [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.Shared.Rent(minimumSize); - int itemsToCopy = Math.Min(this.array.Length, minimumSize); - - Array.Copy(this.array, 0, newArray, 0, itemsToCopy); - - ArrayPool.Shared.Return(array); - - this.array = newArray; - } - - /// - public void Dispose() - { - ArrayPool.Shared.Return(this.array); - } - - /// - /// A debug proxy used for displaying debug info. - /// - internal sealed class DebugView - { - /// - /// Initializes a new instance of the class with the specified parameters. - /// - /// The input instance to display. - public DebugView(ArrayPoolStringBuilder builder) - { - Text = builder.WrittenSpan.ToString(); - } - - /// - /// Gets the text to display for the current instance. - /// - public string Text { get; } - } - } } } diff --git a/src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs b/src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs new file mode 100644 index 00000000..a7922b49 --- /dev/null +++ b/src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs @@ -0,0 +1,169 @@ +using System; +using System.Buffers; +using System.Diagnostics; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; + +namespace ComputeSharp.__Internals +{ + /// + /// A helper type that implements a pooled buffer writer for values. + /// + [DebuggerTypeProxy(typeof(DebugView))] + public ref struct ArrayPoolStringBuilder + { + /// + /// The underlying array. + /// + private char[] array; + + /// + /// The starting offset within . + /// + private int index; + + /// + /// Creates a new instance ready to use. + /// + /// A new instance with default values. + [Pure] + public static ArrayPoolStringBuilder Create() + { + ArrayPoolStringBuilder builder; + + builder.array = ArrayPool.Shared.Rent(1024); + builder.index = 0; + + return builder; + } + + /// + public ReadOnlySpan WrittenSpan + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new(this.array, 0, this.index); + } + + /// + /// Appends the input sequence of characters to the current buffer. + /// + /// The input characters to write. + public void Append(string value) + { + EnsureCapacity(value.Length); + + value.AsSpan().CopyTo(this.array.AsSpan(this.index)); + + this.index += value.Length; + } + + /// + /// Appends a character to the current buffer. + /// + public void Append(char character) + { + EnsureCapacity(1); + + this.array[this.index++] = character; + } + + /// + /// Appends the input sequence of characters to the current buffer, with a trailing new line. + /// + /// The input characters to write. + public void AppendLine(string value) + { + EnsureCapacity(value.Length + 1); + + value.AsSpan().CopyTo(this.array.AsSpan(this.index)); + + this.index += value.Length; + + this.array[this.index++] = '\n'; + } + + /// + /// Appends a character and a new line to the current buffer. + /// + public void AppendLine(char character) + { + EnsureCapacity(2); + + this.array[this.index++] = character; + this.array[this.index++] = '\n'; + } + + /// + /// Appends a new line to the current buffer. + /// + public void AppendLine() + { + EnsureCapacity(1); + + this.array[this.index++] = '\n'; + } + + /// + /// Ensures that has enough free space to contain a given number of new items. + /// + /// The minimum number of items to ensure space for in . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void EnsureCapacity(int requestedSize) + { + if (requestedSize > this.array.Length - this.index) + { + ResizeBuffer(requestedSize); + } + } + + /// + /// Resizes to ensure it can fit the specified number of new items. + /// + /// The minimum number of items to ensure space for in . + [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.Shared.Rent(minimumSize); + int itemsToCopy = Math.Min(this.array.Length, minimumSize); + + Array.Copy(this.array, 0, newArray, 0, itemsToCopy); + + ArrayPool.Shared.Return(array); + + this.array = newArray; + } + + /// + public void Dispose() + { + ArrayPool.Shared.Return(this.array); + } + + /// + /// A debug proxy used for displaying debug info. + /// + internal sealed class DebugView + { + /// + /// Initializes a new instance of the class with the specified parameters. + /// + /// The input instance to display. + public DebugView(ArrayPoolStringBuilder builder) + { + Text = builder.WrittenSpan.ToString(); + } + + /// + /// Gets the text to display for the current instance. + /// + public string Text { get; } + } + } +} diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs index d2b29955..511d5ea0 100644 --- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs @@ -237,19 +237,19 @@ namespace ComputeSharp.Shaders /// The input instance representing the compute shader to run. /// The instance to return with the cached shader data. [MethodImpl(MethodImplOptions.NoInlining)] - private static void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader shaderData) + private static unsafe void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader shaderData) { - // Load the input shader - ShaderLoader shaderLoader = ShaderLoader.Load(in shader); + ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(); - // Render the loaded shader - using var shaderSource = HlslShaderRenderer.Render(threadsX, threadsY, threadsZ, shaderLoader); + shader.BuildHlslString(ref builder, threadsX, threadsY, threadsZ); - // Compile the loaded shader to HLSL bytecode - IDxcBlobObject shaderBytecode = new(ShaderCompiler.Instance.CompileShader(shaderSource.WrittenSpan)); + using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(builder.WrittenSpan); - // Get the cached shader data - shaderData = new CachedShader(shaderLoader, shaderBytecode); + builder.Dispose(); + + IDxcBlobObject shaderBytecode = new(dxcBlobBytecode.Get()); + + shaderData = new CachedShader(null!, shaderBytecode); // TODO } /// diff --git a/src/ComputeSharp/Shaders/Translation/Interop/IDxcBlobObject.cs b/src/ComputeSharp/Shaders/Translation/Interop/IDxcBlobObject.cs index eb3cd02e..9f7e9135 100644 --- a/src/ComputeSharp/Shaders/Translation/Interop/IDxcBlobObject.cs +++ b/src/ComputeSharp/Shaders/Translation/Interop/IDxcBlobObject.cs @@ -17,9 +17,9 @@ namespace ComputeSharp.Shaders.Translation.Interop /// Creates a new instance with the specified parameters. /// /// The instance to wrap. - public IDxcBlobObject(ComPtr dxcBlob) + public IDxcBlobObject(IDxcBlob* dxcBlob) { - this.dxcBlob = dxcBlob; + this.dxcBlob = new ComPtr(dxcBlob); } /// diff --git a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs index 39434980..51af97ba 100644 --- a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs @@ -26,11 +26,6 @@ namespace ComputeSharp.Shaders.Translation /// private static readonly IComputeShaderSourceAttribute Attribute = IComputeShaderSourceAttribute.GetForType(); - /// - /// The of instances mapping the captured variables in the current shader. - /// - private readonly List capturedFields = new(); - /// /// The number of constant buffers to define in the shader. /// @@ -254,21 +249,18 @@ namespace ComputeSharp.Shaders.Translation { d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount)); - this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++)); } else if (HlslKnownTypes.IsReadOnlyResourceType(fieldType)) { d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, this.readOnlyBuffersCount)); - this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++)); } else if (HlslKnownTypes.IsReadWriteResourceType(fieldType)) { d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount)); - this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); } else if (fieldInfo.GetValue(shader) is Delegate func) @@ -289,7 +281,6 @@ namespace ComputeSharp.Shaders.Translation } else { - this.capturedFields.Add(fieldInfo); this.fieldsInfo.Add(new CapturedFieldInfo(hlslType, hlslName)); } }