Merge pull request #651 from Sergio0694/dev/primary-constructors-net8-shared
Support primary constructor parameters for DX12 shaders
このコミットが含まれているのは:
23ファイル変更
+998
-952
検索条件に一致するファイルはありません
-415
@@ -1,415 +0,0 @@
|
||||
using System.Linq;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Mappings;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
partial class ConstantBuffer
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes the <c>LoadConstantBuffer</c> method.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteLoadConstantBufferSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
|
||||
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
|
||||
writer.WriteLine($"static unsafe void global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.LoadConstantBuffer<TLoader>(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<byte>(&buffer, sizeof(global::ComputeSharp.D2D1.Generated.ConstantBuffer)));");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the <c>CreateFromConstantBuffer</c> method.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteCreateFromConstantBufferSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
|
||||
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
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<byte> 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<global::ComputeSharp.D2D1.Generated.ConstantBuffer>(data);");
|
||||
writer.WriteLine();
|
||||
writer.WriteLine("return global::ComputeSharp.D2D1.Generated.ConstantBufferMarshaller.ToManaged(in buffer);");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a callback to generate additional types, if needed.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
|
||||
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
|
||||
public static void RegisterAdditionalTypesSyntax(
|
||||
D2D1ShaderInfo info,
|
||||
ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks,
|
||||
ImmutableHashSetBuilder<string> usingDirectives)
|
||||
{
|
||||
// If there are no fields, there is no need for a constant buffer type
|
||||
if (info.Fields.IsEmpty)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_ = usingDirectives.Add("global::System.CodeDom.Compiler");
|
||||
_ = usingDirectives.Add("global::System.Diagnostics");
|
||||
_ = usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
|
||||
_ = usingDirectives.Add("global::System.Runtime.CompilerServices");
|
||||
_ = usingDirectives.Add("global::System.Runtime.InteropServices");
|
||||
|
||||
// Declare the ConstantBuffer type
|
||||
static void ConstantBufferCallback(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName();
|
||||
|
||||
writer.WriteLine($"""/// <summary>""");
|
||||
writer.WriteLine($"""/// A type representing the constant buffer native layout for <see cref="{fullyQualifiedTypeName}"/>.""");
|
||||
writer.WriteLine($"""/// </summary>""");
|
||||
writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false);
|
||||
writer.WriteLine($"""[StructLayout(LayoutKind.Explicit, Size = {info.ConstantBufferSizeInBytes})]""");
|
||||
writer.WriteLine($"""file struct ConstantBuffer""");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
// Declare fields for every mapped item from the shader layout
|
||||
writer.WriteLineSeparatedMembers(info.Fields.AsSpan(), (field, writer) =>
|
||||
{
|
||||
switch (field)
|
||||
{
|
||||
case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive:
|
||||
|
||||
// Append a field as a global::ComputeSharp.Bool value (will use the implicit conversion from bool values)
|
||||
writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName);
|
||||
writer.WriteFieldXmlRemarks(field);
|
||||
writer.WriteLine($"""[FieldOffset({primitive.Offset})]""");
|
||||
writer.WriteLine($"""public global::ComputeSharp.Bool {string.Join("_", primitive.FieldPath.Select(static path => path.Name))};""");
|
||||
break;
|
||||
case FieldInfo.Primitive primitive:
|
||||
|
||||
// Append primitive fields of other types with their mapped names
|
||||
writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName);
|
||||
writer.WriteFieldXmlRemarks(field);
|
||||
writer.WriteLine($"""[FieldOffset({primitive.Offset})]""");
|
||||
writer.WriteLine($"""public {HlslKnownTypes.GetMappedName(primitive.TypeName)} {string.Join("_", primitive.FieldPath.Select(static path => path.Name))};""");
|
||||
break;
|
||||
|
||||
case FieldInfo.NonLinearMatrix matrix:
|
||||
string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}");
|
||||
string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name));
|
||||
|
||||
// Declare a field for every row of the matrix type
|
||||
for (int j = 0; j < matrix.Rows; j++)
|
||||
{
|
||||
writer.WriteLineIf(j > 0);
|
||||
writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName);
|
||||
writer.WriteFieldXmlRemarks(field, row: j);
|
||||
writer.WriteLine($"""[FieldOffset({matrix.Offsets[j]})]""");
|
||||
writer.WriteLine($"""public {rowTypeName} {fieldNamePrefix}_{j};""");
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Declare the ConstantBufferMarshaller type
|
||||
static void ConstantBufferMarshallerCallback(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName();
|
||||
|
||||
writer.WriteLine($"""/// <summary>""");
|
||||
writer.WriteLine($"""/// A type containing marshalling logic for shaders of type <see cref="{fullyQualifiedTypeName}"/>.""");
|
||||
writer.WriteLine($"""/// </summary>""");
|
||||
writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false);
|
||||
writer.WriteLine($"""file static class ConstantBufferMarshaller""");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
// Define the ToManaged method (native constant buffer to managed shader type)
|
||||
writer.WriteLine($"""/// <summary>""");
|
||||
writer.WriteLine($"""/// Marshals native constant buffer data to managed <see cref="{fullyQualifiedTypeName}"/> instances.""");
|
||||
writer.WriteLine($"""/// </summary>""");
|
||||
writer.WriteLine($"""/// <param name="buffer">The input native constant buffer.</param>""");
|
||||
writer.WriteLine($"""/// <returns>The marshalled <see cref="{fullyQualifiedTypeName}"/> instance.</returns>""");
|
||||
writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]""");
|
||||
writer.WriteLine($"""[SkipLocalsInit]""");
|
||||
writer.WriteLine($"public static {fullyQualifiedTypeName} ToManaged(in ConstantBuffer buffer)");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
writer.WriteLine($"Unsafe.SkipInit(out {fullyQualifiedTypeName} shader);");
|
||||
writer.WriteLine();
|
||||
|
||||
// Generate loading statements for each captured field
|
||||
foreach (FieldInfo fieldInfo in info.Fields)
|
||||
{
|
||||
switch (fieldInfo)
|
||||
{
|
||||
case FieldInfo.Primitive primitive:
|
||||
|
||||
// Read a nested primitive value
|
||||
writer.WriteFieldAccessExpression(fieldInfo);
|
||||
writer.WriteLine($" = buffer.{string.Join("_", primitive.FieldPath.Select(static path => path.Name))};");
|
||||
break;
|
||||
|
||||
case FieldInfo.NonLinearMatrix matrix:
|
||||
string primitiveTypeName = matrix.ElementName.ToLowerInvariant();
|
||||
string matrixHlslTypeName = $"{primitiveTypeName}{matrix.Rows}x{matrix.Columns}";
|
||||
string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}");
|
||||
string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name));
|
||||
|
||||
// Get a reference to the whole matrix field, just once for all rows
|
||||
writer.WriteLine(skipIfPresent: true);
|
||||
writer.Write($"ref {matrixHlslTypeName} __{fieldNamePrefix} = ref ");
|
||||
writer.WriteFieldAccessExpression(fieldInfo);
|
||||
writer.WriteLine(";");
|
||||
writer.WriteLine();
|
||||
|
||||
// Read all rows of a given matrix type
|
||||
for (int j = 0; j < matrix.Rows; j++)
|
||||
{
|
||||
writer.WriteLine($"Unsafe.As<{primitiveTypeName}, {rowTypeName}>(ref __{fieldNamePrefix}.M{j + 1}1) = buffer.{fieldNamePrefix}_{j};");
|
||||
}
|
||||
|
||||
writer.WriteLine();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
writer.WriteLine(skipIfPresent: true);
|
||||
writer.WriteLine("return shader;");
|
||||
}
|
||||
|
||||
// Define the FromManaged method (managed shader type to native constant buffer)
|
||||
writer.WriteLine();
|
||||
writer.WriteLine($"""/// <summary>""");
|
||||
writer.WriteLine($"""/// Marshals managed <see cref="{fullyQualifiedTypeName}"/> instances to native constant buffer data.""");
|
||||
writer.WriteLine($"""/// </summary>""");
|
||||
writer.WriteLine($"""/// <param name="buffer">The input native constant buffer.</param>""");
|
||||
writer.WriteLine($"""/// <returns>The marshalled <see cref="{fullyQualifiedTypeName}"/> instance.</returns>""");
|
||||
writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]""");
|
||||
writer.WriteLine($"""[SkipLocalsInit]""");
|
||||
writer.WriteLine($"public static void FromManaged(in {fullyQualifiedTypeName} shader, out ConstantBuffer buffer)");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
// Generate loading statements for each captured field
|
||||
foreach (FieldInfo fieldInfo in info.Fields)
|
||||
{
|
||||
switch (fieldInfo)
|
||||
{
|
||||
case FieldInfo.Primitive primitive:
|
||||
|
||||
// Assign a primitive value
|
||||
writer.Write($"buffer.{string.Join("_", primitive.FieldPath.Select(static path => path.Name))} = ");
|
||||
writer.WriteFieldAccessExpression(fieldInfo);
|
||||
writer.WriteLine(";");
|
||||
break;
|
||||
|
||||
case FieldInfo.NonLinearMatrix matrix:
|
||||
string primitiveTypeName = matrix.ElementName.ToLowerInvariant();
|
||||
string matrixHlslTypeName = $"{primitiveTypeName}{matrix.Rows}x{matrix.Columns}";
|
||||
string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}");
|
||||
string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name));
|
||||
|
||||
// Get a reference to the whole matrix field, just once for all rows
|
||||
writer.WriteLine(skipIfPresent: true);
|
||||
writer.Write($"ref {matrixHlslTypeName} __{fieldNamePrefix} = ref ");
|
||||
writer.WriteFieldAccessExpression(fieldInfo);
|
||||
writer.WriteLine(";");
|
||||
writer.WriteLine();
|
||||
|
||||
// Assign all rows of a given matrix type
|
||||
for (int j = 0; j < matrix.Rows; j++)
|
||||
{
|
||||
writer.WriteLine($"buffer.{fieldNamePrefix}_{j} = Unsafe.As<{primitiveTypeName}, {rowTypeName}>(ref __{fieldNamePrefix}.M{j + 1}1);");
|
||||
}
|
||||
|
||||
writer.WriteLine();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
using ImmutableHashSetBuilder<(string ContainerType, string FieldName)> generatedAccessors = new();
|
||||
|
||||
// Define all field accessors. Note that these are generated regardless of the accessibility
|
||||
// of the field they're getting the value for. This simplifies the rest of the code, and allows
|
||||
// stripping the readonly-ness of the field references, and has no binary size impact anyway.
|
||||
// This is because the fields are compiled to be exactly equivalent to direct field references.
|
||||
foreach (FieldInfo fieldInfo in info.Fields)
|
||||
{
|
||||
for (int i = 0; i < fieldInfo.FieldPath.Length; i++)
|
||||
{
|
||||
FieldPathPart pathPart = fieldInfo.FieldPath[i];
|
||||
|
||||
// Get the friendly type name for the field:
|
||||
// - If the part path is a nested struct, the type name is embedded
|
||||
// - Otherwise, get the correct HLSL mapped type name for the field
|
||||
string typeName = pathPart switch
|
||||
{
|
||||
FieldPathPart.Nested nested => nested.TypeName,
|
||||
FieldPathPart.Leaf when fieldInfo.TypeName is "System.Boolean" => "global::ComputeSharp.Bool",
|
||||
_ => HlslKnownTypes.GetMappedName(fieldInfo.TypeName)
|
||||
};
|
||||
|
||||
// Get the friendly type name for the field. If this nested field is the
|
||||
// first path, then the parent is the shader type itself. Otherwise, the
|
||||
// container path is the type of the previous containing type of the field.
|
||||
string containingTypeName = i == 0
|
||||
? fullyQualifiedTypeName
|
||||
: ((FieldPathPart.Nested)fieldInfo.FieldPath[i - 1]).TypeName;
|
||||
|
||||
// Make sure to skip repeated field accessors. It's possible for some accessors to end up
|
||||
// being required, in case a shader type had multiple fields of the same nested struct type.
|
||||
// To avoid so, we just add the containing type and name to an hashset that we update.
|
||||
if (!generatedAccessors.Add((containingTypeName, pathPart.Name)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
writer.WriteLine();
|
||||
|
||||
// If there is no unspeakable name, we can reference the field directly. This means we can both
|
||||
// use that in XML docs to refer to it (and inherit the docs), and we don't need an explicit name.
|
||||
if (pathPart.UnspeakableName is null)
|
||||
{
|
||||
writer.WriteLine($"""
|
||||
/// <inheritdoc cref="{containingTypeName}.{pathPart.Name}"/>
|
||||
/// <param name="shader">The input <see cref="{containingTypeName}"/> value.</param>
|
||||
/// <returns>A mutable reference to <see cref="{containingTypeName}.{pathPart.Name}"/>.</returns>
|
||||
[UnsafeAccessor(UnsafeAccessorKind.Field)]
|
||||
private static extern ref {typeName} {pathPart.Name}(this ref readonly {containingTypeName} value);
|
||||
""", isMultiline: true);
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteLine($"""
|
||||
/// <summary>Gets a reference to the unspeakable field "{pathPart.Name}" of type <see cref="{containingTypeName}"/>.</summary>
|
||||
/// <param name="shader">The input <see cref="{containingTypeName}"/> value.</param>
|
||||
/// <returns>A mutable reference to the unspeakable field "{pathPart.Name}".</returns>
|
||||
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "{pathPart.UnspeakableName}")]
|
||||
private static extern ref {typeName} {pathPart.Name}(this ref readonly {containingTypeName} value);
|
||||
""", isMultiline: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
callbacks.Add(ConstantBufferCallback);
|
||||
callbacks.Add(ConstantBufferMarshallerCallback);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="SourceGeneration.Extensions.IndentedTextWriterExtensions"/>
|
||||
file static class IndentedTextWriterExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes the XML summary for a given field.
|
||||
/// </summary>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
/// <param name="fieldInfo">The input field to write the XML summary for.</param>
|
||||
/// <param name="fullyQualifiedTypeName">The fully qualified type name of the containing type.</param>
|
||||
public static void WriteFieldXmlSummary(this IndentedTextWriter writer, FieldInfo fieldInfo, string fullyQualifiedTypeName)
|
||||
{
|
||||
if (fieldInfo.FieldPath[0].UnspeakableName is null)
|
||||
{
|
||||
writer.WriteLine($"""/// <inheritdoc cref="{fullyQualifiedTypeName}.{fieldInfo.FieldPath[0].Name}"/>""");
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteLine($"""/// <summary>The unspeakable field "{fieldInfo.FieldPath[0].Name}" of <see cref="{fullyQualifiedTypeName}"/>.</summary>""");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the XML remarks for a given field, if needed.
|
||||
/// </summary>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
/// <param name="fieldInfo">The input field to write the XML remarks for, if needed.</param>
|
||||
/// <param name="row">The row for the field, if this is a matrix type.</param>
|
||||
public static void WriteFieldXmlRemarks(this IndentedTextWriter writer, FieldInfo fieldInfo, int? row = null)
|
||||
{
|
||||
// The remarks are only needed if the field is nested
|
||||
if (fieldInfo.FieldPath is not [.., FieldPathPart.Nested nested, FieldPathPart.Leaf leaf])
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Write the correct remarks depending on whether the field can be referenced directly
|
||||
if (leaf.UnspeakableName is null)
|
||||
{
|
||||
writer.Write($"""/// <remarks>Serialized field mapping to""");
|
||||
writer.WriteIf(row is not null, $""" row {row} of""");
|
||||
writer.WriteLine($""" <see cref="{nested.TypeName}.{leaf.Name}"/>.</remarks>""");
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.Write($"""/// <remarks>Serialized field mapping to""");
|
||||
writer.WriteIf(row is not null, $""" row {row} of""");
|
||||
writer.WriteLine($""" the unspeakable field "{leaf.Name}" of <see cref="{nested.TypeName}"/>.</remarks>""");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes an expression to access a given field.
|
||||
/// </summary>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
/// <param name="fieldInfo">The input field to write the expression for.</param>
|
||||
public static void WriteFieldAccessExpression(this IndentedTextWriter writer, FieldInfo fieldInfo)
|
||||
{
|
||||
writer.Write("shader");
|
||||
|
||||
// Invoke all generated field accessors to get to the target field.
|
||||
// Because they're extension methods, we can chain them sequentially.
|
||||
// This simplifies the formatting and makes the code easier to read.
|
||||
foreach (FieldPathPart part in fieldInfo.FieldPath)
|
||||
{
|
||||
writer.Write($".{part.Name}()");
|
||||
}
|
||||
}
|
||||
}
|
||||
+58
-167
@@ -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;
|
||||
|
||||
@@ -16,26 +14,16 @@ namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the <c>ConstantBuffer</c> methods and additional types.
|
||||
/// A helper with all logic to generate the constant buffer marshalling methods and additional types.
|
||||
/// </summary>
|
||||
private static partial class ConstantBuffer
|
||||
private static class ConstantBuffer
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see cref="Regex"/> to extract the parameter name of a primary constructor capture field.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Temporary workaround until <see href="https://github.com/dotnet/roslyn/issues/70208"/> is available.
|
||||
/// </remarks>
|
||||
private static readonly Regex PrimaryConstructorNameRegex = new("^<([^>]+)>P$", RegexOptions.Compiled);
|
||||
|
||||
/// <summary>
|
||||
/// Explores a given type hierarchy and generates statements to load fields.
|
||||
/// </summary>
|
||||
/// <inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo"/>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The current shader type being explored.</param>
|
||||
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
|
||||
/// <param name="fields">The sequence of <see cref="FieldInfo"/> instances for all captured values.</param>
|
||||
/// <param name="compilation"><inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo" path="/param[@name='compilation']/node()"/></param>
|
||||
/// <param name="structDeclarationSymbol"><inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo" path="/param[@name='structDeclarationSymbol']/node()"/></param>
|
||||
/// <param name="constantBufferSizeInBytes"><inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo" path="/param[@name='constantBufferSizeInBytes']/node()"/></param>
|
||||
/// <param name="fields"><inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo" path="/param[@name='fields']/node()"/></param>
|
||||
public static void GetInfo(
|
||||
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
|
||||
Compilation compilation,
|
||||
@@ -43,79 +31,13 @@ partial class D2DPixelShaderDescriptorGenerator
|
||||
out int constantBufferSizeInBytes,
|
||||
out ImmutableArray<FieldInfo> fields)
|
||||
{
|
||||
// Helper method that uses boxes instead of ref-s (illegal in enumerators)
|
||||
static void GetInfo(
|
||||
Compilation compilation,
|
||||
ITypeSymbol currentTypeSymbol,
|
||||
ImmutableArray<FieldPathPart> fieldPath,
|
||||
ref int rawDataOffset,
|
||||
ImmutableArrayBuilder<FieldInfo> fields)
|
||||
{
|
||||
bool isFirstField = true;
|
||||
constantBufferSizeInBytes = 0;
|
||||
|
||||
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<FieldPathPart> 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<FieldInfo> fieldBuilder = new())
|
||||
{
|
||||
// Traverse all shader fields and gather info, and update the tracking offsets
|
||||
GetInfo(
|
||||
compilation,
|
||||
structDeclarationSymbol,
|
||||
ImmutableArray<FieldPathPart>.Empty,
|
||||
ref rawDataOffset,
|
||||
fieldBuilder);
|
||||
|
||||
constantBufferSizeInBytes = rawDataOffset;
|
||||
fields = fieldBuilder.ToImmutable();
|
||||
}
|
||||
ConstantBufferSyntaxProcessor.GetInfo(
|
||||
compilation,
|
||||
structDeclarationSymbol,
|
||||
ref constantBufferSizeInBytes,
|
||||
out fields);
|
||||
|
||||
// The maximum size for a constant buffer is 64KB
|
||||
const int D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT = 4096;
|
||||
@@ -129,95 +51,64 @@ partial class D2DPixelShaderDescriptorGenerator
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the field name and the accessor name for a given field.
|
||||
/// Writes the <c>LoadConstantBuffer</c> method.
|
||||
/// </summary>
|
||||
/// <param name="fieldSymbol">The field symbol to analyze.</param>
|
||||
/// <param name="referencedName">The name of the field that's referenced in code by users.</param>
|
||||
/// <param name="unspeakableName">The real name of the field that should be accessed, when different.</param>
|
||||
/// <returns>Whether the field is supported and the necessary info could be retrieved.</returns>
|
||||
public static bool TryGetFieldAccessorName(
|
||||
IFieldSymbol fieldSymbol,
|
||||
[NotNullWhen(true)] out string? referencedName,
|
||||
out string? unspeakableName)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
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("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
|
||||
writer.WriteLine($"static unsafe void global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.LoadConstantBuffer<TLoader>(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<byte>(&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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets info on a given captured HLSL primitive type (either a scalar, a vector or a matrix).
|
||||
/// Writes the <c>CreateFromConstantBuffer</c> method.
|
||||
/// </summary>
|
||||
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
|
||||
/// <param name="typeName">The type name currently being read.</param>
|
||||
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
|
||||
private static FieldInfo GetHlslKnownTypeFieldInfo(
|
||||
ImmutableArray<FieldPathPart> fieldPath,
|
||||
string typeName,
|
||||
ref int rawDataOffset)
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
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("/// <inheritdoc/>");
|
||||
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<byte> data)");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
using ImmutableArrayBuilder<int> 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<global::ComputeSharp.D2D1.Generated.ConstantBuffer>(data);");
|
||||
writer.WriteLine();
|
||||
writer.WriteLine("return global::ComputeSharp.D2D1.Generated.ConstantBufferMarshaller.ToManaged(in buffer);");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -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;
|
||||
}
|
||||
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class D2DPixelShaderDescriptorGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
partial class PixelOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes the <c>PixelOptions</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
// Set the right expression if the pixel options are valid
|
||||
string pixelOptionsExpression = (info.PixelOptions is D2D1PixelOptions.None or D2D1PixelOptions.TrivialSampling) switch
|
||||
{
|
||||
true => $"global::ComputeSharp.D2D1.D2D1PixelOptions.{info.PixelOptions}",
|
||||
false => "default"
|
||||
};
|
||||
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine($"static ComputeSharp.D2D1.D2D1PixelOptions global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.PixelOptions => {pixelOptionsExpression};");
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
-1
@@ -1,4 +1,6 @@
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1.SourceGenerators;
|
||||
@@ -9,7 +11,7 @@ partial class D2DPixelShaderDescriptorGenerator
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the <c>PixelOptions</c> property.
|
||||
/// </summary>
|
||||
private static partial class PixelOptions
|
||||
private static class PixelOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Extracts the pixel options for the current shader.
|
||||
@@ -27,5 +29,24 @@ partial class D2DPixelShaderDescriptorGenerator
|
||||
pixelOptions = D2D1PixelOptions.None;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the <c>PixelOptions</c> property.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
// Set the right expression if the pixel options are valid
|
||||
string pixelOptionsExpression = (info.PixelOptions is D2D1PixelOptions.None or D2D1PixelOptions.TrivialSampling) switch
|
||||
{
|
||||
true => $"global::ComputeSharp.D2D1.D2D1PixelOptions.{info.PixelOptions}",
|
||||
false => "default"
|
||||
};
|
||||
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine($"static ComputeSharp.D2D1.D2D1PixelOptions global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.PixelOptions => {pixelOptionsExpression};");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using ComputeSharp.D2D1.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using ComputeSharp.SourceGeneration.SyntaxProcessors;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
@@ -233,7 +235,7 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene
|
||||
using ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> additionalTypes = new();
|
||||
using ImmutableHashSetBuilder<string> usingDirectives = new();
|
||||
|
||||
ConstantBuffer.RegisterAdditionalTypesSyntax(item, additionalTypes, usingDirectives);
|
||||
ConstantBufferSyntaxProcessor.RegisterAdditionalTypesSyntax(GeneratorName, BindingDirection.TwoWay, item, additionalTypes, usingDirectives);
|
||||
InputDescriptions.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
|
||||
InputTypes.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
|
||||
HlslBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
|
||||
|
||||
@@ -40,4 +40,4 @@ internal sealed record D2D1ShaderInfo(
|
||||
D2D1PixelOptions PixelOptions,
|
||||
HlslBytecodeInfoKey HlslInfoKey,
|
||||
HlslBytecodeInfo HlslInfo,
|
||||
EquatableArray<DiagnosticInfo> Diagnostcs);
|
||||
EquatableArray<DiagnosticInfo> Diagnostcs) : IConstantBufferInfo;
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
namespace ComputeSharp.SourceGeneration.SyntaxProcessors;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class ConstantBufferSyntaxProcessor
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
private static partial bool HasArtificialFields()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -26,9 +26,12 @@
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Mappings\HlslKnownTypes.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Models\FieldInfo.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Models\HlslBytecodeInfo.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Models\Interfaces\IConstantBufferInfo.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)SyntaxProcessors\ConstantBufferSyntaxProcessor.Generation.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)SyntaxRewriters\HlslSourceRewriter.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)SyntaxRewriters\HlslSourceRewriter.Diagnostics.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)SyntaxRewriters\ShaderSourceRewriter.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)SyntaxRewriters\StaticFieldRewriter.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)SyntaxProcessors\ConstantBufferSyntaxProcessor.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,24 @@
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
|
||||
namespace ComputeSharp.SourceGeneration.Models;
|
||||
|
||||
/// <summary>
|
||||
/// An interface for a model providing info on constant buffer fields.
|
||||
/// </summary>
|
||||
internal interface IConstantBufferInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// The hierarchy info for the shader type.
|
||||
/// </summary>
|
||||
HierarchyInfo Hierarchy { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The size of the shader constant buffer.
|
||||
/// </summary>
|
||||
int ConstantBufferSizeInBytes { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The description on shader instance fields.
|
||||
/// </summary>
|
||||
EquatableArray<FieldInfo> Fields { get; }
|
||||
}
|
||||
+409
@@ -0,0 +1,409 @@
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Mappings;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
|
||||
namespace ComputeSharp.SourceGeneration.SyntaxProcessors;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class ConstantBufferSyntaxProcessor
|
||||
{
|
||||
/// <summary>
|
||||
/// The name of generator to include in the generated code.
|
||||
/// </summary>
|
||||
private static string? generatorName;
|
||||
|
||||
/// <summary>
|
||||
/// The direction to generate marshalling code for.
|
||||
/// </summary>
|
||||
private static BindingDirection direction;
|
||||
|
||||
/// <summary>
|
||||
/// Registers a callback to generate additional types, if needed.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInfo">The type of model providing the necessary info.</typeparam>
|
||||
/// <param name="generatorName">The name of generator to include in the generated code.</param>
|
||||
/// <param name="direction">The direction to generate marshalling code for.</param>
|
||||
/// <param name="info">The input <typeparamref name="TInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
|
||||
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
|
||||
public static void RegisterAdditionalTypesSyntax<TInfo>(
|
||||
string generatorName,
|
||||
BindingDirection direction,
|
||||
TInfo info,
|
||||
ImmutableArrayBuilder<IndentedTextWriter.Callback<TInfo>> callbacks,
|
||||
ImmutableHashSetBuilder<string> usingDirectives)
|
||||
where TInfo : class, IConstantBufferInfo
|
||||
{
|
||||
// Store the generator name and marshalling direction for later. This avoids needing closures for each
|
||||
// callback below. It is assumed that all calls to this method will have the same arguments in each assembly.
|
||||
ConstantBufferSyntaxProcessor.generatorName = generatorName;
|
||||
ConstantBufferSyntaxProcessor.direction = direction;
|
||||
|
||||
// If there are no fields (including artificial ones), there is no need for a constant buffer type
|
||||
if (info.Fields.IsEmpty && !HasArtificialFields())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_ = usingDirectives.Add("global::System.CodeDom.Compiler");
|
||||
_ = usingDirectives.Add("global::System.Diagnostics");
|
||||
_ = usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
|
||||
_ = usingDirectives.Add("global::System.Runtime.CompilerServices");
|
||||
_ = usingDirectives.Add("global::System.Runtime.InteropServices");
|
||||
|
||||
// Declare the ConstantBuffer type
|
||||
static void ConstantBufferCallback(TInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName();
|
||||
|
||||
writer.WriteLine($"""/// <summary>""");
|
||||
writer.WriteLine($"""/// A type representing the constant buffer native layout for <see cref="{fullyQualifiedTypeName}"/>.""");
|
||||
writer.WriteLine($"""/// </summary>""");
|
||||
writer.WriteGeneratedAttributes(ConstantBufferSyntaxProcessor.generatorName!, useFullyQualifiedTypeNames: false);
|
||||
writer.WriteLine($"""[StructLayout(LayoutKind.Explicit, Size = {info.ConstantBufferSizeInBytes})]""");
|
||||
writer.WriteLine($"""file struct ConstantBuffer""");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
// Append any artificial fields, if needed
|
||||
AppendArtificialFields(info, writer);
|
||||
|
||||
// Declare fields for every mapped item from the shader layout
|
||||
writer.WriteLineSeparatedMembers(info.Fields.AsSpan(), (field, writer) =>
|
||||
{
|
||||
switch (field)
|
||||
{
|
||||
case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive:
|
||||
|
||||
// Append a field as a global::ComputeSharp.Bool value (will use the implicit conversion from bool values)
|
||||
writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName);
|
||||
writer.WriteFieldXmlRemarks(field);
|
||||
writer.WriteLine($"""[FieldOffset({primitive.Offset})]""");
|
||||
writer.WriteLine($"""public global::ComputeSharp.Bool {string.Join("_", primitive.FieldPath.Select(static path => path.Name))};""");
|
||||
break;
|
||||
case FieldInfo.Primitive primitive:
|
||||
|
||||
// Append primitive fields of other types with their mapped names
|
||||
writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName);
|
||||
writer.WriteFieldXmlRemarks(field);
|
||||
writer.WriteLine($"""[FieldOffset({primitive.Offset})]""");
|
||||
writer.WriteLine($"""public {HlslKnownTypes.GetMappedName(primitive.TypeName)} {string.Join("_", primitive.FieldPath.Select(static path => path.Name))};""");
|
||||
break;
|
||||
|
||||
case FieldInfo.NonLinearMatrix matrix:
|
||||
string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}");
|
||||
string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name));
|
||||
|
||||
// Declare a field for every row of the matrix type
|
||||
for (int j = 0; j < matrix.Rows; j++)
|
||||
{
|
||||
writer.WriteLineIf(j > 0);
|
||||
writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName);
|
||||
writer.WriteFieldXmlRemarks(field, row: j);
|
||||
writer.WriteLine($"""[FieldOffset({matrix.Offsets[j]})]""");
|
||||
writer.WriteLine($"""public {rowTypeName} {fieldNamePrefix}_{j};""");
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Declare the ConstantBufferMarshaller type
|
||||
static void ConstantBufferMarshallerCallback(TInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName();
|
||||
|
||||
writer.WriteLine($"""/// <summary>""");
|
||||
writer.WriteLine($"""/// A type containing marshalling logic for shaders of type <see cref="{fullyQualifiedTypeName}"/>.""");
|
||||
writer.WriteLine($"""/// </summary>""");
|
||||
writer.WriteGeneratedAttributes(ConstantBufferSyntaxProcessor.generatorName!, useFullyQualifiedTypeNames: false);
|
||||
writer.WriteLine($"""file static class ConstantBufferMarshaller""");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
// Define the FromManaged method (managed shader type to native constant buffer)
|
||||
writer.WriteLine($"""/// <summary>""");
|
||||
writer.WriteLine($"""/// Marshals managed <see cref="{fullyQualifiedTypeName}"/> instances to native constant buffer data.""");
|
||||
writer.WriteLine($"""/// </summary>""");
|
||||
writer.WriteLine($"""/// <param name="buffer">The input native constant buffer.</param>""");
|
||||
writer.WriteLine($"""/// <returns>The marshalled <see cref="{fullyQualifiedTypeName}"/> instance.</returns>""");
|
||||
writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]""");
|
||||
writer.WriteLine($"""[SkipLocalsInit]""");
|
||||
writer.WriteLine($"public static void FromManaged(in {fullyQualifiedTypeName} shader, out ConstantBuffer buffer)");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
// Initialize any artificial fields, if needed. This is necessary to avoid compiler errors due to
|
||||
// the resulting constant buffer not being fully initialized, in case it had some extra fields.
|
||||
InitializeArtificialFields(info, writer);
|
||||
|
||||
// Generate loading statements for each captured field
|
||||
foreach (FieldInfo fieldInfo in info.Fields)
|
||||
{
|
||||
switch (fieldInfo)
|
||||
{
|
||||
case FieldInfo.Primitive primitive:
|
||||
|
||||
// Assign a primitive value
|
||||
writer.Write($"buffer.{string.Join("_", primitive.FieldPath.Select(static path => path.Name))} = ");
|
||||
writer.WriteFieldAccessExpression(fieldInfo);
|
||||
writer.WriteLine(";");
|
||||
break;
|
||||
|
||||
case FieldInfo.NonLinearMatrix matrix:
|
||||
string primitiveTypeName = matrix.ElementName.ToLowerInvariant();
|
||||
string matrixHlslTypeName = $"{primitiveTypeName}{matrix.Rows}x{matrix.Columns}";
|
||||
string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}");
|
||||
string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name));
|
||||
|
||||
// Get a reference to the whole matrix field, just once for all rows
|
||||
writer.WriteLine(skipIfPresent: true);
|
||||
writer.Write($"ref {matrixHlslTypeName} __{fieldNamePrefix} = ref ");
|
||||
writer.WriteFieldAccessExpression(fieldInfo);
|
||||
writer.WriteLine(";");
|
||||
writer.WriteLine();
|
||||
|
||||
// Assign all rows of a given matrix type
|
||||
for (int j = 0; j < matrix.Rows; j++)
|
||||
{
|
||||
writer.WriteLine($"buffer.{fieldNamePrefix}_{j} = Unsafe.As<{primitiveTypeName}, {rowTypeName}>(ref __{fieldNamePrefix}.M{j + 1}1);");
|
||||
}
|
||||
|
||||
writer.WriteLine();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only generate the other direction if requested
|
||||
if (ConstantBufferSyntaxProcessor.direction == BindingDirection.TwoWay)
|
||||
{
|
||||
// Define the ToManaged method (native constant buffer to managed shader type)
|
||||
writer.WriteLine();
|
||||
writer.WriteLine($"""/// <summary>""");
|
||||
writer.WriteLine($"""/// Marshals native constant buffer data to managed <see cref="{fullyQualifiedTypeName}"/> instances.""");
|
||||
writer.WriteLine($"""/// </summary>""");
|
||||
writer.WriteLine($"""/// <param name="buffer">The input native constant buffer.</param>""");
|
||||
writer.WriteLine($"""/// <returns>The marshalled <see cref="{fullyQualifiedTypeName}"/> instance.</returns>""");
|
||||
writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]""");
|
||||
writer.WriteLine($"""[SkipLocalsInit]""");
|
||||
writer.WriteLine($"public static {fullyQualifiedTypeName} ToManaged(in ConstantBuffer buffer)");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
writer.WriteLine($"Unsafe.SkipInit(out {fullyQualifiedTypeName} shader);");
|
||||
writer.WriteLine();
|
||||
|
||||
// Generate loading statements for each captured field
|
||||
foreach (FieldInfo fieldInfo in info.Fields)
|
||||
{
|
||||
switch (fieldInfo)
|
||||
{
|
||||
case FieldInfo.Primitive primitive:
|
||||
|
||||
// Read a nested primitive value
|
||||
writer.WriteFieldAccessExpression(fieldInfo);
|
||||
writer.WriteLine($" = buffer.{string.Join("_", primitive.FieldPath.Select(static path => path.Name))};");
|
||||
break;
|
||||
|
||||
case FieldInfo.NonLinearMatrix matrix:
|
||||
string primitiveTypeName = matrix.ElementName.ToLowerInvariant();
|
||||
string matrixHlslTypeName = $"{primitiveTypeName}{matrix.Rows}x{matrix.Columns}";
|
||||
string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}");
|
||||
string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name));
|
||||
|
||||
// Get a reference to the whole matrix field, just once for all rows
|
||||
writer.WriteLine(skipIfPresent: true);
|
||||
writer.Write($"ref {matrixHlslTypeName} __{fieldNamePrefix} = ref ");
|
||||
writer.WriteFieldAccessExpression(fieldInfo);
|
||||
writer.WriteLine(";");
|
||||
writer.WriteLine();
|
||||
|
||||
// Read all rows of a given matrix type
|
||||
for (int j = 0; j < matrix.Rows; j++)
|
||||
{
|
||||
writer.WriteLine($"Unsafe.As<{primitiveTypeName}, {rowTypeName}>(ref __{fieldNamePrefix}.M{j + 1}1) = buffer.{fieldNamePrefix}_{j};");
|
||||
}
|
||||
|
||||
writer.WriteLine();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
writer.WriteLine(skipIfPresent: true);
|
||||
writer.WriteLine("return shader;");
|
||||
}
|
||||
}
|
||||
|
||||
using ImmutableHashSetBuilder<(string ContainerType, string FieldName)> generatedAccessors = new();
|
||||
|
||||
// Define all field accessors. Note that these are generated regardless of the accessibility
|
||||
// of the field they're getting the value for. This simplifies the rest of the code, and allows
|
||||
// stripping the readonly-ness of the field references, and has no binary size impact anyway.
|
||||
// This is because the fields are compiled to be exactly equivalent to direct field references.
|
||||
foreach (FieldInfo fieldInfo in info.Fields)
|
||||
{
|
||||
for (int i = 0; i < fieldInfo.FieldPath.Length; i++)
|
||||
{
|
||||
FieldPathPart pathPart = fieldInfo.FieldPath[i];
|
||||
|
||||
// Get the friendly type name for the field:
|
||||
// - If the part path is a nested struct, the type name is embedded
|
||||
// - Otherwise, get the correct HLSL mapped type name for the field
|
||||
string typeName = pathPart switch
|
||||
{
|
||||
FieldPathPart.Nested nested => nested.TypeName,
|
||||
_ => HlslKnownTypes.GetMappedName(fieldInfo.TypeName)
|
||||
};
|
||||
|
||||
// Get the friendly type name for the field. If this nested field is the
|
||||
// first path, then the parent is the shader type itself. Otherwise, the
|
||||
// container path is the type of the previous containing type of the field.
|
||||
string containingTypeName = i == 0
|
||||
? fullyQualifiedTypeName
|
||||
: ((FieldPathPart.Nested)fieldInfo.FieldPath[i - 1]).TypeName;
|
||||
|
||||
// Make sure to skip repeated field accessors. It's possible for some accessors to end up
|
||||
// being required, in case a shader type had multiple fields of the same nested struct type.
|
||||
// To avoid so, we just add the containing type and name to an hashset that we update.
|
||||
if (!generatedAccessors.Add((containingTypeName, pathPart.Name)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
writer.WriteLine();
|
||||
|
||||
// If there is no unspeakable name, we can reference the field directly. This means we can both
|
||||
// use that in XML docs to refer to it (and inherit the docs), and we don't need an explicit name.
|
||||
if (pathPart.UnspeakableName is null)
|
||||
{
|
||||
writer.WriteLine($"""
|
||||
/// <inheritdoc cref="{containingTypeName}.{pathPart.Name}"/>
|
||||
/// <param name="shader">The input <see cref="{containingTypeName}"/> value.</param>
|
||||
/// <returns>A mutable reference to <see cref="{containingTypeName}.{pathPart.Name}"/>.</returns>
|
||||
[UnsafeAccessor(UnsafeAccessorKind.Field)]
|
||||
private static extern ref {typeName} {pathPart.Name}(this ref readonly {containingTypeName} value);
|
||||
""", isMultiline: true);
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteLine($"""
|
||||
/// <summary>Gets a reference to the unspeakable field "{pathPart.Name}" of type <see cref="{containingTypeName}"/>.</summary>
|
||||
/// <param name="shader">The input <see cref="{containingTypeName}"/> value.</param>
|
||||
/// <returns>A mutable reference to the unspeakable field "{pathPart.Name}".</returns>
|
||||
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "{pathPart.UnspeakableName}")]
|
||||
private static extern ref {typeName} {pathPart.Name}(this ref readonly {containingTypeName} value);
|
||||
""", isMultiline: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
callbacks.Add(ConstantBufferCallback);
|
||||
|
||||
// Only emit the marshaller type if there are any non artificial fields.
|
||||
// Otherwise, it's not needed, as there are either just no fields at all,
|
||||
// or only artificial ones, which would be assigned directly by callers.
|
||||
if (!info.Fields.IsEmpty)
|
||||
{
|
||||
callbacks.Add(ConstantBufferMarshallerCallback);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether any artificial fields are present.
|
||||
/// </summary>
|
||||
/// <returns>Whether any artificial fields are present.</returns>
|
||||
private static partial bool HasArtificialFields();
|
||||
|
||||
/// <summary>
|
||||
/// Appends any artificial fields to the generated constant buffer type.
|
||||
/// </summary>
|
||||
/// <param name="info">The <see cref="IConstantBufferInfo"/> instance to use to extract info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
/// <remarks>This method is responsible for leaving trailing blanklines, if it adds any fields.</remarks>
|
||||
static partial void AppendArtificialFields(IConstantBufferInfo info, IndentedTextWriter writer);
|
||||
|
||||
/// <summary>
|
||||
/// Initializes any artificial fields that have been generated into the constant buffer.
|
||||
/// </summary>
|
||||
/// <param name="info">The <see cref="IConstantBufferInfo"/> instance to use to extract info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
/// <remarks>This method is responsible for leaving trailing blanklines, if it emits any statements.</remarks>
|
||||
static partial void InitializeArtificialFields(IConstantBufferInfo info, IndentedTextWriter writer);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Extensions.IndentedTextWriterExtensions"/>
|
||||
file static class IndentedTextWriterExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes the XML summary for a given field.
|
||||
/// </summary>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
/// <param name="fieldInfo">The input field to write the XML summary for.</param>
|
||||
/// <param name="fullyQualifiedTypeName">The fully qualified type name of the containing type.</param>
|
||||
public static void WriteFieldXmlSummary(this IndentedTextWriter writer, FieldInfo fieldInfo, string fullyQualifiedTypeName)
|
||||
{
|
||||
if (fieldInfo.FieldPath[0].UnspeakableName is null)
|
||||
{
|
||||
writer.WriteLine($"""/// <inheritdoc cref="{fullyQualifiedTypeName}.{fieldInfo.FieldPath[0].Name}"/>""");
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteLine($"""/// <summary>The unspeakable field "{fieldInfo.FieldPath[0].Name}" of <see cref="{fullyQualifiedTypeName}"/>.</summary>""");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the XML remarks for a given field, if needed.
|
||||
/// </summary>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
/// <param name="fieldInfo">The input field to write the XML remarks for, if needed.</param>
|
||||
/// <param name="row">The row for the field, if this is a matrix type.</param>
|
||||
public static void WriteFieldXmlRemarks(this IndentedTextWriter writer, FieldInfo fieldInfo, int? row = null)
|
||||
{
|
||||
// The remarks are only needed if the field is nested
|
||||
if (fieldInfo.FieldPath is not [.., FieldPathPart.Nested nested, FieldPathPart.Leaf leaf])
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Write the correct remarks depending on whether the field can be referenced directly
|
||||
if (leaf.UnspeakableName is null)
|
||||
{
|
||||
writer.Write($"""/// <remarks>Serialized field mapping to""");
|
||||
writer.WriteIf(row is not null, $""" row {row} of""");
|
||||
writer.WriteLine($""" <see cref="{nested.TypeName}.{leaf.Name}"/>.</remarks>""");
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.Write($"""/// <remarks>Serialized field mapping to""");
|
||||
writer.WriteIf(row is not null, $""" row {row} of""");
|
||||
writer.WriteLine($""" the unspeakable field "{leaf.Name}" of <see cref="{nested.TypeName}"/>.</remarks>""");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes an expression to access a given field.
|
||||
/// </summary>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
/// <param name="fieldInfo">The input field to write the expression for.</param>
|
||||
public static void WriteFieldAccessExpression(this IndentedTextWriter writer, FieldInfo fieldInfo)
|
||||
{
|
||||
writer.Write("shader");
|
||||
|
||||
// Invoke all generated field accessors to get to the target field.
|
||||
// Because they're extension methods, we can chain them sequentially.
|
||||
// This simplifies the formatting and makes the code easier to read.
|
||||
foreach (FieldPathPart part in fieldInfo.FieldPath)
|
||||
{
|
||||
writer.Write($".{part.Name}()");
|
||||
}
|
||||
}
|
||||
}
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// A processor responsible for extracting info and writing syntax for the constant buffer syntax for shader types.
|
||||
/// </summary>
|
||||
internal static partial class ConstantBufferSyntaxProcessor
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see cref="Regex"/> to extract the parameter name of a primary constructor capture field.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Temporary workaround until <see href="https://github.com/dotnet/roslyn/issues/70208"/> is available.
|
||||
/// </remarks>
|
||||
private static readonly Regex PrimaryConstructorNameRegex = new("^<([^>]+)>P$", RegexOptions.Compiled);
|
||||
|
||||
/// <summary>
|
||||
/// Explores a given type hierarchy and generates statements to load fields.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The current shader type being explored.</param>
|
||||
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
|
||||
/// <param name="fields">The sequence of <see cref="FieldInfo"/> instances for all captured values.</param>
|
||||
public static void GetInfo(
|
||||
Compilation compilation,
|
||||
ITypeSymbol structDeclarationSymbol,
|
||||
ref int constantBufferSizeInBytes,
|
||||
out ImmutableArray<FieldInfo> fields)
|
||||
{
|
||||
// Helper method that uses boxes instead of ref-s (illegal in enumerators)
|
||||
static void GetInfo(
|
||||
Compilation compilation,
|
||||
ITypeSymbol currentTypeSymbol,
|
||||
ImmutableArray<FieldPathPart> fieldPath,
|
||||
ref int constantBufferSizeInBytes,
|
||||
ImmutableArrayBuilder<FieldInfo> 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)
|
||||
{
|
||||
constantBufferSizeInBytes = AlignmentHelper.Pad(constantBufferSizeInBytes, 16);
|
||||
|
||||
isFirstField = false;
|
||||
}
|
||||
|
||||
if (HlslKnownTypes.IsKnownHlslType(typeName))
|
||||
{
|
||||
ImmutableArray<FieldPathPart> nestedFieldPath = fieldPath.Add(new FieldPathPart.Leaf(fieldName, unspeakableName));
|
||||
|
||||
fields.Add(GetHlslKnownTypeFieldInfo(nestedFieldPath, typeName, ref constantBufferSizeInBytes));
|
||||
}
|
||||
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 constantBufferSizeInBytes, fields);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
using ImmutableArrayBuilder<FieldInfo> fieldBuilder = new();
|
||||
|
||||
// Traverse all shader fields and gather info, and update the tracking offsets
|
||||
GetInfo(
|
||||
compilation,
|
||||
structDeclarationSymbol,
|
||||
ImmutableArray<FieldPathPart>.Empty,
|
||||
ref constantBufferSizeInBytes,
|
||||
fieldBuilder);
|
||||
|
||||
fields = fieldBuilder.ToImmutable();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the field name and the accessor name for a given field.
|
||||
/// </summary>
|
||||
/// <param name="fieldSymbol">The field symbol to analyze.</param>
|
||||
/// <param name="referencedName">The name of the field that's referenced in code by users.</param>
|
||||
/// <param name="unspeakableName">The real name of the field that should be accessed, when different.</param>
|
||||
/// <returns>Whether the field is supported and the necessary info could be retrieved.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets info on a given captured HLSL primitive type (either a scalar, a vector or a matrix).
|
||||
/// </summary>
|
||||
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
|
||||
/// <param name="typeName">The type name currently being read.</param>
|
||||
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
|
||||
private static FieldInfo GetHlslKnownTypeFieldInfo(
|
||||
ImmutableArray<FieldPathPart> 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<int> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.Core.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using ComputeSharp.SourceGeneration.SyntaxProcessors;
|
||||
using ComputeSharp.SourceGenerators.Models;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class ComputeShaderDescriptorGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the constant buffer marshalling methods and additional types.
|
||||
/// </summary>
|
||||
private static class ConstantBuffer
|
||||
{
|
||||
/// <inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo"/>
|
||||
/// <param name="compilation"><inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo" path="/param[@name='compilation']/node()"/></param>
|
||||
/// <param name="structDeclarationSymbol"><inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo" path="/param[@name='structDeclarationSymbol']/node()"/></param>
|
||||
/// <param name="isPixelShaderLike">Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture.</param>
|
||||
/// <param name="constantBufferSizeInBytes"><inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo" path="/param[@name='constantBufferSizeInBytes']/node()"/></param>
|
||||
/// <param name="fields"><inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo" path="/param[@name='fields']/node()"/></param>
|
||||
public static void GetInfo(
|
||||
Compilation compilation,
|
||||
ITypeSymbol structDeclarationSymbol,
|
||||
bool isPixelShaderLike,
|
||||
out int constantBufferSizeInBytes,
|
||||
out ImmutableArray<FieldInfo> fields)
|
||||
{
|
||||
// Setup the resource and byte offsets for tracking. Pixel shaders have only two
|
||||
// implicitly captured int values, as they're always dispatched over a 2D texture.
|
||||
constantBufferSizeInBytes = sizeof(int) * (isPixelShaderLike ? 2 : 3);
|
||||
|
||||
ConstantBufferSyntaxProcessor.GetInfo(
|
||||
compilation,
|
||||
structDeclarationSymbol,
|
||||
ref constantBufferSizeInBytes,
|
||||
out fields);
|
||||
|
||||
// After all the captured fields have been processed, ensure the reported byte size for
|
||||
// the local variables is padded to a multiple of a 32 bit value. This is necessary to
|
||||
// enable loading all the dispatch data after reinterpreting it to a sequence of values
|
||||
// of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds.
|
||||
constantBufferSizeInBytes = AlignmentHelper.Pad(constantBufferSizeInBytes, sizeof(int));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the <c>LoadConstantBuffer</c> method.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
|
||||
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
|
||||
writer.WriteLine($"static unsafe void global::ComputeSharp.Descriptors.IComputeShaderDescriptor<{typeName}>.LoadConstantBuffer<TLoader>(in {typeName} shader, ref TLoader loader, int x, int y, int z)");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
// If there are no fields (ie. there are only artificial ones), just get an uninitialized instance.
|
||||
// All fields (ie. the thread size values) will be assigned directly inline, with no marshalling.
|
||||
if (info.Fields.IsEmpty)
|
||||
{
|
||||
writer.WriteLine("global::System.Runtime.CompilerServices.Unsafe.SkipInit(out global::ComputeSharp.Generated.ConstantBuffer buffer);");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Otherwise, let the generated marshaller create an initialized instance of the constant buffer type
|
||||
writer.WriteLine("global::ComputeSharp.Generated.ConstantBufferMarshaller.FromManaged(in shader, out global::ComputeSharp.Generated.ConstantBuffer buffer);");
|
||||
}
|
||||
|
||||
// Initialize the artificial fields and finally pass a span over the constant buffer
|
||||
writer.WriteLine();
|
||||
writer.WriteLine("buffer.__x = x;");
|
||||
writer.WriteLine("buffer.__y = y;");
|
||||
writer.WriteLineIf(!info.IsPixelShaderLike, "buffer.__z = z;");
|
||||
writer.WriteLineIf(!info.IsPixelShaderLike);
|
||||
writer.WriteLine("loader.LoadConstantBuffer(new global::System.ReadOnlySpan<byte>(&buffer, sizeof(global::ComputeSharp.Generated.ConstantBuffer)));");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-115
@@ -1,115 +0,0 @@
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using ComputeSharp.SourceGenerators.Models;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class ComputeShaderDescriptorGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
partial class DispatchDataLoading
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes the <c>LoadConstantBuffer</c> method.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteLoadConstantBufferSyntax(ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
|
||||
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
|
||||
writer.WriteLine($"static void global::ComputeSharp.Descriptors.IComputeShaderDescriptor<{typeName}>.LoadConstantBuffer<TLoader>(in {typeName} shader, ref TLoader loader, int x, int y, int z)");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
writer.WriteLine($"global::System.Span<byte> span = stackalloc byte[{info.ConstantBufferSizeInBytes}];");
|
||||
|
||||
// Append the statements for the dispatch ranges
|
||||
writer.WriteLine("global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref span[0]) = (uint)x;");
|
||||
writer.WriteLine("global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref span[4]) = (uint)y;");
|
||||
writer.WriteLineIf(!info.IsPixelShaderLike, "global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref span[8]) = (uint)z;");
|
||||
|
||||
// Generate loading statements for each captured field
|
||||
foreach (FieldInfo fieldInfo in info.Fields)
|
||||
{
|
||||
switch (fieldInfo)
|
||||
{
|
||||
case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive:
|
||||
|
||||
// Read a boolean value and cast it to Bool first, which will apply the correct size expansion
|
||||
writer.WriteLine(
|
||||
$"global::System.Runtime.CompilerServices.Unsafe.As<byte, global::ComputeSharp.Bool>(ref span[{primitive.Offset}]) = " +
|
||||
$"(global::ComputeSharp.Bool)shader.{string.Join(".", primitive.FieldPath.Select(static path => path.Name))};");
|
||||
break;
|
||||
case FieldInfo.Primitive primitive:
|
||||
|
||||
// Read a primitive value and serialize it into the target buffer
|
||||
writer.WriteLine(
|
||||
$"global::System.Runtime.CompilerServices.Unsafe.As<byte, global::{primitive.TypeName}>(ref span[{primitive.Offset}]) = " +
|
||||
$"shader.{string.Join(".", primitive.FieldPath.Select(static path => path.Name))};");
|
||||
break;
|
||||
|
||||
case FieldInfo.NonLinearMatrix matrix:
|
||||
string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}";
|
||||
string rowLocalName = $"__{string.Join("_", matrix.FieldPath.Select(static path => path.Name))}__row0";
|
||||
|
||||
// Declare a local to index into individual rows. This will generate:
|
||||
//
|
||||
// ref <ROW_TYPE> <ROW_NAME> = ref global::System.Runtime.CompilerServices.Unsafe.As<global::<TYPE_NAME>, <ROW_TYPE_NAME>>(
|
||||
// ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in <FIELD_PATH>));
|
||||
writer.WriteLine(
|
||||
$"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As<global::{matrix.TypeName}, {rowTypeName}>(" +
|
||||
$"ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in shader.{string.Join(".", matrix.FieldPath.Select(static path => path.Name))}));");
|
||||
|
||||
// Generate the loading code for each individual row, with proper alignment.
|
||||
// This will result in the following (assuming Float2x3 m):
|
||||
//
|
||||
// ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As<global::ComputeSharp.Float2x3, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m));
|
||||
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0);
|
||||
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1);
|
||||
for (int j = 0; j < matrix.Rows; j++)
|
||||
{
|
||||
writer.WriteLine(
|
||||
$"global::System.Runtime.CompilerServices.Unsafe.As<byte, {rowTypeName}>(ref span[{matrix.Offsets[j]}]) = " +
|
||||
$"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j});");
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Load the prepared buffer
|
||||
writer.WriteLine("loader.LoadConstantBuffer(span);");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the <c>LoadGraphicsResources</c> method.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteLoadGraphicsResourcesSyntax(ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
|
||||
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine($"static void global::ComputeSharp.Descriptors.IComputeShaderDescriptor<{typeName}>.LoadGraphicsResources<TLoader>(in {typeName} shader, ref TLoader loader)");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
// Generate loading statements for each captured resource
|
||||
foreach (ResourceInfo resource in info.Resources)
|
||||
{
|
||||
writer.WriteLine($"loader.LoadGraphicsResource(shader.{resource.FieldName}, {resource.Offset});");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-197
@@ -1,197 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.Core.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Mappings;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using ComputeSharp.SourceGenerators.Models;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class ComputeShaderDescriptorGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the dispatch data loading methods.
|
||||
/// </summary>
|
||||
private static partial class DispatchDataLoading
|
||||
{
|
||||
/// <summary>
|
||||
/// Explores a given type hierarchy and generates statements to load fields.
|
||||
/// </summary>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The current shader type being explored.</param>
|
||||
/// <param name="isPixelShaderLike">Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture.</param>
|
||||
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
|
||||
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
|
||||
/// <param name="fields">The sequence of <see cref="FieldInfo"/> instances for all captured values.</param>
|
||||
/// <param name="resources">The sequence of <see cref="ResourceInfo"/> instances for all captured resources.</param>
|
||||
public static void GetInfo(
|
||||
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
|
||||
Compilation compilation,
|
||||
ITypeSymbol structDeclarationSymbol,
|
||||
bool isPixelShaderLike,
|
||||
out int constantBufferSizeInBytes,
|
||||
out int resourceCount,
|
||||
out ImmutableArray<FieldInfo> fields,
|
||||
out ImmutableArray<ResourceInfo> resources)
|
||||
{
|
||||
static void GetInfo(
|
||||
Compilation compilation,
|
||||
ITypeSymbol currentTypeSymbol,
|
||||
ImmutableArray<FieldPathPart> fieldPath,
|
||||
ref int resourceOffset,
|
||||
ref int rawDataOffset,
|
||||
ImmutableArrayBuilder<FieldInfo> fields,
|
||||
ImmutableArrayBuilder<ResourceInfo> resources)
|
||||
{
|
||||
bool isFirstField = true;
|
||||
|
||||
foreach (ISymbol memberSymbol in currentTypeSymbol.GetMembers())
|
||||
{
|
||||
// Only process fields
|
||||
if (memberSymbol is not IFieldSymbol { Type: INamedTypeSymbol { IsStatic: false }, IsConst: false, IsStatic: false, IsFixedSizeBuffer: false, IsImplicitlyDeclared: false } fieldSymbol)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip fields of not accessible types (the analyzer will handle this)
|
||||
if (!fieldSymbol.Type.IsAccessibleFromCompilationAssembly(compilation))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
string fieldName = fieldSymbol.Name;
|
||||
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.IsTypedResourceType(typeName))
|
||||
{
|
||||
resources.Add(new ResourceInfo(fieldName, typeName, resourceOffset++));
|
||||
}
|
||||
else if (HlslKnownTypes.IsKnownHlslType(typeName))
|
||||
{
|
||||
// TODO: share the logic and fix the field path parts
|
||||
fields.Add(GetHlslKnownTypeFieldInfo(fieldPath.Add(new FieldPathPart.Leaf(fieldName, null)), typeName, ref rawDataOffset));
|
||||
}
|
||||
else if (fieldSymbol.Type.IsUnmanagedType)
|
||||
{
|
||||
// Custom struct type defined by the user
|
||||
GetInfo(compilation, fieldSymbol.Type, fieldPath.Add(new FieldPathPart.Leaf(fieldName, null)), ref resourceOffset, ref rawDataOffset, fields, resources);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Setup the resource and byte offsets for tracking. Pixel shaders have only two
|
||||
// implicitly captured int values, as they're always dispatched over a 2D texture.
|
||||
int rawDataOffset = sizeof(int) * (isPixelShaderLike ? 2 : 3);
|
||||
int resourceOffset = 0;
|
||||
|
||||
using (ImmutableArrayBuilder<FieldInfo> fieldBuilder = new())
|
||||
using (ImmutableArrayBuilder<ResourceInfo> resourceBuilder = new())
|
||||
{
|
||||
// Traverse all shader fields and gather info, and update the tracking offsets
|
||||
GetInfo(
|
||||
compilation,
|
||||
structDeclarationSymbol,
|
||||
ImmutableArray<FieldPathPart>.Empty,
|
||||
ref resourceOffset,
|
||||
ref rawDataOffset,
|
||||
fieldBuilder,
|
||||
resourceBuilder);
|
||||
|
||||
resourceCount = resourceOffset;
|
||||
fields = fieldBuilder.ToImmutable();
|
||||
resources = resourceBuilder.ToImmutable();
|
||||
}
|
||||
|
||||
// After all the captured fields have been processed, ensure the reported byte size for
|
||||
// the local variables is padded to a multiple of a 32 bit value. This is necessary to
|
||||
// enable loading all the dispatch data after reinterpreting it to a sequence of values
|
||||
// of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds.
|
||||
constantBufferSizeInBytes = AlignmentHelper.Pad(rawDataOffset, sizeof(int));
|
||||
|
||||
// A shader root signature has a maximum size of 64 DWORDs, so 256 bytes.
|
||||
// Loaded values in the root signature have the following costs:
|
||||
// - Root constants cost 1 DWORD each, since they are 32-bit values.
|
||||
// - Descriptor tables cost 1 DWORD each.
|
||||
// - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each.
|
||||
// So here we check whether the current signature respects that constraint,
|
||||
// and emit a build error otherwise. For more info on this, see the docs here:
|
||||
// https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits.
|
||||
int root32BitConstantCount = (constantBufferSizeInBytes / sizeof(int)) + resourceCount;
|
||||
|
||||
if (root32BitConstantCount > 64)
|
||||
{
|
||||
diagnostics.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets info on a given captured HLSL primitive type (either a scalar, a vector or a matrix).
|
||||
/// </summary>
|
||||
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
|
||||
/// <param name="typeName">The type name currently being read.</param>
|
||||
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
|
||||
private static FieldInfo GetHlslKnownTypeFieldInfo(
|
||||
ImmutableArray<FieldPathPart> 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<int> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -16,7 +16,7 @@ partial class ComputeShaderDescriptorGenerator
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteHlslBytecodeSyntax(ShaderInfo info, IndentedTextWriter writer)
|
||||
public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Mappings;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using ComputeSharp.SourceGenerators.Models;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class ComputeShaderDescriptorGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the resources loading code.
|
||||
/// </summary>
|
||||
private static class Resources
|
||||
{
|
||||
/// <summary>
|
||||
/// Explores a given type hierarchy and generates statements to load fields.
|
||||
/// </summary>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The current shader type being explored.</param>
|
||||
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
|
||||
/// <param name="resources">The sequence of <see cref="ResourceInfo"/> instances for all captured resources.</param>
|
||||
public static void GetInfo(
|
||||
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
|
||||
Compilation compilation,
|
||||
ITypeSymbol structDeclarationSymbol,
|
||||
int constantBufferSizeInBytes,
|
||||
out ImmutableArray<ResourceInfo> resources)
|
||||
{
|
||||
using ImmutableArrayBuilder<ResourceInfo> resourceBuilder = new();
|
||||
|
||||
foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers())
|
||||
{
|
||||
// Only process instance fields
|
||||
if (memberSymbol is not IFieldSymbol { Type: INamedTypeSymbol { IsStatic: false }, IsConst: false, IsStatic: false, IsFixedSizeBuffer: false, IsImplicitlyDeclared: false } fieldSymbol)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip fields of not accessible types (the analyzer will handle this just like other fields)
|
||||
if (!fieldSymbol.Type.IsAccessibleFromCompilationAssembly(compilation))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
string fieldName = fieldSymbol.Name;
|
||||
string typeName = fieldSymbol.Type.GetFullyQualifiedMetadataName();
|
||||
|
||||
// Check if the field is a resource (note: resources can only be top level fields)
|
||||
if (HlslKnownTypes.IsTypedResourceType(typeName))
|
||||
{
|
||||
resourceBuilder.Add(new ResourceInfo(fieldName, typeName));
|
||||
}
|
||||
}
|
||||
|
||||
resources = resourceBuilder.ToImmutable();
|
||||
|
||||
// A shader root signature has a maximum size of 64 DWORDs, so 256 bytes.
|
||||
// Loaded values in the root signature have the following costs:
|
||||
// - Root constants cost 1 DWORD each, since they are 32-bit values.
|
||||
// - Descriptor tables cost 1 DWORD each.
|
||||
// - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each.
|
||||
// So here we check whether the current signature respects that constraint,
|
||||
// and emit a build error otherwise. For more info on this, see the docs here:
|
||||
// https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits.
|
||||
if ((constantBufferSizeInBytes / sizeof(int)) + resourceBuilder.Count > 64)
|
||||
{
|
||||
diagnostics.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the <c>LoadGraphicsResources</c> method.
|
||||
/// </summary>
|
||||
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
|
||||
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
|
||||
public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
|
||||
|
||||
writer.WriteLine("/// <inheritdoc/>");
|
||||
writer.WriteGeneratedAttributes(GeneratorName);
|
||||
writer.WriteLine($"static void global::ComputeSharp.Descriptors.IComputeShaderDescriptor<{typeName}>.LoadGraphicsResources<TLoader>(in {typeName} shader, ref TLoader loader)");
|
||||
|
||||
using (writer.WriteBlock())
|
||||
{
|
||||
// Generate loading statements for each captured resource
|
||||
for (int i = 0; i < info.Resources.Length; i++)
|
||||
{
|
||||
writer.WriteLine($"loader.LoadGraphicsResource(shader.{info.Resources[i].FieldName}, {i});");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using ComputeSharp.SourceGeneration.SyntaxProcessors;
|
||||
using ComputeSharp.SourceGenerators.Models;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
@@ -58,14 +60,21 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener
|
||||
using ImmutableArrayBuilder<DiagnosticInfo> diagnostics = new();
|
||||
|
||||
// Get the fields info
|
||||
DispatchDataLoading.GetInfo(
|
||||
diagnostics,
|
||||
ConstantBuffer.GetInfo(
|
||||
context.SemanticModel.Compilation,
|
||||
typeSymbol,
|
||||
isPixelShaderLike,
|
||||
out int constantBufferSizeInBytes,
|
||||
out int resourceCount,
|
||||
out ImmutableArray<FieldInfo> fieldInfos,
|
||||
out ImmutableArray<FieldInfo> fieldInfos);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// Get the resources info
|
||||
Resources.GetInfo(
|
||||
diagnostics,
|
||||
context.SemanticModel.Compilation,
|
||||
typeSymbol,
|
||||
constantBufferSizeInBytes,
|
||||
out ImmutableArray<ResourceInfo> resourceInfo);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
@@ -129,7 +138,6 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener
|
||||
IsPixelShaderLike: isPixelShaderLike,
|
||||
IsSamplerUsed: isSamplerUsed,
|
||||
ConstantBufferSizeInBytes: constantBufferSizeInBytes,
|
||||
ResourceCount: resourceCount,
|
||||
Fields: fieldInfos,
|
||||
Resources: resourceInfo,
|
||||
ResourceDescriptors: resourceDescriptors,
|
||||
@@ -158,13 +166,14 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener
|
||||
declaredMembers.Add(MetadataProperties.WriteIsStaticSamplerRequiredSyntax);
|
||||
declaredMembers.Add(ResourceDescriptorRanges.WriteSyntax);
|
||||
declaredMembers.Add(HlslSource.WriteSyntax);
|
||||
declaredMembers.Add(HlslBytecode.WriteHlslBytecodeSyntax);
|
||||
declaredMembers.Add(DispatchDataLoading.WriteLoadConstantBufferSyntax);
|
||||
declaredMembers.Add(DispatchDataLoading.WriteLoadGraphicsResourcesSyntax);
|
||||
declaredMembers.Add(HlslBytecode.WriteSyntax);
|
||||
declaredMembers.Add(ConstantBuffer.WriteSyntax);
|
||||
declaredMembers.Add(Resources.WriteSyntax);
|
||||
|
||||
using ImmutableArrayBuilder<IndentedTextWriter.Callback<ShaderInfo>> additionalTypes = new();
|
||||
using ImmutableHashSetBuilder<string> usingDirectives = new();
|
||||
|
||||
ConstantBufferSyntaxProcessor.RegisterAdditionalTypesSyntax(GeneratorName, BindingDirection.OneWay, item, additionalTypes, usingDirectives);
|
||||
ResourceDescriptorRanges.RegisterAdditionalDataMemberSyntax(item, additionalTypes, usingDirectives);
|
||||
HlslBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
|
||||
|
||||
|
||||
@@ -5,5 +5,4 @@ namespace ComputeSharp.SourceGenerators.Models;
|
||||
/// </summary>
|
||||
/// <param name="FieldName">The name of the resource field.</param>
|
||||
/// <param name="TypeName">The full metadata name for the resource type.</param>
|
||||
/// <param name="Offset">The offset for the resource within the root signature.</param>
|
||||
public sealed record ResourceInfo(string FieldName, string TypeName, int Offset);
|
||||
public sealed record ResourceInfo(string FieldName, string TypeName);
|
||||
@@ -13,7 +13,6 @@ namespace ComputeSharp.SourceGenerators.Models;
|
||||
/// <param name="IsPixelShaderLike">Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture.</param>
|
||||
/// <param name="IsSamplerUsed">Whether or not the static sampler is used.</param>
|
||||
/// <param name="ConstantBufferSizeInBytes">The size of the shader constant buffer.</param>
|
||||
/// <param name="ResourceCount">The total number of captured resources in the shader.</param>
|
||||
/// <param name="Fields">The description on shader instance fields.</param>
|
||||
/// <param name="Resources">The description on shader captured resources.</param>
|
||||
/// <param name="ResourceDescriptors">The sequence of resource descriptors for the shader.</param>
|
||||
@@ -28,10 +27,9 @@ internal sealed record ShaderInfo(
|
||||
bool IsPixelShaderLike,
|
||||
bool IsSamplerUsed,
|
||||
int ConstantBufferSizeInBytes,
|
||||
int ResourceCount,
|
||||
EquatableArray<FieldInfo> Fields,
|
||||
EquatableArray<ResourceInfo> Resources,
|
||||
EquatableArray<ResourceDescriptor> ResourceDescriptors,
|
||||
HlslBytecodeInfoKey HlslInfoKey,
|
||||
HlslBytecodeInfo HlslInfo,
|
||||
EquatableArray<DiagnosticInfo> Diagnostcs);
|
||||
EquatableArray<DiagnosticInfo> Diagnostcs) : IConstantBufferInfo;
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using ComputeSharp.SourceGenerators.Models;
|
||||
|
||||
namespace ComputeSharp.SourceGeneration.SyntaxProcessors;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class ConstantBufferSyntaxProcessor
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
private static partial bool HasArtificialFields()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
static partial void AppendArtificialFields(IConstantBufferInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
// The X and Y axes are always present
|
||||
writer.WriteLine("""
|
||||
/// <summary>The artificial field backing <see cref="DispatchSize.X"/>.</summary>
|
||||
[FieldOffset(0)]
|
||||
public int __x;
|
||||
|
||||
/// <summary>The artificial field backing <see cref="DispatchSize.Y"/>.</summary>
|
||||
[FieldOffset(4)]
|
||||
public int __y;
|
||||
""", isMultiline: true);
|
||||
|
||||
// The Z axis is only present for non pixel-shader-like compute shaders
|
||||
writer.WriteLineIf(!((ShaderInfo)info).IsPixelShaderLike);
|
||||
writer.WriteLineIf(
|
||||
condition: !((ShaderInfo)info).IsPixelShaderLike,
|
||||
"""
|
||||
/// <summary>The artificial field backing <see cref="DispatchSize.Z"/>.</summary>
|
||||
[FieldOffset(8)]
|
||||
public int __z;
|
||||
""", isMultiline: true);
|
||||
|
||||
// Leave a trailing blank line if the shader has any fields
|
||||
writer.WriteLineIf(!info.Fields.IsEmpty);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
static partial void InitializeArtificialFields(IConstantBufferInfo info, IndentedTextWriter writer)
|
||||
{
|
||||
// Ignore the artificial fields (they will be set separately)
|
||||
writer.WriteLine("Unsafe.SkipInit(out buffer.__x);");
|
||||
writer.WriteLine("Unsafe.SkipInit(out buffer.__y);");
|
||||
writer.WriteLineIf(!((ShaderInfo)info).IsPixelShaderLike, "Unsafe.SkipInit(out buffer.__z);");
|
||||
writer.WriteLineIf(!info.Fields.IsEmpty);
|
||||
}
|
||||
}
|
||||
@@ -293,7 +293,7 @@ namespace ComputeSharp.Tests
|
||||
|
||||
static int C() => 1;
|
||||
|
||||
int D() => A() + E() + F();
|
||||
public int D() => A() + E() + F();
|
||||
|
||||
int E() => 1;
|
||||
|
||||
|
||||
@@ -31,12 +31,6 @@ internal readonly partial struct TriangleGridContouring : IComputeShader
|
||||
return new(c, -s, s, c);
|
||||
}
|
||||
|
||||
// IQ's float2 to float hash.
|
||||
private static float Hash21(float2 p)
|
||||
{
|
||||
return Hlsl.Frac(Hlsl.Sin(Hlsl.Dot(p, new float2(27.619f, 57.583f))) * 43758.5453f);
|
||||
}
|
||||
|
||||
// float2 to float2 hash.
|
||||
private float2 Hash22(float2 p)
|
||||
{
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする