diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.Syntax.cs
deleted file mode 100644
index 515b8a26..00000000
--- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.Syntax.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-using ComputeSharp.D2D1.SourceGenerators.Models;
-using ComputeSharp.SourceGeneration.Extensions;
-using ComputeSharp.SourceGeneration.Helpers;
-
-namespace ComputeSharp.D2D1.SourceGenerators;
-
-///
-partial class D2DPixelShaderDescriptorGenerator
-{
- ///
- partial class ConstantBuffer
- {
- ///
- /// Writes the LoadConstantBuffer method.
- ///
- /// The input instance with gathered shader info.
- /// The instance to write into.
- public static void WriteLoadConstantBufferSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
- {
- string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
-
- writer.WriteLine("/// ");
- writer.WriteGeneratedAttributes(GeneratorName);
- writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
- writer.WriteLine($"static unsafe void global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.LoadConstantBuffer(in {typeName} shader, ref TLoader loader)");
-
- using (writer.WriteBlock())
- {
- // If there are no fields, just load an empty buffer
- if (info.Fields.IsEmpty)
- {
- writer.WriteLine("loader.LoadConstantBuffer(default);");
- }
- else
- {
- // Otherwise, pass a span into the marshalled native layout buffer
- writer.WriteLine("global::ComputeSharp.D2D1.Generated.ConstantBufferMarshaller.FromManaged(in shader, out global::ComputeSharp.D2D1.Generated.ConstantBuffer buffer);");
- writer.WriteLine();
- writer.WriteLine("loader.LoadConstantBuffer(new global::System.ReadOnlySpan(&buffer, sizeof(global::ComputeSharp.D2D1.Generated.ConstantBuffer)));");
- }
- }
- }
-
- ///
- /// Writes the CreateFromConstantBuffer method.
- ///
- /// The input instance with gathered shader info.
- /// The instance to write into.
- public static void WriteCreateFromConstantBufferSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
- {
- string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
-
- writer.WriteLine("/// ");
- writer.WriteGeneratedAttributes(GeneratorName);
- writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
- writer.WriteLine($"static unsafe {typeName} global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.CreateFromConstantBuffer(global::System.ReadOnlySpan data)");
-
- using (writer.WriteBlock())
- {
- // If there are no fields, just return an empty shader
- if (info.Fields.IsEmpty)
- {
- writer.WriteLine("return default;");
-
- return;
- }
-
- // Get a reference to the data through the generated native layout type and define the shader
- writer.WriteLine("ref readonly global::ComputeSharp.D2D1.Generated.ConstantBuffer buffer = ref global::System.Runtime.InteropServices.MemoryMarshal.AsRef(data);");
- writer.WriteLine();
- writer.WriteLine("return global::ComputeSharp.D2D1.Generated.ConstantBufferMarshaller.ToManaged(in buffer);");
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.cs
index d86dbe5b..2add6b86 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.cs
@@ -1,12 +1,10 @@
using System;
using System.Collections.Immutable;
-using System.Diagnostics.CodeAnalysis;
-using System.Text.RegularExpressions;
-using ComputeSharp.Core.Helpers;
+using ComputeSharp.D2D1.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
-using ComputeSharp.SourceGeneration.Mappings;
using ComputeSharp.SourceGeneration.Models;
+using ComputeSharp.SourceGeneration.SyntaxProcessors;
using Microsoft.CodeAnalysis;
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
@@ -20,22 +18,12 @@ partial class D2DPixelShaderDescriptorGenerator
///
private static partial class ConstantBuffer
{
- ///
- /// A to extract the parameter name of a primary constructor capture field.
- ///
- ///
- /// Temporary workaround until is available.
- ///
- private static readonly Regex PrimaryConstructorNameRegex = new("^<([^>]+)>P$", RegexOptions.Compiled);
-
- ///
- /// Explores a given type hierarchy and generates statements to load fields.
- ///
+ ///
/// The collection of produced instances.
- /// The input object currently in use.
- /// The current shader type being explored.
- /// The size of the shader constant buffer.
- /// The sequence of instances for all captured values.
+ ///
+ ///
+ ///
+ ///
public static void GetInfo(
ImmutableArrayBuilder diagnostics,
Compilation compilation,
@@ -43,79 +31,11 @@ partial class D2DPixelShaderDescriptorGenerator
out int constantBufferSizeInBytes,
out ImmutableArray fields)
{
- // Helper method that uses boxes instead of ref-s (illegal in enumerators)
- static void GetInfo(
- Compilation compilation,
- ITypeSymbol currentTypeSymbol,
- ImmutableArray fieldPath,
- ref int rawDataOffset,
- ImmutableArrayBuilder fields)
- {
- bool isFirstField = true;
-
- foreach (ISymbol memberSymbol in currentTypeSymbol.GetMembers())
- {
- // Only process fields of a valid shape/type
- if (memberSymbol is not IFieldSymbol { Type: INamedTypeSymbol { IsStatic: false }, IsConst: false, IsStatic: false, IsFixedSizeBuffer: false } fieldSymbol)
- {
- continue;
- }
-
- // Skip fields of not accessible types (the analyzer will handle this)
- if (!fieldSymbol.Type.IsAccessibleFromCompilationAssembly(compilation))
- {
- continue;
- }
-
- // Try to get the name to use for the field and the accessor
- if (!TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out string? unspeakableName))
- {
- continue;
- }
-
- string typeName = fieldSymbol.Type.GetFullyQualifiedMetadataName();
-
- // The first item in each nested struct needs to be aligned to 16 bytes
- if (isFirstField && fieldPath.Length > 0)
- {
- rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
-
- isFirstField = false;
- }
-
- if (HlslKnownTypes.IsKnownHlslType(typeName))
- {
- ImmutableArray nestedFieldPath = fieldPath.Add(new FieldPathPart.Leaf(fieldName, unspeakableName));
-
- fields.Add(GetHlslKnownTypeFieldInfo(nestedFieldPath, typeName, ref rawDataOffset));
- }
- else if (fieldSymbol.Type.IsUnmanagedType)
- {
- string nestedTypeName = fieldSymbol.Type.GetFullyQualifiedName(includeGlobal: true);
- FieldPathPart fieldPathPart = new FieldPathPart.Nested(fieldName, unspeakableName, nestedTypeName);
-
- // Custom struct type defined by the user
- GetInfo(compilation, fieldSymbol.Type, fieldPath.Add(fieldPathPart), ref rawDataOffset, fields);
- }
- }
- }
-
- // Setup the resource and byte offsets for tracking
- int rawDataOffset = 0;
-
- using (ImmutableArrayBuilder fieldBuilder = new())
- {
- // Traverse all shader fields and gather info, and update the tracking offsets
- GetInfo(
- compilation,
- structDeclarationSymbol,
- ImmutableArray.Empty,
- ref rawDataOffset,
- fieldBuilder);
-
- constantBufferSizeInBytes = rawDataOffset;
- fields = fieldBuilder.ToImmutable();
- }
+ ConstantBufferSyntaxProcessor.GetInfo(
+ compilation,
+ structDeclarationSymbol,
+ out constantBufferSizeInBytes,
+ out fields);
// The maximum size for a constant buffer is 64KB
const int D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT = 4096;
@@ -129,95 +49,64 @@ partial class D2DPixelShaderDescriptorGenerator
}
///
- /// Tries to get the field name and the accessor name for a given field.
+ /// Writes the LoadConstantBuffer method.
///
- /// The field symbol to analyze.
- /// The name of the field that's referenced in code by users.
- /// The real name of the field that should be accessed, when different.
- /// Whether the field is supported and the necessary info could be retrieved.
- public static bool TryGetFieldAccessorName(
- IFieldSymbol fieldSymbol,
- [NotNullWhen(true)] out string? referencedName,
- out string? unspeakableName)
+ /// The input instance with gathered shader info.
+ /// The instance to write into.
+ public static void WriteLoadConstantBufferSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
- // If the field can be referenced by name, we can just access it directly
- if (fieldSymbol.CanBeReferencedByName)
+ string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
+
+ writer.WriteLine("/// ");
+ writer.WriteGeneratedAttributes(GeneratorName);
+ writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
+ writer.WriteLine($"static unsafe void global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.LoadConstantBuffer(in {typeName} shader, ref TLoader loader)");
+
+ using (writer.WriteBlock())
{
- referencedName = fieldSymbol.Name;
- unspeakableName = null;
-
- return true;
+ // If there are no fields, just load an empty buffer
+ if (info.Fields.IsEmpty)
+ {
+ writer.WriteLine("loader.LoadConstantBuffer(default);");
+ }
+ else
+ {
+ // Otherwise, pass a span into the marshalled native layout buffer
+ writer.WriteLine("global::ComputeSharp.D2D1.Generated.ConstantBufferMarshaller.FromManaged(in shader, out global::ComputeSharp.D2D1.Generated.ConstantBuffer buffer);");
+ writer.WriteLine();
+ writer.WriteLine("loader.LoadConstantBuffer(new global::System.ReadOnlySpan(&buffer, sizeof(global::ComputeSharp.D2D1.Generated.ConstantBuffer)));");
+ }
}
-
- // If the field is a primary constructor capture field, get the original name
- if (PrimaryConstructorNameRegex.Match(fieldSymbol.Name) is { Success: true, Groups: [_, { Value: string parameterName }] })
- {
- referencedName = parameterName;
- unspeakableName = fieldSymbol.Name;
-
- return true;
- }
-
- // The field is not recognized, so just invalid
- referencedName = null;
- unspeakableName = null;
-
- return false;
}
///
- /// Gets info on a given captured HLSL primitive type (either a scalar, a vector or a matrix).
+ /// Writes the CreateFromConstantBuffer method.
///
- /// The current path of the field with respect to the shader instance.
- /// The type name currently being read.
- /// The current offset within the loaded data buffer.
- private static FieldInfo GetHlslKnownTypeFieldInfo(
- ImmutableArray fieldPath,
- string typeName,
- ref int rawDataOffset)
+ /// The input instance with gathered shader info.
+ /// The instance to write into.
+ public static void WriteCreateFromConstantBufferSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
- // For scalar, vector and linear matrix types, serialize the value normally.
- // Only the initial alignment needs to be considered, while data is packed.
- (int fieldSize, int fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
+ string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
- // Check if the current type is a matrix type with more than one row. In this
- // case, each row is aligned as if it was a separate array, so the start of
- // each row needs to be at a multiple of 16 bytes (a float4 register).
- if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns))
+ writer.WriteLine("/// ");
+ writer.WriteGeneratedAttributes(GeneratorName);
+ writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
+ writer.WriteLine($"static unsafe {typeName} global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.CreateFromConstantBuffer(global::System.ReadOnlySpan data)");
+
+ using (writer.WriteBlock())
{
- using ImmutableArrayBuilder builder = new();
-
- for (int j = 0; j < rows; j++)
+ // If there are no fields, just return an empty shader
+ if (info.Fields.IsEmpty)
{
- int startingRawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
+ writer.WriteLine("return default;");
- builder.Add(startingRawDataOffset);
-
- rawDataOffset = startingRawDataOffset + (fieldPack * columns);
+ return;
}
- return new FieldInfo.NonLinearMatrix(
- fieldPath,
- typeName,
- elementName!,
- rows,
- columns,
- builder.ToImmutable());
- }
- else
- {
- // Calculate the right offset with 16-bytes padding (HLSL constant buffer).
- // Since we're in a constant buffer, we need to both pad the starting offset
- // to be aligned to the packing size of the type, and also to align the initial
- // offset to ensure that values do not cross 16 bytes boundaries either.
- int startingRawDataOffset = AlignmentHelper.AlignToBoundary(
- AlignmentHelper.Pad(rawDataOffset, fieldPack),
- fieldSize,
- 16);
-
- rawDataOffset = startingRawDataOffset + fieldSize;
-
- return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset);
+ // Get a reference to the data through the generated native layout type and define the shader
+ writer.WriteLine("ref readonly global::ComputeSharp.D2D1.Generated.ConstantBuffer buffer = ref global::System.Runtime.InteropServices.MemoryMarshal.AsRef(data);");
+ writer.WriteLine();
+ writer.WriteLine("return global::ComputeSharp.D2D1.Generated.ConstantBufferMarshaller.ToManaged(in buffer);");
}
}
}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs
index 5415f5f3..fcf1994d 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs
@@ -6,6 +6,7 @@ using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Mappings;
using ComputeSharp.SourceGeneration.Models;
+using ComputeSharp.SourceGeneration.SyntaxProcessors;
using ComputeSharp.SourceGeneration.SyntaxRewriters;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
@@ -117,7 +118,7 @@ partial class D2DPixelShaderDescriptorGenerator
}
// Try to get the actual field name
- if (!ConstantBuffer.TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out _))
+ if (!ConstantBufferSyntaxProcessor.TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out _))
{
continue;
}
@@ -411,7 +412,7 @@ partial class D2DPixelShaderDescriptorGenerator
}
// Try to get the actual field name
- if (!ConstantBuffer.TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out _))
+ if (!ConstantBufferSyntaxProcessor.TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out _))
{
continue;
}
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs
index 7574a56c..9a0b8d04 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs
@@ -4,7 +4,7 @@ using ComputeSharp.D2D1.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Models;
-using ComputeSharp.SourceGeneration.SyntaxWriters;
+using ComputeSharp.SourceGeneration.SyntaxProcessors;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -234,7 +234,7 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene
using ImmutableArrayBuilder> additionalTypes = new();
using ImmutableHashSetBuilder usingDirectives = new();
- ConstantBufferSyntaxWriter.RegisterAdditionalTypesSyntax(GeneratorName, item, additionalTypes, usingDirectives);
+ ConstantBufferSyntaxProcessor.RegisterAdditionalTypesSyntax(GeneratorName, item, additionalTypes, usingDirectives);
InputDescriptions.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
InputTypes.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
HlslBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems
index e6cb2cda..0f3f97f3 100644
--- a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems
+++ b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems
@@ -27,10 +27,11 @@
+
-
+
\ No newline at end of file
diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxWriters/ConstantBufferSyntaxWriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.Generation.cs
similarity index 98%
rename from src/ComputeSharp.SourceGeneration.Hlsl/SyntaxWriters/ConstantBufferSyntaxWriter.cs
rename to src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.Generation.cs
index e948fcd6..8a9abefc 100644
--- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxWriters/ConstantBufferSyntaxWriter.cs
+++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.Generation.cs
@@ -4,12 +4,10 @@ using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Mappings;
using ComputeSharp.SourceGeneration.Models;
-namespace ComputeSharp.SourceGeneration.SyntaxWriters;
+namespace ComputeSharp.SourceGeneration.SyntaxProcessors;
-///
-/// A helper responsible for writing the constant buffer syntax for shader types.
-///
-internal static partial class ConstantBufferSyntaxWriter
+///
+partial class ConstantBufferSyntaxProcessor
{
///
/// The name of generator to include in the generated code.
@@ -33,7 +31,7 @@ internal static partial class ConstantBufferSyntaxWriter
{
// Store the generator name for later. This avoids needing closures for each callback below.
// It is assumed that all calls to this method will have the same argument in each assembly.
- ConstantBufferSyntaxWriter.generatorName = generatorName;
+ ConstantBufferSyntaxProcessor.generatorName = generatorName;
// If there are no fields, there is no need for a constant buffer type
if (info.Fields.IsEmpty)
@@ -55,7 +53,7 @@ internal static partial class ConstantBufferSyntaxWriter
writer.WriteLine($"""/// """);
writer.WriteLine($"""/// A type representing the constant buffer native layout for .""");
writer.WriteLine($"""/// """);
- writer.WriteGeneratedAttributes(ConstantBufferSyntaxWriter.generatorName!, useFullyQualifiedTypeNames: false);
+ writer.WriteGeneratedAttributes(ConstantBufferSyntaxProcessor.generatorName!, useFullyQualifiedTypeNames: false);
writer.WriteLine($"""[StructLayout(LayoutKind.Explicit, Size = {info.ConstantBufferSizeInBytes})]""");
writer.WriteLine($"""file struct ConstantBuffer""");
@@ -111,7 +109,7 @@ internal static partial class ConstantBufferSyntaxWriter
writer.WriteLine($"""/// """);
writer.WriteLine($"""/// A type containing marshalling logic for shaders of type .""");
writer.WriteLine($"""/// """);
- writer.WriteGeneratedAttributes(ConstantBufferSyntaxWriter.generatorName!, useFullyQualifiedTypeNames: false);
+ writer.WriteGeneratedAttributes(ConstantBufferSyntaxProcessor.generatorName!, useFullyQualifiedTypeNames: false);
writer.WriteLine($"""file static class ConstantBufferMarshaller""");
using (writer.WriteBlock())
diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.cs
new file mode 100644
index 00000000..deaad4ee
--- /dev/null
+++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.cs
@@ -0,0 +1,205 @@
+using System.Collections.Immutable;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.RegularExpressions;
+using ComputeSharp.Core.Helpers;
+using ComputeSharp.SourceGeneration.Extensions;
+using ComputeSharp.SourceGeneration.Helpers;
+using ComputeSharp.SourceGeneration.Mappings;
+using ComputeSharp.SourceGeneration.Models;
+using Microsoft.CodeAnalysis;
+
+namespace ComputeSharp.SourceGeneration.SyntaxProcessors;
+
+///
+/// A processor responsible for extracting info and writing syntax for the constant buffer syntax for shader types.
+///
+internal static partial class ConstantBufferSyntaxProcessor
+{
+ ///
+ /// A to extract the parameter name of a primary constructor capture field.
+ ///
+ ///
+ /// Temporary workaround until is available.
+ ///
+ private static readonly Regex PrimaryConstructorNameRegex = new("^<([^>]+)>P$", RegexOptions.Compiled);
+
+ ///
+ /// Explores a given type hierarchy and generates statements to load fields.
+ ///
+ /// The input object currently in use.
+ /// The current shader type being explored.
+ /// The size of the shader constant buffer.
+ /// The sequence of instances for all captured values.
+ public static void GetInfo(
+ Compilation compilation,
+ ITypeSymbol structDeclarationSymbol,
+ out int constantBufferSizeInBytes,
+ out ImmutableArray fields)
+ {
+ // Helper method that uses boxes instead of ref-s (illegal in enumerators)
+ static void GetInfo(
+ Compilation compilation,
+ ITypeSymbol currentTypeSymbol,
+ ImmutableArray fieldPath,
+ ref int rawDataOffset,
+ ImmutableArrayBuilder fields)
+ {
+ bool isFirstField = true;
+
+ foreach (ISymbol memberSymbol in currentTypeSymbol.GetMembers())
+ {
+ // Only process fields of a valid shape/type
+ if (memberSymbol is not IFieldSymbol { Type: INamedTypeSymbol { IsStatic: false }, IsConst: false, IsStatic: false, IsFixedSizeBuffer: false } fieldSymbol)
+ {
+ continue;
+ }
+
+ // Skip fields of not accessible types (the analyzer will handle this)
+ if (!fieldSymbol.Type.IsAccessibleFromCompilationAssembly(compilation))
+ {
+ continue;
+ }
+
+ // Try to get the name to use for the field and the accessor
+ if (!TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out string? unspeakableName))
+ {
+ continue;
+ }
+
+ string typeName = fieldSymbol.Type.GetFullyQualifiedMetadataName();
+
+ // The first item in each nested struct needs to be aligned to 16 bytes
+ if (isFirstField && fieldPath.Length > 0)
+ {
+ rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
+
+ isFirstField = false;
+ }
+
+ if (HlslKnownTypes.IsKnownHlslType(typeName))
+ {
+ ImmutableArray nestedFieldPath = fieldPath.Add(new FieldPathPart.Leaf(fieldName, unspeakableName));
+
+ fields.Add(GetHlslKnownTypeFieldInfo(nestedFieldPath, typeName, ref rawDataOffset));
+ }
+ else if (fieldSymbol.Type.IsUnmanagedType)
+ {
+ string nestedTypeName = fieldSymbol.Type.GetFullyQualifiedName(includeGlobal: true);
+ FieldPathPart fieldPathPart = new FieldPathPart.Nested(fieldName, unspeakableName, nestedTypeName);
+
+ // Custom struct type defined by the user
+ GetInfo(compilation, fieldSymbol.Type, fieldPath.Add(fieldPathPart), ref rawDataOffset, fields);
+ }
+ }
+ }
+
+ // Setup the resource and byte offsets for tracking
+ int rawDataOffset = 0;
+
+ using ImmutableArrayBuilder fieldBuilder = new();
+
+ // Traverse all shader fields and gather info, and update the tracking offsets
+ GetInfo(
+ compilation,
+ structDeclarationSymbol,
+ ImmutableArray.Empty,
+ ref rawDataOffset,
+ fieldBuilder);
+
+ constantBufferSizeInBytes = rawDataOffset;
+ fields = fieldBuilder.ToImmutable();
+ }
+
+ ///
+ /// Tries to get the field name and the accessor name for a given field.
+ ///
+ /// The field symbol to analyze.
+ /// The name of the field that's referenced in code by users.
+ /// The real name of the field that should be accessed, when different.
+ /// Whether the field is supported and the necessary info could be retrieved.
+ public static bool TryGetFieldAccessorName(
+ IFieldSymbol fieldSymbol,
+ [NotNullWhen(true)] out string? referencedName,
+ out string? unspeakableName)
+ {
+ // If the field can be referenced by name, we can just access it directly
+ if (fieldSymbol.CanBeReferencedByName)
+ {
+ referencedName = fieldSymbol.Name;
+ unspeakableName = null;
+
+ return true;
+ }
+
+ // If the field is a primary constructor capture field, get the original name
+ if (PrimaryConstructorNameRegex.Match(fieldSymbol.Name) is { Success: true, Groups: [_, { Value: string parameterName }] })
+ {
+ referencedName = parameterName;
+ unspeakableName = fieldSymbol.Name;
+
+ return true;
+ }
+
+ // The field is not recognized, so just invalid
+ referencedName = null;
+ unspeakableName = null;
+
+ return false;
+ }
+
+ ///
+ /// Gets info on a given captured HLSL primitive type (either a scalar, a vector or a matrix).
+ ///
+ /// The current path of the field with respect to the shader instance.
+ /// The type name currently being read.
+ /// The current offset within the loaded data buffer.
+ private static FieldInfo GetHlslKnownTypeFieldInfo(
+ ImmutableArray fieldPath,
+ string typeName,
+ ref int rawDataOffset)
+ {
+ // For scalar, vector and linear matrix types, serialize the value normally.
+ // Only the initial alignment needs to be considered, while data is packed.
+ (int fieldSize, int fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
+
+ // Check if the current type is a matrix type with more than one row. In this
+ // case, each row is aligned as if it was a separate array, so the start of
+ // each row needs to be at a multiple of 16 bytes (a float4 register).
+ if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns))
+ {
+ using ImmutableArrayBuilder builder = new();
+
+ for (int j = 0; j < rows; j++)
+ {
+ int startingRawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
+
+ builder.Add(startingRawDataOffset);
+
+ rawDataOffset = startingRawDataOffset + (fieldPack * columns);
+ }
+
+ return new FieldInfo.NonLinearMatrix(
+ fieldPath,
+ typeName,
+ elementName!,
+ rows,
+ columns,
+ builder.ToImmutable());
+ }
+ else
+ {
+ // Calculate the right offset with 16-bytes padding (HLSL constant buffer).
+ // Since we're in a constant buffer, we need to both pad the starting offset
+ // to be aligned to the packing size of the type, and also to align the initial
+ // offset to ensure that values do not cross 16 bytes boundaries either.
+ int startingRawDataOffset = AlignmentHelper.AlignToBoundary(
+ AlignmentHelper.Pad(rawDataOffset, fieldPack),
+ fieldSize,
+ 16);
+
+ rawDataOffset = startingRawDataOffset + fieldSize;
+
+ return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset);
+ }
+ }
+}
\ No newline at end of file