diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index 381e0b6d..a97ea1b9 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -1,7 +1,11 @@ +using System; using System.Collections.Immutable; using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Mappings; +using ComputeSharp.SourceGeneration.Models; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -19,10 +23,22 @@ partial class ID2D1ShaderGenerator /// /// Creates a instance for the LoadDispatchDataMethod method. /// + /// The hiararchy info of the shader type. /// The dispatch info gathered for the current shader. + /// Any additional instances needed by the generated code, if needed. /// The resulting instance for the LoadDispatchDataMethod method. - public static MethodDeclarationSyntax GetSyntax(DispatchDataInfo dispatchInfo) + public static MethodDeclarationSyntax GetSyntax(HierarchyInfo hierarchyInfo, DispatchDataInfo dispatchInfo, out TypeDeclarationSyntax[] additionalTypes) { + // Declare the mapping constant buffer type, if needed (ie. if the shader has at least one field) + if (dispatchInfo.FieldInfos.Length == 0) + { + additionalTypes = Array.Empty(); + } + else + { + additionalTypes = new[] { GetConstantBufferDeclaration(hierarchyInfo, dispatchInfo.FieldInfos, dispatchInfo.ConstantBufferSizeInBytes) }; + } + // This code produces a method declaration as follows: // // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadDispatchData(ref TLoader loader) @@ -38,6 +54,122 @@ partial class ID2D1ShaderGenerator .WithBody(Block(GetDispatchDataLoadingStatements(dispatchInfo.FieldInfos, dispatchInfo.ConstantBufferSizeInBytes))); } + /// + /// Gets a type definition to map the constant buffer of a given shader type. + /// + /// The hiararchy info of the shader type. + /// The array of values for all captured fields. + /// The size of the shader constant buffer. + /// The object for the mapped constant buffer for the current shader type. + private static TypeDeclarationSyntax GetConstantBufferDeclaration(HierarchyInfo hierarchyInfo, ImmutableArray fieldInfos, int constantBufferSizeInBytes) + { + string fullyQualifiedTypeName = hierarchyInfo.GetFullyQualifiedTypeName(); + + using ImmutableArrayBuilder fieldDeclarations = ImmutableArrayBuilder.Rent(); + + // Appends a new field declaration for a constant buffer field: + // + // + // [global::System.Runtime.InteropServices.FieldOffset()] + // public ; + void AppendFieldDeclaration( + string comment, + TypeSyntax typeIdentifier, + string identifierName, + int fieldOffset) + { + fieldDeclarations.Add( + FieldDeclaration( + VariableDeclaration(typeIdentifier) + .AddVariables(VariableDeclarator(Identifier(identifierName)))) + .AddAttributeLists(AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.Runtime.InteropServices.FieldOffset")) + .AddArgumentListArguments(AttributeArgument( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(fieldOffset))))))) + .AddModifiers(Token(SyntaxKind.PublicKeyword)) + .WithLeadingTrivia(Comment(comment))); + } + + // Declare fields for every mapped item from the shader layout + foreach (FieldInfo fieldInfo in fieldInfos) + { + switch (fieldInfo) + { + case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive: + + // Append a field as a global::ComputeSharp.Bool value (will use the implicit conversion from bool values) + AppendFieldDeclaration( + comment: $"""/// """, + typeIdentifier: IdentifierName("global::ComputeSharp.Bool"), + identifierName: string.Join("_", primitive.FieldPath), + fieldOffset: primitive.Offset); + break; + case FieldInfo.Primitive primitive: + + // Append primitive fields of other types with their mapped names + AppendFieldDeclaration( + comment: $"""/// """, + typeIdentifier: IdentifierName(HlslKnownTypes.GetMappedName(primitive.TypeName)), + identifierName: string.Join("_", primitive.FieldPath), + fieldOffset: primitive.Offset); + break; + + case FieldInfo.NonLinearMatrix matrix: + string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}"); + string fieldNamePrefix = string.Join("_", matrix.FieldPath); + + // Declare a field for every row of the matrix type + for (int j = 0; j < matrix.Rows; j++) + { + AppendFieldDeclaration( + comment: $"""/// Row {j} of .""", + typeIdentifier: IdentifierName(rowTypeName), + identifierName: $"{fieldNamePrefix}_{j}", + fieldOffset: matrix.Offsets[j]); + } + + break; + } + } + + // Create the constant buffer type: + // + // /// + // /// A type representing the constant buffer native layout for . + // /// + // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")] + // [global::System.Diagnostics.DebuggerNonUserCode] + // [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + // [global::System.Runtime.InteropServices.StructLayout(global::System.Runtime.InteropServices.LayoutKind.Explicit, Size = )] + // file struct ConstantBuffer + // { + // + // } + return + StructDeclaration("ConstantBuffer") + .AddModifiers(Token(SyntaxKind.FileKeyword)) + .AddAttributeLists( + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.Runtime.InteropServices.StructLayout")).AddArgumentListArguments( + AttributeArgument(MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("global::System.Runtime.InteropServices.LayoutKind"), + IdentifierName("Explicit"))), + AttributeArgument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(constantBufferSizeInBytes))) + .WithNameEquals(NameEquals(IdentifierName("Size"))))))) + .AddMembers(fieldDeclarations.ToArray()) + .WithLeadingTrivia( + Comment("/// "), + Comment($"""/// A type representing the constant buffer native layout for ."""), + Comment("/// ")); + } + /// /// Gets a sequence of statements to load the dispatch data for a given shader. /// diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index 5194aafa..1d85eac3 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -307,8 +307,8 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Generate the LoadDispatchData() methods context.RegisterSourceOutput(dispatchDataInfo, static (context, item) => { - MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(item.Info.Dispatch); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Info.Hierarchy, loadDispatchDataMethod, item.CanUseSkipLocalsInit); + MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(item.Info.Hierarchy, item.Info.Dispatch, out TypeDeclarationSyntax[] additionalTypes); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Info.Hierarchy, loadDispatchDataMethod, item.CanUseSkipLocalsInit, additionalMemberDeclarations: additionalTypes); context.AddSource($"{item.Info.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownTypes.cs index cecae13f..280c4196 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownTypes.cs @@ -181,8 +181,18 @@ internal static partial class HlslKnownTypes /// Gets the mapped HLSL-compatible type name for the input type name. /// /// The input type name to map. - /// The resulting mapped type name, if found. /// The HLSL-compatible type name that can be used in an HLSL shader. + public static string GetMappedName(string originalName) + { + return KnownHlslTypes[originalName]; + } + + /// + /// Tries to get the mapped HLSL-compatible type name for the input type name. + /// + /// The input type name to map. + /// The resulting mapped type name, if found. + /// Whether a mapped name was available. public static bool TryGetMappedName(string originalName, out string? mappedName) { return KnownHlslTypes.TryGetValue(originalName, out mappedName);