diff --git a/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs b/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs index 26f4f0cf..c6c501f3 100644 --- a/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs +++ b/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs @@ -1,12 +1,15 @@ using System; +using ComputeSharp.__Internals; using ComputeSharp.Interop; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; +#pragma warning disable CS0618 + namespace ComputeSharp.SwapChain.Backend { internal sealed class SwapChainApplication : Win32Application - where T : struct, IPixelShader + where T : struct, IPixelShader, IShader { /// /// The instance used to create shaders to run. diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md index 8ab9597d..02fa72d6 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md @@ -7,50 +7,48 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- -CMPS0001 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0002 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0003 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0004 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0005 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0006 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0007 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0008 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0009 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0010 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0011 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0012 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0013 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0014 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0015 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0016 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0017 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0018 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0019 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0020 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0021 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0022 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0023 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0024 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0025 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0026 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0027 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0028 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0029 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0030 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0031 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0032 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0033 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0034 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0035 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0036 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0001 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0002 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0003 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0004 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0005 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0006 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0007 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0008 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0009 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0010 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0011 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0012 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0013 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0014 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0015 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0016 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0017 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0018 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0019 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0020 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0021 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0022 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0023 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0024 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0025 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0026 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0027 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0028 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0029 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0030 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0031 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0032 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0033 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0034 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0035 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0036 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0037 | ComputeSharp.SourceGenerators.AutoConstructorGenerator | Warning | AutoConstructorGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0038 | ComputeSharp.SourceGenerators.IComputeShaderDataLoaderGenerator | Warning | IComputeShaderDataLoaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0039 | ComputeSharp.SourceGenerators.IComputeShaderHashCodeGenerator | Warning | IComputeShaderHashCodeGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0040 | ComputeSharp.SourceGenerators.IComputeShaderSourceGenerator | Warning | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0040 | ComputeSharp.SourceGenerators.IShaderGenerator | Warning | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0041 | ComputeSharp.SourceGenerators.ShaderMethodSourceGenerator | Warning | ShaderMethodSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0042 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0043 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0044 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0045 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0046 | ComputeSharp.IComputeShader | Error | IComputeShaderDataLoaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0047 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0042 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0043 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0044 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0045 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0046 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0047 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs index 395f1b22..8d31d254 100644 --- a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs @@ -101,7 +101,7 @@ namespace ComputeSharp.SourceGenerators var source = CompilationUnit().AddMembers( NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax)) - .NormalizeWhitespace() + .NormalizeWhitespace(eol: "\n") .ToFullString(); // Add the partial type diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 3e2dcc6f..a621a6da 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -14,8 +14,6 @@ - - @@ -24,8 +22,6 @@ - - diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index caf8bc94..e936e826 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -513,51 +513,19 @@ namespace ComputeSharp.SourceGenerators.Diagnostics helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// - /// Gets a for an internal error in . + /// Gets a for an internal error in . /// - /// Format: "The generator IComputeShaderDataLoaderGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash". + /// Format: "The generator IShaderGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash". /// /// - public static readonly DiagnosticDescriptor IComputeShaderDataLoaderGeneratorError = new( - id: "CMPS0038", - title: $"Internal error for {nameof(IComputeShaderDataLoaderGenerator)}", - messageFormat: $"The generator {nameof(IComputeShaderDataLoaderGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash", - category: typeof(IComputeShaderDataLoaderGenerator).FullName, - defaultSeverity: DiagnosticSeverity.Warning, - isEnabledByDefault: true, - description: $"The {nameof(IComputeShaderDataLoaderGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.", - helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); - - /// - /// Gets a for an internal error in . - /// - /// Format: "The generator IComputeShaderHashCodeGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash". - /// - /// - public static readonly DiagnosticDescriptor IComputeShaderHashCodeGeneratorError = new( - id: "CMPS0039", - title: $"Internal error for {nameof(IComputeShaderHashCodeGenerator)}", - messageFormat: $"The generator {nameof(IComputeShaderHashCodeGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash", - category: typeof(IComputeShaderHashCodeGenerator).FullName, - defaultSeverity: DiagnosticSeverity.Warning, - isEnabledByDefault: true, - description: $"The {nameof(IComputeShaderHashCodeGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.", - helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); - - /// - /// Gets a for an internal error in . - /// - /// Format: "The generator IComputeShaderSourceGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash". - /// - /// - public static readonly DiagnosticDescriptor IComputeShaderSourceGeneratorError = new( + public static readonly DiagnosticDescriptor IShaderGeneratorError = new( id: "CMPS0040", - title: $"Internal error for {nameof(IComputeShaderSourceGenerator)}", - messageFormat: $"The generator {nameof(IComputeShaderSourceGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash", - category: typeof(IComputeShaderSourceGenerator).FullName, + title: $"Internal error for {nameof(IShaderGenerator)}", + messageFormat: $"The generator {nameof(IShaderGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash", + category: typeof(IShaderGenerator).FullName, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, - description: $"The {nameof(IComputeShaderSourceGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.", + description: $"The {nameof(IShaderGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// @@ -657,7 +625,7 @@ namespace ComputeSharp.SourceGenerators.Diagnostics id: "CMPS0047", title: "Multiple shader implementations for type declaration", messageFormat: $"The shader of type {{0}} cannot implement more than one shader interface", - category: typeof(IComputeShaderSourceGenerator).FullName, + category: typeof(IShaderGenerator).FullName, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A shader type cannot implement more than one shader interface.", diff --git a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs index e90839c0..80403c01 100644 --- a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs +++ b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs @@ -12,68 +12,19 @@ namespace ComputeSharp.SourceGenerators.Helpers /// internal static class SyntaxFactoryHelper { - /// - /// Creates a [] array expression from the given sequence of instances. - /// - /// That it, it applies the following transformation: - /// - /// { "S1", "S2" } => new string[] { "S1", "S2" } - /// - /// - /// - /// The input sequence of instances. - /// An instance with the described contents. - [Pure] - public static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable values) - { - return - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions(values.Select(static value => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(value))).ToArray())); - } - /// /// Creates an [] array expression with the nested groups in the input sequence. /// /// That it, it applies the following transformation: /// - /// { ("K1", "V1"), ("K2", "V2") } => new object[] { new[] { "K1", "V1" }, new[] { "K2", "V2" } } + /// { ("K1", "V1"), ("K2", "V2") } => new object[] { new string[] { "K1", "V1" }, new string[] { "K2", "V2" } } /// /// /// /// The input sequence of groups. /// An instance with the described contents. [Pure] - public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable> groups) - { - return - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions(groups.Select(static group => - ImplicitArrayCreationExpression(InitializerExpression(SyntaxKind.ArrayInitializerExpression).AddExpressions( - group.Select(static item => item is null - ? LiteralExpression(SyntaxKind.NullLiteralExpression) - : LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))) - .ToArray()))).ToArray())); - } - - /// - /// Creates an [] array expression with the nested groups in the input sequence. - /// - /// That it, it applies the following transformation: - /// - /// { ("K1", "V1", I1), ("K2", "V2", null) } => new object[] { new object[] { "K1", "V1", I1 }, new object[] { "K2", "V2", null } } - /// - /// - /// - /// The input sequence of groups. - /// An instance with the described contents. - [Pure] - public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<(string A, string B, int? C)> groups) + public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<(string A, string B)> groups) { return ArrayCreationExpression( @@ -82,45 +33,12 @@ namespace ComputeSharp.SourceGenerators.Helpers .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) .AddExpressions(groups.Select(static group => ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword))) + ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword))) .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) .AddExpressions( LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.A)), - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.B)), - group.C is int i - ? LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(i)) - : LiteralExpression(SyntaxKind.NullLiteralExpression)))).ToArray())); - } - - /// - /// Creates a []? array expression from the given tuple instance. - /// - /// That it, it applies the following transformation: - /// - /// null => null - /// ("S1", "S2") => new string[] { "S1", "S2" } - /// - /// - /// - /// The input tuple instance. - /// An instance with the described contents. - [Pure] - public static ExpressionSyntax ArrayExpression((string First, string Second)? values) - { - if (values is null) - { - return LiteralExpression(SyntaxKind.NullLiteralExpression); - } - - return - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions( - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(values.Value.First)), - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(values.Value.Second)))); + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.B))))).ToArray())); } } } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.SyntaxReceiver.cs deleted file mode 100644 index b426151e..00000000 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.SyntaxReceiver.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -namespace ComputeSharp.SourceGenerators -{ - /// - public sealed partial class IComputeShaderDataLoaderGenerator - { - /// - /// An that selects candidate nodes to process. - /// - private sealed class SyntaxReceiver : ISyntaxContextReceiver - { - /// - /// The list of info gathered during exploration. - /// - private readonly List gatheredInfo = new(); - - /// - /// Gets the collection of gathered info to process. - /// - public IReadOnlyCollection GatheredInfo => this.gatheredInfo; - - /// - public void OnVisitSyntaxNode(GeneratorSyntaxContext context) - { - if (context.Node is StructDeclarationSyntax structDeclaration && - context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol && - structSymbol.Interfaces.Any(static interfaceSymbol => - interfaceSymbol.Name == nameof(IComputeShader) || - interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) })) - { - this.gatheredInfo.Add(new Item(structDeclaration, structSymbol)); - } - } - - /// - /// A model for a group of item representing a discovered type to process. - /// - /// The instance for the target struct declaration. - /// The instance for . - public sealed record Item(StructDeclarationSyntax StructDeclaration, INamedTypeSymbol StructSymbol); - } - } -} - diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs deleted file mode 100644 index dea57d54..00000000 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ /dev/null @@ -1,307 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Text; -using ComputeSharp.__Internals; -using ComputeSharp.Core.Helpers; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Mappings; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 - -namespace ComputeSharp.SourceGenerators -{ - /// - /// A source generator creating data loaders for types. - /// - [Generator] - public sealed partial class IComputeShaderDataLoaderGenerator : ISourceGenerator - { - /// - public void Initialize(GeneratorInitializationContext context) - { - context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver()); - } - - /// - public void Execute(GeneratorExecutionContext context) - { - // Get the syntax receiver with the candidate nodes - if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver) - { - return; - } - - // Type attributes - AttributeListSyntax[] attributes = new[] - { - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( - AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( - AttributeArgument(LiteralExpression( - SyntaxKind.StringLiteralExpression, - Literal("This type is not intended to be used directly by user code")))))) - }; - - foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo) - { - try - { - OnExecute(context, item.StructDeclaration, item.StructSymbol, ref attributes); - } - catch - { - context.ReportDiagnostic(IComputeShaderDataLoaderGeneratorError, item.StructDeclaration, item.StructSymbol); - } - } - } - - /// - /// Processes a given target type. - /// - /// The input instance to use. - /// The node to process. - /// The for . - /// The list of instances to append to the first copy of the partial class being generated. - private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, ref AttributeListSyntax[] attributes) - { - TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString()); - BlockSyntax block = Block(GetDispatchDataLoadingStatements(context, structDeclarationSymbol, out int root32BitConstantsCount)); - - // Create a static method to create the combined hashcode for a given shader type. - // This code takes a block syntax and produces a compilation unit as follows: - // - // using System; - // using System.ComponentModel; - // - // namespace ComputeSharp.__Internals - // { - // internal static partial class DispatchDataLoader - // { - // [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)] - // [System.Obsolete("This method is not intended to be called directly by user code")] - // [return: ComputeRoot32BitConstants(42)] - // public static int LoadDispatchData(GraphicsDevice device, in ShaderType shader, ref ulong r0, ref byte r1) - // { - // ... - // } - // } - // } - var source = - CompilationUnit().AddUsings( - UsingDirective(IdentifierName("System")), - UsingDirective(IdentifierName("System.ComponentModel")), - UsingDirective(IdentifierName("System.Runtime.CompilerServices"))).AddMembers( - NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers( - ClassDeclaration("DispatchDataLoader").AddModifiers( - Token(SyntaxKind.InternalKeyword), - Token(SyntaxKind.StaticKeyword), - Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers( - MethodDeclaration( - PredefinedType(Token(SyntaxKind.IntKeyword)), - Identifier("LoadDispatchData")).AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( - AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( - AttributeArgument(LiteralExpression( - SyntaxKind.StringLiteralExpression, - Literal("This method is not intended to be called directly by user code")))))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName(nameof(ComputeRoot32BitConstantsAttribute).Replace("Attribute", ""))) - .AddArgumentListArguments(AttributeArgument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(root32BitConstantsCount)))))) - .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.ReturnKeyword)))).AddModifiers( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword)).AddParameterListParameters( - Parameter(Identifier("device")).WithType(IdentifierName("ComputeSharp.GraphicsDevice")), - Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType), - Parameter(Identifier("r0")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ULongKeyword))), - Parameter(Identifier("r1")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .WithBody(block))) - .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) - .NormalizeWhitespace() - .ToFullString(); - - // Clear the attribute list to avoid duplicates - attributes = Array.Empty(); - - // Add the method source attribute - context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); - } - - /// - /// Gets a sequence of statements to load the dispatch data for a given shader - /// - /// The current generator context in use. - /// The input instance to process. - /// The total number of 32 bit root constants to load. - /// The sequence of instances to load shader dispatch data. - [Pure] - private static IEnumerable GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out int count) - { - List statements = new(); - - var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); - var isComputeShader = pixelShaderSymbol is null; - int - resourceOffset = 0, - rawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2); - - AppendFields(structDeclarationSymbol, Array.Empty(), ref resourceOffset, ref rawDataOffset, statements); - - // After all the captured fields have been processed, ansure 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. - rawDataOffset = AlignmentHelper.Pad(rawDataOffset, sizeof(int)); - - statements.Add(ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(rawDataOffset)))); - - count = 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 rootSignatureDwordSize = count + resourceOffset; - - if (rootSignatureDwordSize > 64) - { - context.ReportDiagnostic(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); - } - - return statements; - } - - /// - /// Explores a given type hierarchy and generates statements to load fields. - /// - /// The current type being explored. - /// The current path of the field with respect to the shader instance. - /// The current offset in the root table of loaded resources. - /// The current offset within the loaded data buffer. - /// The target list of statements being generated. - private static void AppendFields(ITypeSymbol currentTypeSymbol, IReadOnlyCollection fieldPath, ref int resourceOffset, ref int rawDataOffset, ICollection statements) - { - bool isFirstField = true; - - foreach ( - IFieldSymbol fieldSymbol in - from fieldSymbol in currentTypeSymbol.GetMembers().OfType() - where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } && - !fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer - select fieldSymbol) - { - string typeName = fieldSymbol.Type.GetFullMetadataName(); - - // The first item in each nested struct needs to be aligned to 16 bytes - if (isFirstField && fieldPath.Count > 0) - { - rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); - - isFirstField = false; - } - - if (HlslKnownTypes.IsTypedResourceType(typeName)) - { - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"Unsafe.Add(ref r0, {resourceOffset++})"), - ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(shader.{fieldSymbol.Name}, device)")))); - } - else if (HlslKnownTypes.IsKnownHlslType(typeName)) - { - AppendHlslKnownTypeField(fieldPath.Concat(new[] { fieldSymbol.Name }), typeName, ref rawDataOffset, statements); - } - else if (fieldSymbol.Type.IsUnmanagedType) - { - // Custom struct type defined by the user - AppendFields(fieldSymbol.Type, fieldPath.Concat(new[] { fieldSymbol.Name }).ToArray(), ref resourceOffset, ref rawDataOffset, statements); - } - } - } - - /// - /// Generates a loading statement for a known HLSL primitive type field (scalar, vector or matrix). - /// - /// The current path of the field with respect to the shader instance. - /// The type name currently being read. - /// The current offset within the loaded data buffer. - /// The target list of statements being generated. - private static void AppendHlslKnownTypeField(IEnumerable fieldPath, string typeName, ref int rawDataOffset, ICollection statements) - { - // For scalar, vector and linear matrix types, serialize the value normally. - // Only the initial alignment needs to be considered, while data is packed. - var (fieldSize, 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)) - { - string - rowTypeName = $"ComputeSharp.{elementName}{columns}", - rowLocalName = $"__{string.Join("_", fieldPath)}__row0"; - - statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref Unsafe.As<{typeName}, {rowTypeName}>(ref Unsafe.AsRef(in shader.{string.Join(".", fieldPath)}));")); - - // Generate the loading code for each individual row, with proper alignment. - // This will result in the following (assuming Float2x3 m): - // - // ref Float3 __m__row0 = ref Unsafe.As(ref Unsafe.AsRef(in shader.m)); - // Unsafe.As(ref Unsafe.Add(ref r1, rawDataOffset)) =, Unsafe.Add(ref __m__row0, 0); - // Unsafe.As(ref Unsafe.Add(ref r1, rawDataOffset + 16)) = Unsafe.Add(ref __m__row0, 1); - for (int j = 0; j < rows; j++) - { - rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); - - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"Unsafe.As(ref Unsafe.Add(ref r1, {rawDataOffset}))"), - ParseExpression($"Unsafe.Add(ref {rowLocalName}, {j})")))); - - rawDataOffset += fieldPack * columns; - } - } - 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. - rawDataOffset = AlignmentHelper.AlignToBoundary( - AlignmentHelper.Pad(rawDataOffset, fieldPack), - fieldSize, - 16); - - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"Unsafe.As(ref Unsafe.Add(ref r1, {rawDataOffset}))"), - ParseExpression($"shader.{string.Join(".", fieldPath)}")))); - - rawDataOffset += fieldSize; - } - } - } -} - diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.SyntaxReceiver.cs deleted file mode 100644 index 2e58a0cb..00000000 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.SyntaxReceiver.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -namespace ComputeSharp.SourceGenerators -{ - /// - public sealed partial class IComputeShaderHashCodeGenerator - { - /// - /// An that selects candidate nodes to process. - /// - private sealed class SyntaxReceiver : ISyntaxContextReceiver - { - /// - /// The list of info gathered during exploration. - /// - private readonly List gatheredInfo = new(); - - /// - /// Gets the collection of gathered info to process. - /// - public IReadOnlyCollection GatheredInfo => this.gatheredInfo; - - /// - public void OnVisitSyntaxNode(GeneratorSyntaxContext context) - { - if (context.Node is StructDeclarationSyntax structDeclaration && - context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol && - structSymbol.Interfaces.Any(static interfaceSymbol => - interfaceSymbol.Name == nameof(IComputeShader) || - interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) })) - { - this.gatheredInfo.Add(new Item(structDeclaration, structSymbol)); - } - } - - /// - /// A model for a group of item representing a discovered type to process. - /// - /// The instance for the target struct declaration. - /// The instance for . - public sealed record Item(StructDeclarationSyntax StructDeclaration, INamedTypeSymbol StructSymbol); - } - } -} - diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs deleted file mode 100644 index c6e5b676..00000000 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs +++ /dev/null @@ -1,156 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Text; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -namespace ComputeSharp.SourceGenerators -{ - /// - /// A source generator creating hash code factories for types. - /// - [Generator] - public sealed partial class IComputeShaderHashCodeGenerator : ISourceGenerator - { - /// - public void Initialize(GeneratorInitializationContext context) - { - context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver()); - } - - /// - public void Execute(GeneratorExecutionContext context) - { - // Get the syntax receiver with the candidate nodes - if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver) - { - return; - } - - // Type attributes - AttributeListSyntax[] attributes = new[] - { - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( - AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( - AttributeArgument(LiteralExpression( - SyntaxKind.StringLiteralExpression, - Literal("This type is not intended to be used directly by user code")))))) - }; - - foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo) - { - try - { - OnExecute(context, item.StructDeclaration, item.StructSymbol, ref attributes); - } - catch - { - context.ReportDiagnostic(IComputeShaderHashCodeGeneratorError, item.StructDeclaration, item.StructSymbol); - } - } - } - - /// - /// Processes a given target type. - /// - /// The input instance to use. - /// The node to process. - /// The for . - /// The list of instances to append to the first copy of the partial class being generated. - private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, ref AttributeListSyntax[] attributes) - { - TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString()); - BlockSyntax block = Block(GetDelegateHashCodeStatements(structDeclarationSymbol)); - - if (block.Statements.Count == 1) return; - - // Create a static method to create the combined hashcode for a given shader type. - // This code takes a block syntax and produces a compilation unit as follows: - // - // using System; - // using System.ComponentModel; - // - // namespace ComputeSharp.__Internals - // { - // internal static partial class HashCodeProvider - // { - // [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)] - // [System.Obsolete("This method is not intended to be called directly by user code")] - // public static int CombineHashCode(int hash, in ShaderType shader) - // { - // return ...; - // } - // } - // } - var source = - CompilationUnit().AddUsings( - UsingDirective(IdentifierName("System")), - UsingDirective(IdentifierName("System.ComponentModel"))).AddMembers( - NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers( - ClassDeclaration("HashCodeProvider").AddModifiers( - Token(SyntaxKind.InternalKeyword), - Token(SyntaxKind.StaticKeyword), - Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers( - MethodDeclaration( - PredefinedType(Token(SyntaxKind.IntKeyword)), - Identifier("CombineHash")).AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( - AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( - AttributeArgument(LiteralExpression( - SyntaxKind.StringLiteralExpression, - Literal("This method is not intended to be called directly by user code"))))))).AddModifiers( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword)).AddParameterListParameters( - Parameter(Identifier("hash")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType)) - .WithBody(block)))) - .NormalizeWhitespace() - .ToFullString(); - - // Clear the attribute list to avoid duplicates - attributes = Array.Empty(); - - // Add the method source attribute - context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); - } - - /// - /// Gets a sequence of statements to process the hashcode of the captured delegates. - /// - /// The input instance to process. - /// The sequence of instances to hash the captured delegates. - [Pure] - private static IEnumerable GetDelegateHashCodeStatements(INamedTypeSymbol structDeclarationSymbol) - { - foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) - { - if (fieldSymbol.Type is not INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false } typeSymbol) - { - continue; - } - - // hash += hash << 5; - yield return ExpressionStatement(ParseExpression($"hash += hash << 5")); - - // hash += shader.Field[#i].Method.GetHashCode(); - yield return ExpressionStatement(ParseExpression($"hash += shader.{fieldSymbol.Name}.Method.GetHashCode()")); - } - - yield return ReturnStatement(IdentifierName("hash")); - } - } -} - diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs deleted file mode 100644 index e1d257a2..00000000 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ /dev/null @@ -1,480 +0,0 @@ -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Text; -using ComputeSharp.__Internals; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Helpers; -using ComputeSharp.SourceGenerators.Mappings; -using ComputeSharp.SourceGenerators.SyntaxRewriters; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; -using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 - -namespace ComputeSharp.SourceGenerators -{ - /// - /// A source generator for processing types. - /// - [Generator] - public sealed partial class IComputeShaderSourceGenerator : ISourceGenerator - { - /// - public void Initialize(GeneratorInitializationContext context) - { - context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver()); - } - - /// - public void Execute(GeneratorExecutionContext context) - { - // Get the syntax receiver with the candidate nodes - if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver) - { - return; - } - - foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo) - { - SemanticModelProvider semanticModel = new(context.Compilation); - - try - { - OnExecute(context, item.StructDeclaration, semanticModel, item.StructSymbol); - } - catch - { - context.ReportDiagnostic(IComputeShaderSourceGeneratorError, item.StructDeclaration, item.StructSymbol); - } - } - } - - /// - /// Processes a given target type. - /// - /// The input instance to use. - /// The node to process. - /// The with metadata on the types being processed. - /// The for . - private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, SemanticModelProvider semanticModel, INamedTypeSymbol structDeclarationSymbol) - { - // Properties are not supported - DetectAndReportPropertyDeclarations(context, structDeclarationSymbol); - - // We need to sets to track all discovered custom types and static methods - HashSet discoveredTypes = new(SymbolEqualityComparer.Default); - Dictionary staticMethods = new(SymbolEqualityComparer.Default); - Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); - - // A given type can only represent a single shader type - if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader) }) > 1) - { - context.ReportDiagnostic(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol); - } - - // Explore the syntax tree and extract the processed info - var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); - var isComputeShader = pixelShaderSymbol is null; - var implicitTextureField = isComputeShader ? default((string, string)?) : (HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!), "__outputTexture"); - var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray(); - var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); - var (entryPoint, processedMethods, forwardDeclarations, isSamplerUsed) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); - var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); - var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); - var processedConstants = GetProcessedConstants(constantDefinitions); - var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); - - // Create the compilation unit with the source attribute - var source = - CompilationUnit().AddUsings( - UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName(typeof(IComputeShaderSourceAttribute).FullName)).AddArgumentListArguments( - AttributeArgument(TypeOfExpression(IdentifierName(structDeclarationSymbol.ToDisplayString()))), - AttributeArgument(ArrayExpression(processedTypes)), - AttributeArgument(ArrayExpression(implicitTextureField)), - AttributeArgument(ArrayExpression(implicitSamplerField)), - AttributeArgument(NestedArrayExpression(processedMembers)), - AttributeArgument(ArrayExpression(forwardDeclarations)), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(entryPoint))), - AttributeArgument(ArrayExpression(processedMethods)), - AttributeArgument(NestedArrayExpression(processedConstants)), - AttributeArgument(NestedArrayExpression(staticFields)), - AttributeArgument(NestedArrayExpression(sharedBuffers))))) - .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) - .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) - .NormalizeWhitespace() - .ToFullString(); - - // Add the method source attribute - context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); - } - - /// - /// Gets a sequence of captured fields and their mapped names. - /// - /// The current generator context in use. - /// The input instance to process. - /// The collection of currently discovered types. - /// Indicates whether or not represents a compute shader. - /// A sequence of captured fields in . - [Pure] - private static IEnumerable> GetProcessedFields( - GeneratorExecutionContext context, - INamedTypeSymbol structDeclarationSymbol, - ICollection types, - bool isComputeShader) - { - bool hlslResourceFound = false; - - foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) - { - if (fieldSymbol.IsStatic) continue; - - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); - - // Group shared fields must be static - if (attribute is not null) - { - context.ReportDiagnostic(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name); - } - - // Captured fields must be named type symbols - if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) - { - context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - string metadataName = typeSymbol.GetFullMetadataName(); - - // Allowed fields must be either resources, unmanaged values or delegates - if (HlslKnownTypes.IsTypedResourceType(metadataName)) - { - hlslResourceFound = true; - - // Track the type of items in the current buffer - if (HlslKnownTypes.IsStructuredBufferType(metadataName)) - { - types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); - } - } - else if (!typeSymbol.IsUnmanagedType && - typeSymbol.TypeKind != TypeKind.Delegate) - { - // Shaders can only capture valid HLSL resource types or unmanaged types - context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol); - - continue; - } - else if (!HlslKnownTypes.IsKnownHlslType(metadataName)) - { - // Track the type if it's a custom struct - types.Add(typeSymbol); - } - - string typeName = HlslKnownTypes.GetMappedName(typeSymbol); - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - // Yield back the current mapping for the name (if the name used a reserved keyword) - yield return new[] { fieldSymbol.Name, mapping ?? fieldSymbol.Name, typeName }; - } - - // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource - if (!hlslResourceFound && isComputeShader) - { - context.ReportDiagnostic(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol); - } - } - - /// - /// Gets a sequence of shader static fields and their mapped names. - /// - /// The current generator context in use. - /// The instance for the type to process. - /// The instance for the current type. - /// The type symbol for the shader type. - /// The collection of currently discovered types. - /// The collection of discovered constant definitions. - /// A sequence of static constant fields in . - [Pure] - private static IEnumerable> GetStaticFields( - GeneratorExecutionContext context, - SemanticModelProvider semanticModel, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - ICollection discoveredTypes, - IDictionary constantDefinitions) - { - foreach (var fieldDeclaration in structDeclaration.Members.OfType()) - { - foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) - { - IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!; - - if (!fieldSymbol.IsStatic || fieldSymbol.IsConst) - { - continue; - } - - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); - - if (attribute is not null) continue; - - // Constant properties must be of a primitive, vector or matrix type - if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || - !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName())) - { - context.ReportDiagnostic(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - string typeDeclaration = fieldSymbol.IsReadOnly switch - { - true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}", - false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" - }; - - StaticFieldRewriter staticFieldRewriter = new( - semanticModel, - discoveredTypes, - constantDefinitions, - context); - - string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace().ToFullString(); - - yield return new[] { mapping ?? fieldSymbol.Name, typeDeclaration, assignment }; - } - } - } - - /// - /// Gets a sequence of captured members and their mapped names. - /// - /// The current generator context in use. - /// The input instance to process. - /// The collection of currently discovered types. - /// A sequence of captured members in . - [Pure] - private static IEnumerable<(string Name, string Type, int? Count)> GetGroupSharedMembers( - GeneratorExecutionContext context, - INamedTypeSymbol structDeclarationSymbol, - ICollection types) - { - foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) - { - if (!fieldSymbol.IsStatic) continue; - - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); - - if (attribute is null) continue; - - if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol) - { - context.ReportDiagnostic(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - if (!typeSymbol.ElementType.IsUnmanagedType) - { - context.ReportDiagnostic(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; - - string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - yield return (mapping ?? fieldSymbol.Name, typeName, bufferSize); - - types.Add((INamedTypeSymbol)typeSymbol.ElementType); - } - } - - /// - /// Gets a sequence of processed methods declared within a given type. - /// - /// The current generator context in use. - /// The type symbol for the shader type. - /// The instance for the current type. - /// The instance for the type to process. - /// The collection of currently discovered types. - /// The set of discovered and processed static methods. - /// The collection of discovered constant definitions. - /// Indicates whether or not represents a compute shader. - /// A sequence of processed methods in , and the entry point. - [Pure] - private static (string EntryPoint, IEnumerable Methods, IEnumerable Declarations, bool IsSamplerUser) GetProcessedMethods( - GeneratorExecutionContext context, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary staticMethods, - IDictionary constantDefinitions, - bool isComputeShader) - { - // Find all declared methods in the type - ImmutableArray methodDeclarations = ( - from syntaxNode in structDeclaration.DescendantNodes() - where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) - select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); - - string? entryPoint = null; - List methods = new(); - List declarations = new(); - bool isSamplerUsed = false; - - foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) - { - IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!; - bool isShaderEntryPoint = - (isComputeShader && - methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && - methodDeclarationSymbol.ReturnsVoid && - methodDeclarationSymbol.TypeParameters.Length == 0 && - methodDeclarationSymbol.Parameters.Length == 0) || - (!isComputeShader && - methodDeclarationSymbol.Name == nameof(IPixelShader.Execute) && - methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type - methodDeclarationSymbol.TypeParameters.Length == 0 && - methodDeclarationSymbol.Parameters.Length == 0); - - // Create the source rewriter for the current method - ShaderSourceRewriter shaderSourceRewriter = new( - structDeclarationSymbol, - semanticModel, - discoveredTypes, - staticMethods, - constantDefinitions, - context, - isShaderEntryPoint); - - // Rewrite the method syntax tree - MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); - - // Track the implicit sampler, if used - isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed; - - // Emit the extracted local functions first - foreach (var localFunction in shaderSourceRewriter.LocalFunctions) - { - methods.Add(localFunction.Value.NormalizeWhitespace().ToFullString()); - declarations.Add(localFunction.Value.AsDefinition().NormalizeWhitespace().ToFullString()); - } - - // If the method is the shader entry point, do additional processing - if (isShaderEntryPoint) - { - processedMethod = isComputeShader switch - { - true => new ExecuteMethodRewriter.Compute(shaderSourceRewriter).Visit(processedMethod)!, - false => new ExecuteMethodRewriter.Pixel(shaderSourceRewriter).Visit(processedMethod)! - }; - - entryPoint = processedMethod.NormalizeWhitespace().ToFullString(); - } - else - { - methods.Add(processedMethod.NormalizeWhitespace().ToFullString()); - declarations.Add(processedMethod.AsDefinition().NormalizeWhitespace().ToFullString()); - } - } - - // Process static methods as well - foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) - { - methods.Add(staticMethod.NormalizeWhitespace().ToFullString()); - declarations.Add(staticMethod.AsDefinition().NormalizeWhitespace().ToFullString()); - } - - return (entryPoint!, methods, declarations, isSamplerUsed); - } - - /// - /// Gets a sequence of discovered constants. - /// - /// The collection of discovered constant definitions. - /// A sequence of discovered constants to declare in the shader. - [Pure] - internal static IEnumerable> GetProcessedConstants(IReadOnlyDictionary constantDefinitions) - { - foreach (var constant in constantDefinitions) - { - var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; - - yield return new string[] { constantName, constant.Value }; - } - } - - /// - /// Gets the sequence of processed discovered custom types. - /// - /// The sequence of discovered custom types. - /// A sequence of custom type definitions to add to the shader source. - internal static IEnumerable GetProcessedTypes(IEnumerable types) - { - foreach (var type in HlslKnownTypes.GetCustomTypes(types)) - { - var structType = type.GetFullMetadataName().ToHlslIdentifierName(); - var structDeclaration = StructDeclaration(structType); - - // Declare the fields of the current type - foreach (var field in type.GetMembers().OfType()) - { - INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; - - // Convert the name to the fully qualified HLSL version - if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped)) - { - mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName(); - } - - structDeclaration = structDeclaration.AddMembers( - FieldDeclaration(VariableDeclaration( - IdentifierName(mapped!)).AddVariables( - VariableDeclarator(Identifier(field.Name))))); - } - - // Insert the trailing ; right after the closing bracket (after normalization) - yield return - structDeclaration - .NormalizeWhitespace() - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - .ToFullString(); - } - } - - /// - /// Finds and reports all declared properties in a shader. - /// - /// The current generator context in use. - /// The input instance to process. - private static void DetectAndReportPropertyDeclarations(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol) - { - foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType()) - { - context.ReportDiagnostic(DiagnosticDescriptors.PropertyDeclaration, propertySymbol); - } - } - } -} - diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs new file mode 100644 index 00000000..c345ff3c --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -0,0 +1,821 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Text; +using ComputeSharp.__Internals; +using ComputeSharp.SourceGenerators.Diagnostics; +using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Helpers; +using ComputeSharp.SourceGenerators.Mappings; +using ComputeSharp.SourceGenerators.SyntaxRewriters; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; + +#pragma warning disable CS0618 + +namespace ComputeSharp.SourceGenerators +{ + /// + public sealed partial class IShaderGenerator + { + /// + private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod( + GeneratorExecutionContext context, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + out string? implicitTextureType, + out bool isSamplerUsed, + out bool isHashSetDirectiveNeeded) + { + // Properties are not supported + DetectAndReportPropertyDeclarations(context, structDeclarationSymbol); + + // We need to sets to track all discovered custom types and static methods + HashSet discoveredTypes = new(SymbolEqualityComparer.Default); + Dictionary staticMethods = new(SymbolEqualityComparer.Default); + Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); + + // A given type can only represent a single shader type + if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader) }) > 1) + { + context.ReportDiagnostic(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol); + } + + // Explore the syntax tree and extract the processed info + var semanticModel = new SemanticModelProvider(context.Compilation); + var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); + var isComputeShader = pixelShaderSymbol is null; + var pixelShaderTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); + var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray(); + var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); + var (entryPoint, processedMethods, accessesStaticSampler) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); + var implicitSamplerField = accessesStaticSampler ? ("SamplerState", "__sampler") : default((string, string)?); + var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); + var processedConstants = GetProcessedConstants(constantDefinitions); + var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); + string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); + string structName = structDeclaration.Identifier.Text; + SyntaxTokenList structModifiers = structDeclaration.Modifiers; + IEnumerable bodyStatements = GenerateRenderMethodBody( + processedConstants, + staticFields, + processedTypes, + isComputeShader, + processedMembers, + pixelShaderTextureType, + accessesStaticSampler, + sharedBuffers, + processedMethods, + entryPoint, + out isHashSetDirectiveNeeded); + + implicitTextureType = pixelShaderTextureType; + isSamplerUsed = accessesStaticSampler; + + // This code produces a method declaration as follows: + // + // public readonly void BuildHlslString(ref ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("BuildHlslString")) + .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword)) + .AddParameterListParameters( + Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("ArrayPoolStringBuilder")), + Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) + .WithBody(Block(bodyStatements)); + } + + /// + /// Gets a sequence of captured fields and their mapped names. + /// + /// The current generator context in use. + /// The input instance to process. + /// The collection of currently discovered types. + /// Indicates whether or not represents a compute shader. + /// A sequence of captured fields in . + [Pure] + private static IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> GetProcessedFields( + GeneratorExecutionContext context, + INamedTypeSymbol structDeclarationSymbol, + ICollection types, + bool isComputeShader) + { + bool hlslResourceFound = false; + + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + if (fieldSymbol.IsStatic) continue; + + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + + // Group shared fields must be static + if (attribute is not null) + { + context.ReportDiagnostic(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name); + } + + // Captured fields must be named type symbols + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) + { + context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + string metadataName = typeSymbol.GetFullMetadataName(); + + // Allowed fields must be either resources, unmanaged values or delegates + if (HlslKnownTypes.IsTypedResourceType(metadataName)) + { + hlslResourceFound = true; + + // Track the type of items in the current buffer + if (HlslKnownTypes.IsStructuredBufferType(metadataName)) + { + types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); + } + } + else if (!typeSymbol.IsUnmanagedType && + typeSymbol.TypeKind != TypeKind.Delegate) + { + // Shaders can only capture valid HLSL resource types or unmanaged types + context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol); + + continue; + } + else if (typeSymbol.IsUnmanagedType && + !HlslKnownTypes.IsKnownHlslType(metadataName)) + { + // Track the type if it's a custom struct + types.Add(typeSymbol); + } + + string typeName = HlslKnownTypes.GetMappedName(typeSymbol); + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + // Yield back the current mapping for the name (if the name used a reserved keyword) + yield return (fieldSymbol, mapping ?? fieldSymbol.Name, typeName); + } + + // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource + if (!hlslResourceFound && isComputeShader) + { + context.ReportDiagnostic(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol); + } + } + + /// + /// Gets a sequence of shader static fields and their mapped names. + /// + /// The current generator context in use. + /// The instance for the type to process. + /// The instance for the current type. + /// The type symbol for the shader type. + /// The collection of currently discovered types. + /// The collection of discovered constant definitions. + /// A sequence of static constant fields in . + [Pure] + private static IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( + GeneratorExecutionContext context, + SemanticModelProvider semanticModel, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + ICollection discoveredTypes, + IDictionary constantDefinitions) + { + foreach (var fieldDeclaration in structDeclaration.Members.OfType()) + { + foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) + { + IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!; + + if (!fieldSymbol.IsStatic || fieldSymbol.IsConst) + { + continue; + } + + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + + if (attribute is not null) continue; + + // Constant properties must be of a primitive, vector or matrix type + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || + !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName())) + { + context.ReportDiagnostic(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + string typeDeclaration = fieldSymbol.IsReadOnly switch + { + true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}", + false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" + }; + + StaticFieldRewriter staticFieldRewriter = new( + semanticModel, + discoveredTypes, + constantDefinitions, + context); + + string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString(); + + yield return (mapping ?? fieldSymbol.Name, typeDeclaration, assignment); + } + } + } + + /// + /// Gets a sequence of captured members and their mapped names. + /// + /// The current generator context in use. + /// The input instance to process. + /// The collection of currently discovered types. + /// A sequence of captured members in . + [Pure] + private static IEnumerable<(string Name, string Type, int? Count)> GetGroupSharedMembers( + GeneratorExecutionContext context, + INamedTypeSymbol structDeclarationSymbol, + ICollection types) + { + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + if (!fieldSymbol.IsStatic) continue; + + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + + if (attribute is null) continue; + + if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol) + { + context.ReportDiagnostic(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + if (!typeSymbol.ElementType.IsUnmanagedType) + { + context.ReportDiagnostic(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; + + string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + yield return (mapping ?? fieldSymbol.Name, typeName, bufferSize); + + types.Add((INamedTypeSymbol)typeSymbol.ElementType); + } + } + + /// + /// Gets a sequence of processed methods declared within a given type. + /// + /// The current generator context in use. + /// The type symbol for the shader type. + /// The instance for the current type. + /// The instance for the type to process. + /// The collection of currently discovered types. + /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. + /// Indicates whether or not represents a compute shader. + /// A sequence of processed methods in , and the entry point. + [Pure] + private static (string EntryPoint, IEnumerable<(string Signature, string Definition)> ProcessedMethods, bool IsSamplerUser) GetProcessedMethods( + GeneratorExecutionContext context, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary constantDefinitions, + bool isComputeShader) + { + // Find all declared methods in the type + ImmutableArray methodDeclarations = ( + from syntaxNode in structDeclaration.DescendantNodes() + where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) + select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); + + string? entryPoint = null; + List<(string, string)> processedMethods = new(); + bool isSamplerUsed = false; + + foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) + { + IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!; + bool isShaderEntryPoint = + (isComputeShader && + methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && + methodDeclarationSymbol.ReturnsVoid && + methodDeclarationSymbol.TypeParameters.Length == 0 && + methodDeclarationSymbol.Parameters.Length == 0) || + (!isComputeShader && + methodDeclarationSymbol.Name == nameof(IPixelShader.Execute) && + methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type + methodDeclarationSymbol.TypeParameters.Length == 0 && + methodDeclarationSymbol.Parameters.Length == 0); + + // Create the source rewriter for the current method + ShaderSourceRewriter shaderSourceRewriter = new( + structDeclarationSymbol, + semanticModel, + discoveredTypes, + staticMethods, + constantDefinitions, + context, + isShaderEntryPoint); + + // Rewrite the method syntax tree + MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); + + // Track the implicit sampler, if used + isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed; + + // Emit the extracted local functions first + foreach (var localFunction in shaderSourceRewriter.LocalFunctions) + { + processedMethods.Add(( + localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); + } + + // If the method is the shader entry point, do additional processing + if (isShaderEntryPoint) + { + processedMethod = isComputeShader switch + { + true => new ExecuteMethodRewriter.Compute(shaderSourceRewriter).Visit(processedMethod)!, + false => new ExecuteMethodRewriter.Pixel(shaderSourceRewriter).Visit(processedMethod)! + }; + + entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString(); + } + else + { + processedMethods.Add(( + processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + processedMethod.NormalizeWhitespace(eol: "\n").ToFullString())); + } + } + + // Process static methods as well + foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) + { + processedMethods.Add(( + staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); + } + + return (entryPoint!, processedMethods, isSamplerUsed); + } + + /// + /// Gets a sequence of discovered constants. + /// + /// The collection of discovered constant definitions. + /// A sequence of discovered constants to declare in the shader. + [Pure] + internal static IEnumerable<(string Name, string Value)> GetProcessedConstants(IReadOnlyDictionary constantDefinitions) + { + foreach (var constant in constantDefinitions) + { + var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; + + yield return (constantName, constant.Value); + } + } + + /// + /// Gets the sequence of processed discovered custom types. + /// + /// The sequence of discovered custom types. + /// A sequence of custom type definitions to add to the shader source. + internal static IEnumerable<(string Name, string Definition)> GetProcessedTypes(IEnumerable types) + { + foreach (var type in HlslKnownTypes.GetCustomTypes(types)) + { + var structType = type.GetFullMetadataName().ToHlslIdentifierName(); + var structDeclaration = StructDeclaration(structType); + + // Declare the fields of the current type + foreach (var field in type.GetMembers().OfType()) + { + INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; + + // Convert the name to the fully qualified HLSL version + if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped)) + { + mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName(); + } + + structDeclaration = structDeclaration.AddMembers( + FieldDeclaration(VariableDeclaration( + IdentifierName(mapped!)).AddVariables( + VariableDeclarator(Identifier(field.Name))))); + } + + // Insert the trailing ; right after the closing bracket (after normalization) + yield return + (structType, + structDeclaration + .NormalizeWhitespace(eol: "\n") + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) + .ToFullString()); + } + } + + /// + /// Finds and reports all declared properties in a shader. + /// + /// The current generator context in use. + /// The input instance to process. + private static void DetectAndReportPropertyDeclarations(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol) + { + foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType()) + { + context.ReportDiagnostic(DiagnosticDescriptors.PropertyDeclaration, propertySymbol); + } + } + + /// + /// Produces the series of statements to build the current HLSL source. + /// + /// The sequence of defined constants for the shader. + /// The sequence of static fields referenced by the shader. + /// The sequence of declared types used by the shader. + /// Whether or not the current shader is a compute shader (or a pixel shader). + /// The sequence of instance fields for the current shader. + /// The type of the implicit target texture, if present. + /// Whether the static sampler is used by the shader. + /// The sequence of shared buffers declared by the shader. + /// The sequence of processed methods used by the shader. + /// The body of the entry point of the shader. + /// Indicates whether or not the directive for is needed. + /// The series of statements to build the HLSL source to compile to execute the current shader. + private static IEnumerable GenerateRenderMethodBody( + IEnumerable<(string Name, string Value)> definedConstants, + IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields, + IEnumerable<(string Name, string Definition)> declaredTypes, + bool isComputeShader, + IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields, + string? implicitTextureType, + bool isSamplerUsed, + IEnumerable<(string Name, string Type, int? Count)> sharedBuffers, + IEnumerable<(string Signature, string Definition)> processedMethods, + string executeMethod, + out bool isHashSetDirectiveNeeded) + { + List statements = new(); + StringBuilder textBuilder = new(); + int capturedDelegates = 0; + int prologueStatements = 0; + int sizeHint = 64; + + void AppendLF() + { + textBuilder.Append('\n'); + } + + void AppendLine(string text) + { + textBuilder.Append(text); + } + + void AppendLineAndLF(string text) + { + textBuilder.Append(text); + textBuilder.Append('\n'); + } + + void AppendCharacterAndLF(char c) + { + textBuilder.Append(c); + textBuilder.Append('\n'); + } + + void AppendParsedStatement(string text) + { + FlushText(); + + statements.Add(ParseStatement(text)); + } + + void FlushText() + { + if (textBuilder.Length > 0) + { + sizeHint += textBuilder.Length; + + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(textBuilder.ToString())))))); + + textBuilder.Clear(); + } + } + + // Declare the hashsets to track imported members and types from delegates, if needed + if (instanceFields.Any(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) + { + void DeclareMapping(int index, string name, IEnumerable items) + { + // HashSet = new(); + statements.Insert(index, + LocalDeclarationStatement(VariableDeclaration( + GenericName(Identifier("HashSet")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword)))) + .AddVariables( + VariableDeclarator(Identifier(name)) + .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression()))))); + + prologueStatements++; + + // .Add(""); + foreach (var item in items) + { + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(name), + IdentifierName("Add"))) + .AddArgumentListArguments(Argument( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item)))))); + + prologueStatements++; + } + } + + DeclareMapping(0, "__typeNames", declaredTypes.Select(static t => t.Name)); + DeclareMapping(1, "__constantNames", definedConstants.Select(static t => t.Name)); + DeclareMapping(2, "__methodNames", processedMethods.Select(static t => t.Signature)); + + // Go through all existing delegate fields, if any + foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) + { + // ShaderMethodSourceAttribute __Attribute = ShaderMethodSourceAttribute.GetForDelegate(, ""); + statements.Add( + LocalDeclarationStatement(VariableDeclaration(IdentifierName(nameof(ShaderMethodSourceAttribute))) + .AddVariables( + VariableDeclarator(Identifier($"__{fieldName}Attribute")) + .WithInitializer( + EqualsValueClause( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(nameof(ShaderMethodSourceAttribute)), + IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) + .AddArgumentListArguments( + Argument(IdentifierName(fieldName)), + Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); + + capturedDelegates++; + prologueStatements++; + } + } + + isHashSetDirectiveNeeded = capturedDelegates > 0; + + // Header + AppendLineAndLF("// ================================================"); + AppendLineAndLF("// AUTO GENERATED"); + AppendLineAndLF("// ================================================"); + AppendLineAndLF("// This shader was created by ComputeSharp."); + AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp."); + + // Group size constants + AppendLF(); + AppendLine("#define __GroupSize__get_X "); + AppendParsedStatement("builder.Append(threadsX);"); + AppendLF(); + AppendLine("#define __GroupSize__get_Y "); + AppendParsedStatement("builder.Append(threadsY);"); + AppendLF(); + AppendLine("#define __GroupSize__get_Z "); + AppendParsedStatement("builder.Append(threadsZ);"); + AppendLF(); + + // Define declarations + foreach (var (name, value) in definedConstants) + { + AppendLineAndLF($"#define {name} {value}"); + } + + // Defines from captured delegates + foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);"); + } + + // Static fields + if (staticFields.Any()) + { + AppendLF(); + + foreach (var field in staticFields) + { + if (field.Assignment is string assignment) + { + AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};"); + } + else + { + AppendLineAndLF($"{field.TypeDeclaration} {field.Name};"); + } + } + } + + // Declared types + foreach (var (_, typeDefinition) in declaredTypes) + { + AppendLF(); + AppendLineAndLF(typeDefinition); + } + + // Declared types from captured delegates + foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);"); + } + + // Captured variables + AppendLF(); + AppendLineAndLF("cbuffer _ : register(b0)"); + AppendCharacterAndLF('{'); + AppendLineAndLF(" uint __x;"); + AppendLineAndLF(" uint __y;"); + + if (isComputeShader) + { + AppendLineAndLF(" uint __z;"); + } + + // User-defined values + foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.IsUnmanagedType)) + { + AppendLineAndLF($" {fieldType} {fieldName};"); + } + + AppendCharacterAndLF('}'); + + int + constantBuffersCount = 1, + readOnlyBuffersCount = 0, + readWriteBuffersCount = 0; + + // Optional implicit texture field + if (!isComputeShader) + { + AppendLF(); + AppendLineAndLF($"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});"); + } + + // Optional sampler field + if (isSamplerUsed) + { + AppendLF(); + AppendLineAndLF("SamplerState __sampler : register(s);"); + } + + // Resources + foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) + { + string metadataName = fieldSymbol.Type.GetFullMetadataName(); + + if (HlslKnownTypes.IsConstantBufferType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"cbuffer _{fieldName} : register(b{constantBuffersCount++})"); + AppendCharacterAndLF('{'); + AppendLineAndLF($" {fieldType} {fieldName}[2];"); + AppendCharacterAndLF('}'); + } + else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"{fieldType} {fieldName} : register(t{readOnlyBuffersCount++});"); + } + else if (HlslKnownTypes.IsTypedResourceType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"{fieldType} {fieldName} : register(u{readWriteBuffersCount++});"); + } + } + + // Shared buffers + foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers) + { + object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ"; + + AppendLF(); + AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];"); + } + + // Forward declarations + foreach (var (forwardDeclaration, _) in processedMethods) + { + AppendLF(); + AppendLineAndLF(forwardDeclaration); + } + + // Forward declarations from captured delegates + foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);"); + } + + // Remove all forward declarations from methods that are embedded into the shader. + // This is necessary to avoid duplicate definitions from methods from delegates. + if (capturedDelegates > 0) + { + // .Add(""); + foreach (var (forwardDeclaration, _) in processedMethods) + { + FlushText(); + + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("__methodNames"), + IdentifierName("Remove"))) + .AddArgumentListArguments(Argument( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration)))))); + } + } + + // Captured methods + foreach (var (_, method) in processedMethods) + { + AppendLF(); + AppendLineAndLF(method); + } + + // Captured methods from captured delegates + foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);"); + } + + // Captured delegate methods + foreach (var (fieldSymbol, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) + { + AppendLF(); + AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");"); + AppendLF(); + } + + // Entry point + AppendLF(); + AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); + AppendLineAndLF(executeMethod); + + FlushText(); + + // builder = ArrayPoolStringBuilder.Create(); + statements.Insert( + prologueStatements, + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("builder"), + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("ArrayPoolStringBuilder"), + IdentifierName("Create"))) + .AddArgumentListArguments( + Argument(LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(sizeHint))))))); + + return statements; + } + } +} + diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs new file mode 100644 index 00000000..9f3e0235 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs @@ -0,0 +1,96 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.Contracts; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators +{ + /// + public sealed partial class IShaderGenerator + { + /// + private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol) + { + // This code produces a method declaration as follows: + // + // public readonly int GetDispatchId() + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.IntKeyword)), + Identifier("GetDispatchId")) + .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword)) + .WithBody(GetShaderHashCodeBody(structDeclarationSymbol)); + } + + /// + /// Gets a instance with the logic to compute the hashcode of a given shader type. + /// + /// The input instance to process. + /// The instance to hash the input shader. + [Pure] + private static BlockSyntax GetShaderHashCodeBody(INamedTypeSymbol structDeclarationSymbol) + { + var delegateFields = structDeclarationSymbol + .GetMembers() + .OfType() + .Where(static m => m.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false }) + .ToImmutableArray(); + + if (delegateFields.Length == 0) + { + // return 0; + return + Block(ReturnStatement( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))); + } + + List blockStatements = new(4); + + // HashCode hashCode = default; + blockStatements.Add(LocalDeclarationStatement( + VariableDeclaration(IdentifierName("HashCode")) + .AddVariables( + VariableDeclarator(Identifier("hashCode")) + .WithInitializer(EqualsValueClause( + LiteralExpression( + SyntaxKind.DefaultLiteralExpression, + Token(SyntaxKind.DefaultKeyword))))))); + + foreach (IFieldSymbol fieldSymbol in delegateFields) + { + // hashCode.Add(delegateField.Method); + blockStatements.Add(ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("hashCode"), + IdentifierName("Add"))) + .AddArgumentListArguments(Argument( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(fieldSymbol.Name), + IdentifierName("Method")))))); + } + + // return hashCode.ToHashCode(); + blockStatements.Add(ReturnStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("hashCode"), + IdentifierName("ToHashCode"))))); + + return Block(blockStatements); + } + } +} + diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs new file mode 100644 index 00000000..50e40a94 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -0,0 +1,342 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using ComputeSharp.Core.Helpers; +using ComputeSharp.SourceGenerators.Diagnostics; +using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Mappings; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators +{ + /// + public sealed partial class IShaderGenerator + { + /// + private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod( + GeneratorExecutionContext context, + INamedTypeSymbol structDeclarationSymbol, + out IReadOnlyCollection discoveredResources, + out int root32BitConstantsCount) + { + // This code produces a method declaration as follows: + // + // public readonly void LoadDispatchData(ref TDataLoader loader, GraphicsDevice device, int x, int y, int z) + // where TDataLoader : struct, IDispatchDataLoader + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("LoadDispatchData")) + .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword)) + .AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader"))) + .AddParameterListParameters( + Parameter(Identifier("loader")) + .AddModifiers(Token(SyntaxKind.RefKeyword)) + .WithType(IdentifierName("TDataLoader")), + Parameter(Identifier("device")).WithType(IdentifierName("GraphicsDevice")), + Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) + .AddConstraintClauses( + TypeParameterConstraintClause(IdentifierName("TDataLoader")) + .AddConstraints( + ClassOrStructConstraint(SyntaxKind.StructConstraint), + TypeConstraint(IdentifierName("IDispatchDataLoader")))) + .WithBody(Block(GetDispatchDataLoadingStatements(context, structDeclarationSymbol, out discoveredResources, out root32BitConstantsCount))); + } + + /// + /// Gets a sequence of statements to load the dispatch data for a given shader. + /// + /// The current generator context in use. + /// The input instance to process. + /// The collection of discovered resources in the current shader type. + /// The total number of 32 bit root constants being loaded for the current shader type. + /// The sequence of instances to load shader dispatch data. + private static IEnumerable GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out IReadOnlyCollection discoveredResources, out int root32BitConstantsCount) + { + List statements = new(); + List resources = new(); + + discoveredResources = resources; + + var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); + var isComputeShader = pixelShaderSymbol is null; + int + resourceOffset = 0, + rawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2); + + // Append the statements for the dispatch ranges: + // + // span0[0] = (uint)x; + // span0[1] = (uint)y; + // span0[2] = (uint)z; + statements.Add( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))), + CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x"))))); + + statements.Add( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))), + CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y"))))); + + if (isComputeShader) + { + statements.Add( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))), + CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z"))))); + } + + // Append the statements to load all fields (both resources and other captured values) + AppendFields(structDeclarationSymbol, Array.Empty(), ref resourceOffset, ref rawDataOffset, resources, statements); + + // After all the captured fields have been processed, ansure 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. + rawDataOffset = AlignmentHelper.Pad(rawDataOffset, sizeof(int)); + root32BitConstantsCount = 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 rootSignatureDwordSize = root32BitConstantsCount + resourceOffset; + + if (rootSignatureDwordSize > 64) + { + context.ReportDiagnostic(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); + } + + // Span span0 = stackalloc uint[]; + statements.Insert(0, + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("span0")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount))))))))))); + + // ref uint r0 = ref span0[0]; + statements.Insert(1, + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + // loader.LoadCapturedValues(span0); + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadCapturedValues"))) + .AddArgumentListArguments(Argument(IdentifierName("span0"))))); + + if (resourceOffset > 0) + { + // Span span1 = stackalloc ulong[]; + statements.Insert(1, + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("span1")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceOffset))))))))))); + + // ref ulong r1 = ref span1[0]; + statements.Insert(3, + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r1")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span1")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + // loader.LoadCapturedResources(span1); + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadCapturedResources"))) + .AddArgumentListArguments(Argument(IdentifierName("span1"))))); + } + + return statements; + } + + /// + /// Explores a given type hierarchy and generates statements to load fields. + /// + /// The current type being explored. + /// The current path of the field with respect to the shader instance. + /// The current offset in the root table of loaded resources. + /// The current offset within the loaded data buffer. + /// The target list of resources in the current shader type. + /// The target list of statements being generated. + private static void AppendFields(ITypeSymbol currentTypeSymbol, IReadOnlyCollection fieldPath, ref int resourceOffset, ref int rawDataOffset, ICollection resources, ICollection statements) + { + bool isFirstField = true; + + foreach ( + IFieldSymbol fieldSymbol in + from fieldSymbol in currentTypeSymbol.GetMembers().OfType() + where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } && + !fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer + select fieldSymbol) + { + string + fieldName = fieldSymbol.Name, + typeName = fieldSymbol.Type.GetFullMetadataName(); + + // Disambiguates the name of target fields against the current input parameters + if (fieldName is "loader" or "device" or "x" or "y" or "z") + { + fieldName = $"this.{fieldName}"; + } + + // The first item in each nested struct needs to be aligned to 16 bytes + if (isFirstField && fieldPath.Count > 0) + { + rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); + + isFirstField = false; + } + + if (HlslKnownTypes.IsTypedResourceType(typeName)) + { + resources.Add(typeName); + + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"Unsafe.Add(ref r1, {resourceOffset++})"), + ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({fieldName}, device)")))); + } + else if (HlslKnownTypes.IsKnownHlslType(typeName)) + { + AppendHlslKnownTypeField(fieldPath.Concat(new[] { fieldName }), typeName, ref rawDataOffset, statements); + } + else if (fieldSymbol.Type.IsUnmanagedType) + { + // Custom struct type defined by the user + AppendFields(fieldSymbol.Type, fieldPath.Concat(new[] { fieldName }).ToArray(), ref resourceOffset, ref rawDataOffset, resources, statements); + } + } + } + + /// + /// Generates a loading statement for a known HLSL primitive type field (scalar, vector or matrix). + /// + /// The current path of the field with respect to the shader instance. + /// The type name currently being read. + /// The current offset within the loaded data buffer. + /// The target list of statements being generated. + private static void AppendHlslKnownTypeField(IEnumerable fieldPath, string typeName, ref int rawDataOffset, ICollection statements) + { + // For scalar, vector and linear matrix types, serialize the value normally. + // Only the initial alignment needs to be considered, while data is packed. + var (fieldSize, 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)) + { + string + rowTypeName = $"ComputeSharp.{elementName}{columns}", + rowLocalName = $"__{string.Join("_", fieldPath)}__row0"; + + statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref Unsafe.As<{typeName}, {rowTypeName}>(ref Unsafe.AsRef(in {string.Join(".", fieldPath)}));")); + + // Generate the loading code for each individual row, with proper alignment. + // This will result in the following (assuming Float2x3 m): + // + // ref Float3 __m__row0 = ref Unsafe.As(ref Unsafe.AsRef(in m)); + // Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, Unsafe.Add(ref __m__row0, 0); + // Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = Unsafe.Add(ref __m__row0, 1); + for (int j = 0; j < rows; j++) + { + rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); + + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"), + ParseExpression($"Unsafe.Add(ref {rowLocalName}, {j})")))); + + rawDataOffset += fieldPack * columns; + } + } + 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. + rawDataOffset = AlignmentHelper.AlignToBoundary( + AlignmentHelper.Pad(rawDataOffset, fieldPack), + fieldSize, + 16); + + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"), + ParseExpression($"{string.Join(".", fieldPath)}")))); + + rawDataOffset += fieldSize; + } + } + } +} + diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs new file mode 100644 index 00000000..c67767fe --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Generic; +using ComputeSharp.SourceGenerators.Mappings; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators +{ + /// + public sealed partial class IShaderGenerator + { + /// + private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod( + string? implicitTextureType, + IReadOnlyCollection discoveredResources, + int root32BitConstantsCount, + bool isSamplerUsed) + { + // This code produces a method declaration as follows: + // + // public readonly void LoadDispatchMetadata(ref TMetadataLoader loader, out IntPtr result) + // where TMetadataLoader : struct, IDispatchMetadataLoader + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("LoadDispatchMetadata")) + .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword)) + .AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader"))) + .AddParameterListParameters( + Parameter(Identifier("loader")) + .AddModifiers(Token(SyntaxKind.RefKeyword)) + .WithType(IdentifierName("TMetadataLoader")), + Parameter(Identifier("result")) + .AddModifiers(Token(SyntaxKind.OutKeyword)) + .WithType(IdentifierName(typeof(IntPtr).Name))) + .AddConstraintClauses( + TypeParameterConstraintClause(IdentifierName("TMetadataLoader")) + .AddConstraints( + ClassOrStructConstraint(SyntaxKind.StructConstraint), + TypeConstraint(IdentifierName("IDispatchMetadataLoader")))) + .WithBody(Block(GetDispatchMetadataLoadingStatements(implicitTextureType, discoveredResources, root32BitConstantsCount, isSamplerUsed))); + } + + /// + /// Gets a sequence of statements to load the dispatch metadata for a given shader type. + /// + /// The implicit texture type, if available (if the shader is a pixel shader). + /// The collection of resources used by the shader. + /// The total number of 32 bit root constants being loaded for the shader. + /// Whether or not the shader requires a static sampler to be available. + /// The sequence of instances to load shader dispatch data. + private static IEnumerable GetDispatchMetadataLoadingStatements( + string? implicitTextureType, + IReadOnlyCollection discoveredResources, + int root32BitConstantsCount, + bool isSamplerUsed) + { + // Span span0 = stackalloc byte[5]; + yield return + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("span0")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5)))))))))); + + // Compute the total number of resources (discovered ones and the implicit target texture, if present) + int totalResourcesCount = discoveredResources.Count + (implicitTextureType is not null ? 1 : 0); + + // Span span1 = stackalloc ResourceDescriptor[]; + yield return + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("Span")) + .AddTypeArgumentListArguments(IdentifierName("ResourceDescriptor"))) + .AddVariables( + VariableDeclarator(Identifier("span1")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(IdentifierName("ResourceDescriptor")) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount)))))))))); + + // ref byte r0 = ref span0[0]; + yield return + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0))))))))); + + // ref ResourceDescriptor r1 = ref span1[0]; + yield return + LocalDeclarationStatement( + VariableDeclaration(RefType(IdentifierName("ResourceDescriptor"))) + .AddVariables( + VariableDeclarator(Identifier("r1")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span1")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0))))))))); + + // Serialized shader metadata + yield return ParseStatement($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r0, 0), {root32BitConstantsCount});"); + yield return ParseStatement($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r0, 4), {isSamplerUsed.ToString().ToLowerInvariant()});"); + + int + constantBufferOffset = 1, + readOnlyResourceOffset = 0, + readWriteResourceOffset = 0, + resourceOffset = 0; + + // Add the implicit texture descriptor, if needed + if (implicitTextureType is not null) + { + yield return ParseStatement($"ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));"); + } + + // Populate the sequence of resource descriptors + foreach (var resource in discoveredResources) + { + if (HlslKnownTypes.IsConstantBufferType(resource)) + { + yield return ParseStatement($"ResourceDescriptor.Create(2, {constantBufferOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));"); + } + else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource)) + { + yield return ParseStatement($"ResourceDescriptor.Create(0, {readOnlyResourceOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));"); + } + else + { + yield return ParseStatement($"ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));"); + } + } + + // Invoke the value delegate to create the opaque root signature handle + yield return ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);"); + } + } +} + diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.SyntaxReceiver.cs similarity index 97% rename from src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.SyntaxReceiver.cs rename to src/ComputeSharp.SourceGenerators/IShaderGenerator.SyntaxReceiver.cs index a4d2182b..0f61834c 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.SyntaxReceiver.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.SyntaxReceiver.cs @@ -7,7 +7,7 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; namespace ComputeSharp.SourceGenerators { /// - public sealed partial class IComputeShaderSourceGenerator + public sealed partial class IShaderGenerator { /// /// An that selects candidate nodes to process. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs new file mode 100644 index 00000000..085f2734 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -0,0 +1,225 @@ +using System.Collections.Generic; +using System.Linq; +using System.Text; +using ComputeSharp.SourceGenerators.Diagnostics; +using ComputeSharp.SourceGenerators.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; + +namespace ComputeSharp.SourceGenerators +{ + /// + /// A source generator creating data loaders for and types. + /// + [Generator] + public sealed partial class IShaderGenerator : ISourceGenerator + { + /// + public void Initialize(GeneratorInitializationContext context) + { + context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver()); + } + + /// + public void Execute(GeneratorExecutionContext context) + { + // Get the syntax receiver with the candidate nodes + if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver) + { + return; + } + + foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo) + { + try + { + OnExecute(context, item.StructDeclaration, item.StructSymbol); + } + catch + { + context.ReportDiagnostic(IShaderGeneratorError, item.StructDeclaration, item.StructSymbol); + } + } + } + + /// + /// Processes a given target type. + /// + /// The input instance to use. + /// The node to process. + /// The for . + private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol) + { + // Create the required interface methods for the current shader type + MethodDeclarationSyntax + getDispatchIdMethod = CreateGetDispatchIdMethod(structDeclarationSymbol), + loadDispatchDataMethod = CreateLoadDispatchDataMethod(context, structDeclarationSymbol, out var discoveredResources, out int root32BitConstants), + buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed, out bool isHashSetDirectiveNeeded), + loadDispatchMetadataMethod = CreateLoadDispatchMetadataMethod(implicitTextureType, discoveredResources, root32BitConstants, isSamplerUsed); + + // Reorder the method declarations to respect the order in the interface definition + MethodDeclarationSyntax[] methods = + { + getDispatchIdMethod, + loadDispatchDataMethod, + loadDispatchMetadataMethod, + buildHlslStringMethod + }; + + // Method attributes + AttributeListSyntax[] attributes = new[] + { + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( + AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( + AttributeArgument(LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal("This method is not intended to be used directly by user code")))))) + }; + + string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); + string structName = structDeclaration.Identifier.Text; + SyntaxTokenList structModifiers = structDeclaration.Modifiers; + + // Create the partial shader type declaration with the hashcode interface method implementation. + // This code produces a struct declaration as follows: + // + // public struct ShaderType : IShader + // { + // + // } + var structDeclarationSyntax = + StructDeclaration(structName) + .WithModifiers(structModifiers) + .AddBaseListTypes(SimpleBaseType( + GenericName(Identifier("IShader")) + .AddTypeArgumentListArguments(IdentifierName(structName)))) + .AddMembers(methods.Select(m => m.AddAttributeLists(attributes)).ToArray()); + + TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; + + // Add all parent types in ascending order, if any + foreach (var parentType in structDeclaration.Ancestors().OfType()) + { + typeDeclarationSyntax = parentType + .WithMembers(SingletonList(typeDeclarationSyntax)) + .WithConstraintClauses(List()) + .WithBaseList(null) + .WithAttributeLists(List()) + .WithoutTrivia(); + } + + // Prepare the necessary using directives + List usingDirectives = new() + { + UsingDirective(IdentifierName("System")), + UsingDirective(IdentifierName("System.CodeDom.Compiler")), + UsingDirective(IdentifierName("System.ComponentModel")), + UsingDirective(IdentifierName("System.Diagnostics")), + UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")), + UsingDirective(IdentifierName("System.Runtime.CompilerServices")), + UsingDirective(IdentifierName("ComputeSharp")), + UsingDirective(IdentifierName("ComputeSharp.__Internals")) + }; + + if (isHashSetDirectiveNeeded) + { + usingDirectives.Insert(2, UsingDirective(IdentifierName("System.Collections.Generic"))); + } + + // Create a static method to create the combined hashcode for a given shader type. + // This code takes a block syntax and produces a compilation unit as follows: + // + // using System; + // using System.CodeDom.Compiler; + // using System.ComponentModel; + // using System.Diagnostics; + // using System.Diagnostics.CodeAnalysis; + // using System.Runtime.CompilerServices; + // using ComputeSharp.__Internals; + // + // #pragma warning disable + // + // namespace + // { + // + // } + var source = + CompilationUnit().AddUsings(usingDirectives.ToArray()).AddMembers( + NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax) + .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) + .NormalizeWhitespace(eol: "\n") + .ToFullString(); + + // Add the method source attribute + context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); + } + + /// + /// Creates a instance for the GetDispatchId method. + /// + /// The for . + /// The resulting instance for the GetDispatchId method. + private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol); + + /// + /// Creates a instance for the LoadDispatchDataMethod method. + /// + /// The input instance to use. + /// The for . + /// The collection of discovered resources in the current shader type. + /// The total number of 32 bit root constants being loaded for the current shader type. + /// The resulting instance for the LoadDispatchDataMethod method. + private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod( + GeneratorExecutionContext context, + INamedTypeSymbol structDeclarationSymbol, + out IReadOnlyCollection discoveredResources, + out int root32BitConstantsCount); + + /// + /// Creates a instance for the BuildHlslString method. + /// + /// The input instance to use. + /// The node to process. + /// The for . + /// The implicit texture type, if available (if the shader is a pixel shader). + /// Whether or not the current shader type requires a static sampler to be available. + /// Indicates whether or not the directive for is needed. + /// The resulting instance for the BuildHlslString method. + private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod( + GeneratorExecutionContext context, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + out string? implicitTextureType, + out bool isSamplerUsed, + out bool isHashSetDirectiveNeeded); + + /// + /// Creates a instance for the LoadDispatchMetadata method. + /// + /// The implicit texture type, if available (if the shader is a pixel shader). + /// The collection of resources used by the shader. + /// The total number of 32 bit root constants being loaded for the shader. + /// Whether or not the shader requires a static sampler to be available. + /// The resulting instance for the LoadDispatchMetadata method. + private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod( + string? implicitTextureType, + IReadOnlyCollection discoveredResources, + int root32BitConstantsCount, + bool isSamplerUsed); + } +} + diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 1c7a0751..468a1e56 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -101,6 +101,16 @@ namespace ComputeSharp.SourceGenerators.Mappings return knownTypes; } + /// + /// Checks whether or not a given type name matches a constant buffer type. + /// + /// The input type name to check. + /// Whether or not represents a constant buffer type. + public static bool IsConstantBufferType(string typeName) + { + return typeName == "ComputeSharp.ConstantBuffer`1"; + } + /// /// Checks whether or not a given type name matches a structured buffer type. /// @@ -118,6 +128,27 @@ namespace ComputeSharp.SourceGenerators.Mappings }; } + /// + /// Checks whether or not a given type name matches a readonly typed resource type. + /// + /// The input type name to check. + /// Whether or not represents a readonly typed resource type. + public static bool IsReadOnlyTypedResourceType(string typeName) + { + switch (typeName) + { + case "ComputeSharp.ReadOnlyBuffer`1": + case "ComputeSharp.ReadOnlyTexture2D`1": + case "ComputeSharp.ReadOnlyTexture2D`2": + case "ComputeSharp.ReadOnlyTexture3D`1": + case "ComputeSharp.ReadOnlyTexture3D`2": + case "ComputeSharp.IReadOnlyTexture2D`1": + case "ComputeSharp.IReadOnlyTexture3D`1": + return true; + default: return false; + }; + } + /// /// Checks whether or not a given type name matches a typed resource type. /// diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 7ea87bdf..898c36a4 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -66,13 +66,12 @@ namespace ComputeSharp.SourceGenerators { // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); - Dictionary staticMethods = new(SymbolEqualityComparer.Default); Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); // Explore the syntax tree and extract the processed info - var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions); - var processedTypes = IComputeShaderSourceGenerator.GetProcessedTypes(discoveredTypes).ToArray(); - var processedConstants = IComputeShaderSourceGenerator.GetProcessedConstants(constantDefinitions); + var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions); + var processedTypes = IShaderGenerator.GetProcessedTypes(discoveredTypes).ToArray(); + var processedConstants = IShaderGenerator.GetProcessedConstants(constantDefinitions); // Create the compilation unit with the source attribute var source = @@ -80,13 +79,13 @@ namespace ComputeSharp.SourceGenerators AttributeList(SingletonSeparatedList( Attribute(IdentifierName(typeof(ShaderMethodSourceAttribute).FullName)).AddArgumentListArguments( AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))), - AttributeArgument(ArrayExpression(processedTypes)), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))), - AttributeArgument(ArrayExpression(processedMethods)), + AttributeArgument(NestedArrayExpression(processedTypes)), + AttributeArgument(NestedArrayExpression(processedMethods)), AttributeArgument(NestedArrayExpression(processedConstants))))) .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) - .NormalizeWhitespace() + .NormalizeWhitespace(eol: "\n") .ToFullString(); // Add the method source attribute @@ -100,18 +99,18 @@ namespace ComputeSharp.SourceGenerators /// The instance for the current method. /// The instance for the method to process. /// The collection of currently discovered types. - /// The set of discovered and processed static methods. /// The collection of discovered constant definitions. - /// A sequence of processed methods in (main method and local functions). + /// A sequence of processed methods in (main method and all captured methods). [Pure] - private static (string TargetMethod, IEnumerable LocalFunctions) GetProcessedMethods( + private static (string TargetMethod, IEnumerable<(string Signature, string Definition)> ProcessedMethods) GetProcessedMethods( GeneratorExecutionContext context, MethodDeclarationSyntax methodDeclaration, SemanticModelProvider semanticModel, ICollection discoveredTypes, - IDictionary staticMethods, IDictionary constantDefinitions) { + Dictionary staticMethods = new(SymbolEqualityComparer.Default); + ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, context); // Rewrite the method syntax tree @@ -119,18 +118,28 @@ namespace ComputeSharp.SourceGenerators .Visit(methodDeclaration)! .WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)) .WithoutTrivia() - .NormalizeWhitespace() + .NormalizeWhitespace(eol: "\n") .ToFullString(); - List localFunctions = new(shaderSourceRewriter.LocalFunctions.Count); + List<(string, string)> processedMethods = new(shaderSourceRewriter.LocalFunctions.Count); // Emit the extracted local functions foreach (var localFunction in shaderSourceRewriter.LocalFunctions) { - localFunctions.Add(localFunction.Value.NormalizeWhitespace().ToFullString()); + processedMethods.Add(( + localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); } - return (targetMethod, localFunctions); + // Emit the discovered static methods + foreach (var staticMethod in staticMethods.Values) + { + processedMethods.Add(( + staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); + } + + return (targetMethod, processedMethods); } } } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs index 38a70d07..9cea28a0 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs @@ -171,21 +171,6 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return base.VisitUsingStatement(node); } - /// - public override SyntaxNode? VisitVariableDeclarator(VariableDeclaratorSyntax node) - { - var updatedNode = (VariableDeclaratorSyntax)base.VisitVariableDeclarator(node)!; - - if (node.Initializer is null && - node.Parent is VariableDeclarationSyntax declaration && - SemanticModel.For(node).GetTypeInfo(declaration.Type).Type is ITypeSymbol { IsUnmanagedType: false } type) - { - Context.ReportDiagnostic(InvalidObjectDeclaration, node, type); - } - - return updatedNode; - } - /// public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node) { diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs index b52a6974..d346d8f4 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs @@ -73,6 +73,25 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); } + /// + public override SyntaxNode? VisitVariableDeclaration(VariableDeclarationSyntax node) + { + var updatedNode = (VariableDeclarationSyntax)base.VisitVariableDeclaration(node)!; + + if (SemanticModel.For(node).GetTypeInfo(node.Type).Type is ITypeSymbol { IsUnmanagedType: false } type) + { + Context.ReportDiagnostic(InvalidObjectDeclaration, node, type); + } + + // If var is used, replace it with the explicit type + if (updatedNode.Type is IdentifierNameSyntax { IsVar: true }) + { + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); + } + + return updatedNode; + } + /// public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) { diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 43fe3386..cd0c7d32 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -406,7 +406,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Context); MethodDeclarationSyntax methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(), - processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace().WithoutTrivia(); + processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia(); this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier))); } diff --git a/src/ComputeSharp/Core/Attributes/__Internals/ComputeRoot32BitConstantsAttribute.cs b/src/ComputeSharp/Core/Attributes/__Internals/ComputeRoot32BitConstantsAttribute.cs deleted file mode 100644 index 3277c05b..00000000 --- a/src/ComputeSharp/Core/Attributes/__Internals/ComputeRoot32BitConstantsAttribute.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.ComponentModel; - -namespace ComputeSharp.__Internals -{ - /// - /// An attribute that contains info on the number of 32 bit constants for a given shader. - /// - /// This attribute is not meant to be directly used by applications using ComputeSharp. - [AttributeUsage(AttributeTargets.ReturnValue, AllowMultiple = false)] - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This attribute is not intended to be used directly by user code")] - public sealed class ComputeRoot32BitConstantsAttribute : Attribute - { - /// - /// Creates a new instance with the specified parameters. - /// - /// The number of 32 bit constants for the annotated method. - public ComputeRoot32BitConstantsAttribute(int count) - { - Count = count; - } - - /// - /// Gets the number of 32 bit constants for the annotated method. - /// - internal int Count { get; } - } -} \ No newline at end of file diff --git a/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs b/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs deleted file mode 100644 index d33a491b..00000000 --- a/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs +++ /dev/null @@ -1,134 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Reflection; -using ComputeSharp.Exceptions; - -namespace ComputeSharp.__Internals -{ - /// - /// An attribute that contains info on a processed compute shader that can be executed. - /// - /// This attribute is not meant to be directly used by applications using ComputeSharp. - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This attribute is not intended to be used directly by user code")] - public sealed class IComputeShaderSourceAttribute : Attribute - { - /// - /// Creates a new instance with the specified parameters. - /// - /// The type of the current shader. - /// The collection of custom types. - /// The implicit texture field info, if present. - /// The implicit texture sampler field info, if present. - /// The mapped collection of shader fields. - /// The forward declarations for static methods. - /// The source code for the method. - /// The collection of processed methods. - /// The collection of discovered defines. - /// The collection of discovered static fields. - /// The collection of group shared buffers. - public IComputeShaderSourceAttribute( - Type shaderType, - string[] types, - string[]? implicitTextureField, - string[]? implicitSamplerFields, - object[] fields, - string[] forwardDeclarations, - string executeMethod, - string[] methods, - object[] defines, - object[] staticFields, - object[] sharedBuffers) - { - ShaderType = shaderType; - Types = types; - ImplicitTextureField = implicitTextureField is null ? null : (implicitTextureField[0], implicitTextureField[1]); - ImplicitSamplerField = implicitSamplerFields is null ? null : (implicitSamplerFields[0], implicitSamplerFields[1]); - Fields = fields.Cast().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2])); - ForwardDeclarations = forwardDeclarations; - ExecuteMethod = executeMethod; - Methods = methods; - Defines = defines.Cast().ToDictionary(static c => c[0], static c => c[1]); - StaticFields = staticFields.Cast().ToDictionary(static arg => arg[0]!, static arg => (arg[1]!, arg[2])); - SharedBuffers = sharedBuffers.Cast().ToDictionary(static t => (string)t[0], static t => ((string)t[1], (int?)t[2])); - } - - /// - /// Gets the type of the current shader. - /// - internal Type ShaderType { get; } - - /// - /// Gets the collection of processed custom types. - /// - internal IReadOnlyCollection Types { get; } - - /// - /// Gets the mapping for the implicit texture field, if the shader is a pixel shader. - /// - internal (string Name, string Type)? ImplicitTextureField { get; } - - /// - /// Gets the mapping for the implicit sampler field, if necessary. - /// - internal (string Name, string Type)? ImplicitSamplerField { get; } - - /// - /// Gets the mapping of field names. - /// - internal IReadOnlyDictionary Fields { get; } - - /// - /// The forward declarations for static methods. - /// - internal IReadOnlyCollection ForwardDeclarations { get; } - - /// - /// Gets the source code for the method. - /// - internal string ExecuteMethod { get; } - - /// - /// Gets the collection of processed methods. - /// - internal IReadOnlyCollection Methods { get; } - - /// - /// Gets the collection of discovered define declarations. - /// - internal IReadOnlyDictionary Defines { get; } - - /// - /// Gets the collection of discovered static fields. - /// - internal IReadOnlyDictionary StaticFields { get; } - - /// - /// Gets the collection of discovered shared buffers. - /// - internal IReadOnlyDictionary SharedBuffers { get; } - - /// - /// Gets the associated instance for a specified type. - /// - /// The shader type to get the attribute for. - /// The associated instance for type . - [Pure] - internal static IComputeShaderSourceAttribute GetForType() - { - IEnumerable attributes = typeof(T).Assembly.GetCustomAttributes(); - IComputeShaderSourceAttribute? attribute = attributes.SingleOrDefault(static attribute => attribute.ShaderType == typeof(T)); - - if (attribute is null) - { - MissingShaderMetadataException.Throw(); - } - - return attribute!; - } - } -} \ No newline at end of file diff --git a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs new file mode 100644 index 00000000..be523c2c --- /dev/null +++ b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; + +namespace ComputeSharp.__Internals +{ + /// + public sealed partial class ShaderMethodSourceAttribute : Attribute + { + /// + /// Appends the mapped source code for the current method. + /// + /// The target instance to write to. + /// The mapping of already discovered constant names. + public void AppendConstants(ref ArrayPoolStringBuilder builder, HashSet mapping) + { + foreach (KeyValuePair constant in this.constants) + { + if (mapping.Add(constant.Key)) + { + builder.Append($"#define {constant.Key} {constant.Value}\n"); + } + } + } + + /// + /// Appends the discovered types for the current method. + /// + /// The target instance to write to. + /// The mapping of already discovered type names. + public void AppendTypes(ref ArrayPoolStringBuilder builder, HashSet mapping) + { + foreach (KeyValuePair type in this.types) + { + if (mapping.Add(type.Key)) + { + builder.Append("\n"); + builder.Append(type.Value); + builder.Append("\n"); + } + } + } + + /// + /// Appends the discovered forward declarations for the current method. + /// + /// The target instance to write to. + /// The mapping of already discovered type names. + public void AppendForwardDeclarations(ref ArrayPoolStringBuilder builder, HashSet mapping) + { + foreach (KeyValuePair method in this.methods) + { + if (mapping.Add(method.Key)) + { + builder.Append("\n"); + builder.Append(method.Key); + builder.Append("\n"); + } + } + } + + /// + /// Appends the discovered methods for the current method. + /// + /// The target instance to write to. + /// The mapping of already discovered type names. + public void AppendMethods(ref ArrayPoolStringBuilder builder, HashSet mapping) + { + foreach (KeyValuePair method in this.methods) + { + if (mapping.Remove(method.Key)) + { + builder.Append("\n"); + builder.Append(method.Value); + builder.Append("\n"); + } + } + } + + /// + /// Appends the mapped source code for the current method. + /// + /// The target instance to write to. + /// The name to bind the method to. + public void AppendMappedInvokeMethod(ref ArrayPoolStringBuilder builder, string name) + { + builder.Append(this.invokeMethod.Replace(InvokeMethodIdentifier, name)); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs index 8d0bbce3..fd76f48f 100644 --- a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs +++ b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs @@ -5,7 +5,6 @@ using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; using ComputeSharp.Core.Extensions; -using ComputeSharp.Exceptions; namespace ComputeSharp.__Internals { @@ -17,78 +16,67 @@ namespace ComputeSharp.__Internals [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This attribute is not intended to be used directly by user code")] - public sealed class ShaderMethodSourceAttribute : Attribute + public sealed partial class ShaderMethodSourceAttribute : Attribute { /// /// The identifier for the invoke method, for late binding. /// internal const string InvokeMethodIdentifier = "____"; + /// + /// The fully qualified name of the current method. + /// + private readonly string methodName; + /// /// The source code for the target entry point method. /// private readonly string invokeMethod; + /// + /// The collection of custom types. + /// + private readonly Dictionary types; + + /// + /// The collection of processed methods. + /// + private readonly Dictionary methods; + + /// + /// The collection of discovered constants. + /// + private readonly Dictionary constants; + /// /// Creates a new instance with the specified parameters. /// /// The fully qualified name of the current method. - /// The collection of custom types. /// The source code for the target entry point method. + /// The collection of custom types. /// The collection of processed methods. /// The collection of discovered constants. - public ShaderMethodSourceAttribute(string methodName, string[] types, string invokeMethod, string[] methods, object[] constants) + public ShaderMethodSourceAttribute(string methodName, string invokeMethod, object[] types, object[] methods, object[] constants) { + this.methodName = methodName; this.invokeMethod = invokeMethod; - - MethodName = methodName; - Types = types; - Methods = methods; - Constants = constants.Cast().ToDictionary(static c => c[0], static c => c[1]); - } - - /// - /// Gets the fully qualified name of the shader type. - /// - internal string MethodName { get; } - - /// - /// Gets the collection of processed custom types. - /// - internal IReadOnlyCollection Types { get; } - - /// - /// Gets the collection of processed methods. - /// - internal IReadOnlyCollection Methods { get; } - - /// - /// Gets the collection of discovered constants. - /// - internal IReadOnlyDictionary Constants { get; } - - /// - /// Gets the mapped source code for the current method. - /// - /// The name to bind the method to. - /// The mapped source code for the current mehtod. - [Pure] - internal string GetMappedInvokeMethod(string name) - { - return this.invokeMethod.Replace(InvokeMethodIdentifier, name); + this.types = types.Cast().ToDictionary(static c => c[0], static c => c[1]); + this.methods = methods.Cast().ToDictionary(static c => c[0], static c => c[1]); + this.constants = constants.Cast().ToDictionary(static c => c[0], static c => c[1]); } /// /// Gets the associated instance for a specified delegate. /// /// The input instance to get info for. + /// The name of the shader field containing . /// The associated instance for the given delegate. [Pure] - internal static ShaderMethodSourceAttribute GetForDelegate(Delegate function) + public static ShaderMethodSourceAttribute GetForDelegate(Delegate function, string name) { if (!function.Method.IsStatic) { - ThrowArgumentExceptionForNonStaticShader(); + return ThrowArgumentExceptionForNonStaticMethod(name); } var attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes(); @@ -96,21 +84,31 @@ namespace ComputeSharp.__Internals foreach (var attribute in attributes) { - if (attribute.MethodName.Equals(methodName)) + if (attribute.methodName.Equals(methodName)) { return attribute; } } - return MissingMethodSourceException.Throw(function); + return ThrowArgumentExceptionForMissingShaderMethodAttribute(name); } /// /// Throws an when a given is not static. /// - private static void ThrowArgumentExceptionForNonStaticShader() + /// The name of the shader field containing the invalid method. + private static ShaderMethodSourceAttribute ThrowArgumentExceptionForNonStaticMethod(string name) { - throw new ArgumentException("Captured delegates in a shader need to wrap a static method.", "function"); + throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a non static method (only static methods are supported for captured delegates).", name); + } + + /// + /// Throws an when a given doesn't have applied to it. + /// + /// The name of the shader field containing the invalid method. + private static ShaderMethodSourceAttribute ThrowArgumentExceptionForMissingShaderMethodAttribute(string name) + { + throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a method without the [ShaderMethod] attribute applied to it.", name); } } } \ No newline at end of file diff --git a/src/ComputeSharp/Core/Exceptions/MissingMethodSourceException.cs b/src/ComputeSharp/Core/Exceptions/MissingMethodSourceException.cs deleted file mode 100644 index c31a043b..00000000 --- a/src/ComputeSharp/Core/Exceptions/MissingMethodSourceException.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Diagnostics.Contracts; -using System.Text; -using ComputeSharp.__Internals; -using ComputeSharp.Core.Extensions; - -#pragma warning disable CS0618 - -namespace ComputeSharp.Exceptions -{ - /// - /// A custom that indicates when an HLSL-only API is called from C# - /// - public sealed class MissingMethodSourceException : InvalidOperationException - { - /// - /// Creates a new instance. - /// - /// The exception message to display. - private MissingMethodSourceException(string message) - : base(message) - { - } - - /// - /// Creates a new instance from the specified parameters. - /// - /// The target that couldn't be processed. - /// A new instance with a formatted error message. - [Pure] - private static MissingMethodSourceException Create(Delegate method) - { - StringBuilder builder = new(512); - - builder.AppendLine("The processed source for a method captured as a delegate in a shader was not found."); - builder.AppendLine($"The delegate was of type {method.GetType()} and it was wrapping the method {method.Method.GetFullName()}."); - builder.Append($"Make sure that the target method is annotated with [{nameof(ShaderMethodAttribute)}]."); - builder.ToString(); - - return new(builder.ToString()); - } - - /// - /// Throws a new for a given delegate. - /// - /// The target that couldn't be processed. - /// This method always throws and never actually returns anything. - internal static ShaderMethodSourceAttribute Throw(Delegate method) - { - throw Create(method); - } - } -} diff --git a/src/ComputeSharp/Core/Exceptions/MissingShaderMetadataException.cs b/src/ComputeSharp/Core/Exceptions/MissingShaderMetadataException.cs deleted file mode 100644 index c4b9f7eb..00000000 --- a/src/ComputeSharp/Core/Exceptions/MissingShaderMetadataException.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Diagnostics.Contracts; -using System.Text; - -namespace ComputeSharp.Exceptions -{ - /// - /// A custom type that indicates when metadata is missing for a given shader. - /// - public sealed class MissingShaderMetadataException : Exception - { - /// - /// Creates a new instance. - /// - /// The error message to include in the exception.. - private MissingShaderMetadataException(string error) - : base(error) - { - } - - /// - /// Gets a formatted exception message for a given error. - /// - /// The type of shader that was failed to be loaded. - /// A new instance with a formatted error message. - [Pure] - private static MissingShaderMetadataException Create(Type type) - { - StringBuilder builder = new(512); - - builder.AppendLine($"Failed to retrieve the shader metadata for type {type}."); - builder.AppendLine("This usually indicates that the necessary source generator failed to run. Make sure to be using a IDE with full support " + - "for source generators, and that there are no build warnings in the errors window upon building your project. If a source " + - "generator fails to run correctly, please open an issue at https://github.com/Sergio0694/ComputeSharp and include a working repro along with it."); - - return new(builder.ToString()); - } - - /// - /// Throws a new for a given delegate. - /// - internal static void Throw() - { - throw Create(typeof(T)); - } - } -} diff --git a/src/ComputeSharp/Core/Extensions/MethodInfoExtensions.cs b/src/ComputeSharp/Core/Extensions/MethodInfoExtensions.cs index b413e1b3..fbff690b 100644 --- a/src/ComputeSharp/Core/Extensions/MethodInfoExtensions.cs +++ b/src/ComputeSharp/Core/Extensions/MethodInfoExtensions.cs @@ -23,10 +23,10 @@ namespace ComputeSharp.Core.Extensions { var arguments = string.Join(", ", method.GetGenericArguments().Select(static t => t.FullName)); - return $"{method.DeclaringType!.FullName}.{method.Name}<{arguments}>({parameters})"; + return $"{method.DeclaringType!.FullName!.Replace('+', '.')}.{method.Name}<{arguments}>({parameters})"; } - return $"{method.DeclaringType!.FullName}.{method.Name}({parameters})"; + return $"{method.DeclaringType!.FullName!.Replace('+', '.')}.{method.Name}({parameters})"; } } } diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchDataLoader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchDataLoader.cs new file mode 100644 index 00000000..29af4b67 --- /dev/null +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchDataLoader.cs @@ -0,0 +1,25 @@ +using System; +using System.ComponentModel; + +namespace ComputeSharp.__Internals +{ + /// + /// A base representing a data loader for a shader being dispatched. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This interface is not intended to be used directly by user code")] + public interface IDispatchDataLoader + { + /// + /// Loads the captured values used by the shader to be dispatched. + /// + /// The sequence of serialized captured values. + void LoadCapturedValues(ReadOnlySpan data); + + /// + /// Loads the captured resources used by the shader to be dispatched. + /// + /// The sequence of serialized resources. + void LoadCapturedResources(ReadOnlySpan data); + } +} diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs new file mode 100644 index 00000000..4ad4b3ce --- /dev/null +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs @@ -0,0 +1,21 @@ +using System; +using System.ComponentModel; + +namespace ComputeSharp.__Internals +{ + /// + /// A base representing a metadatadata loader for a shader being dispatched. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This interface is not intended to be used directly by user code")] + public interface IDispatchMetadataLoader + { + /// + /// Loads an opaque metadata handle from the given shader metadata. + /// + /// The serialized metadata for the current shader. + /// The sequence of resource descriptors for the current shader. + /// The resulting opaque metadata handle. + void LoadMetadataHandle(ReadOnlySpan serializedMetadata, ReadOnlySpan resourceDescriptors, out IntPtr result); + } +} diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs new file mode 100644 index 00000000..fee6f8aa --- /dev/null +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs @@ -0,0 +1,59 @@ +using System; +using System.ComponentModel; + +namespace ComputeSharp.__Internals +{ + /// + /// A base representing a given shader that can be dispatched. + /// + /// The type of shader. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This interface is not intended to be used directly by user code")] + public interface IShader + where TSelf : struct, IShader + { + /// + /// Gets a unique dispatch identifier for the shader. + /// + /// The unique dispatch identifier for the shader. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be used directly by user code")] + int GetDispatchId(); + + /// + /// Loads the dispatch data for the shader. + /// + /// The type of data loader being used. + /// The instance to use to load the data. + /// The device the shader is being dispatched on. + /// The number of iterations to run on the X axis. + /// The number of iterations to run on the Y axis. + /// The number of iterations to run on the Z axis. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + void LoadDispatchData(ref TDataLoader loader, GraphicsDevice device, int x, int y, int z) + where TDataLoader : struct, IDispatchDataLoader; + + /// + /// Loads an opaque metadata handle from the metadata of the current shader. + /// + /// The type of data loader being used. + /// The instance to use to load the data. + /// The resulting opaque metadata handle. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + void LoadDispatchMetadata(ref TMetadataLoader loader, out IntPtr result) + where TMetadataLoader : struct, IDispatchMetadataLoader; + + /// + /// Builds the HLSL source code for the current shader instance. + /// + /// The resulting instance containing the HLSL source. + /// The number of threads in each thread group for the X axis. + /// The number of threads in each thread group for the Y axis. + /// The number of threads in each thread group for the Z axis. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + void BuildHlslString(out ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ); + } +} diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs index 543ec018..25b55a2b 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs @@ -1,9 +1,7 @@ -using System; -using System.Diagnostics.Contracts; +using ComputeSharp.Shaders; using ComputeSharp.__Internals; -using ComputeSharp.Graphics.Helpers; -using ComputeSharp.Resources; -using ComputeSharp.Shaders; + +#pragma warning disable CS0618 namespace ComputeSharp { @@ -20,7 +18,7 @@ namespace ComputeSharp /// The number of iterations to run on the X axis. /// The input instance representing the compute shader to run. public static void For(this GraphicsDevice device, int x, in T shader) - where T : struct, IComputeShader + where T : struct, IComputeShader, IShader { ShaderRunner.Run(device, x, 1, 1, in shader); } @@ -34,7 +32,7 @@ namespace ComputeSharp /// The number of iterations to run on the Y axis. /// The input instance representing the compute shader to run. public static void For(this GraphicsDevice device, int x, int y, in T shader) - where T : struct, IComputeShader + where T : struct, IComputeShader, IShader { ShaderRunner.Run(device, x, y, 1, in shader); } @@ -49,7 +47,7 @@ namespace ComputeSharp /// The number of iterations to run on the Z axis. /// The input instance representing the compute shader to run. public static void For(this GraphicsDevice device, int x, int y, int z, in T shader) - where T : struct, IComputeShader + where T : struct, IComputeShader, IShader { ShaderRunner.Run(device, x, y, z, in shader); } @@ -67,7 +65,7 @@ namespace ComputeSharp /// The number of threads in each thread group for the Z axis. /// The input instance representing the compute shader to run. public static void For(this GraphicsDevice device, int x, int y, int z, int threadsX, int threadsY, int threadsZ, in T shader) - where T : struct, IComputeShader + where T : struct, IComputeShader, IShader { ShaderRunner.Run(device, x, y, z, threadsX, threadsY, threadsZ, in shader); } @@ -80,7 +78,7 @@ namespace ComputeSharp /// The to use to run the shader. /// The target texture to apply the pixel shader to. public static void ForEach(this GraphicsDevice device, IReadWriteTexture2D texture) - where T : struct, IPixelShader + where T : struct, IPixelShader, IShader where TPixel : unmanaged { ShaderRunner.Run(device, texture, default); @@ -95,7 +93,7 @@ namespace ComputeSharp /// The target texture to apply the pixel shader to. /// The input instance representing the pixel shader to run. public static void ForEach(this GraphicsDevice device, IReadWriteTexture2D texture, in T shader) - where T : struct, IPixelShader + where T : struct, IPixelShader, IShader where TPixel : unmanaged { ShaderRunner.Run(device, texture, in shader); diff --git a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs index fdf9a066..17eaea5f 100644 --- a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs @@ -34,8 +34,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the buffer. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong ValidateAndGetGpuDescriptorHandle(Buffer buffer, GraphicsDevice device) where T : unmanaged @@ -53,8 +51,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong ValidateAndGetGpuDescriptorHandle(ReadOnlyTexture2D texture, GraphicsDevice device) where T : unmanaged @@ -72,8 +68,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong ValidateAndGetGpuDescriptorHandle(ReadWriteTexture2D texture, GraphicsDevice device) where T : unmanaged @@ -91,8 +85,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadOnlyTexture2D texture, GraphicsDevice device) where TPixel : unmanaged @@ -114,8 +106,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadWriteTexture2D texture, GraphicsDevice device) where TPixel : unmanaged @@ -137,8 +127,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong ValidateAndGetGpuDescriptorHandle(ReadOnlyTexture3D texture, GraphicsDevice device) where T : unmanaged @@ -156,8 +144,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong ValidateAndGetGpuDescriptorHandle(ReadWriteTexture3D texture, GraphicsDevice device) where T : unmanaged @@ -175,8 +161,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadOnlyTexture3D texture, GraphicsDevice device) where TPixel : unmanaged @@ -198,8 +182,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadWriteTexture3D texture, GraphicsDevice device) where TPixel : unmanaged diff --git a/src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs b/src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs new file mode 100644 index 00000000..fbe2853f --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs @@ -0,0 +1,52 @@ +using System; +using System.ComponentModel; +using TerraFX.Interop; +using FX = TerraFX.Interop.Windows; +using static TerraFX.Interop.D3D12_DESCRIPTOR_RANGE_FLAGS; + +#pragma warning disable IDE0052, CS0414 + +namespace ComputeSharp.__Internals +{ + /// + /// An opaque type describing a captured resource to be used in a shader. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This interface is not intended to be used directly by user code")] + public struct ResourceDescriptor + { + /// + private D3D12_DESCRIPTOR_RANGE_TYPE RangeType; + + /// + private uint NumDescriptors; + + /// + private uint BaseShaderRegister; + + /// + private uint RegisterSpace; + + /// + private D3D12_DESCRIPTOR_RANGE_FLAGS Flags; + + /// + private uint OffsetInDescriptorsFromTableStart; + + /// + /// Initializes a new instance. + /// + /// The type of resource to create the descriptor for. + /// The offset in the resource from the start of the shader mapping. + /// The resulting instance. + public static void Create(int type, uint offset, out ResourceDescriptor descriptor) + { + descriptor.RangeType = (D3D12_DESCRIPTOR_RANGE_TYPE)type; + descriptor.NumDescriptors = 1; + descriptor.BaseShaderRegister = offset; + descriptor.RegisterSpace = 0; + descriptor.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE; + descriptor.OffsetInDescriptorsFromTableStart = FX.D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; + } + } +} diff --git a/src/ComputeSharp/Shaders/Dispatching/ComputeShaderDispatchDataLoader.cs b/src/ComputeSharp/Shaders/Dispatching/ComputeShaderDispatchDataLoader.cs new file mode 100644 index 00000000..86bc33f6 --- /dev/null +++ b/src/ComputeSharp/Shaders/Dispatching/ComputeShaderDispatchDataLoader.cs @@ -0,0 +1,57 @@ +using System; +using System.Runtime.CompilerServices; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.__Internals; +using TerraFX.Interop; +using System.Runtime.InteropServices; + +#pragma warning disable CS0618 + +namespace ComputeSharp.Shaders.Dispatching +{ + /// + /// A data loader for compute shaders. + /// + internal readonly unsafe struct ComputeShaderDispatchDataLoader : IDispatchDataLoader + { + /// + /// The object in use. + /// + private readonly ID3D12GraphicsCommandList* d3D12GraphicsCommandList; + + /// + /// Creates a new instance. + /// + /// The object to use. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ComputeShaderDispatchDataLoader(ID3D12GraphicsCommandList* d3D12GraphicsCommandList) + { + this.d3D12GraphicsCommandList = d3D12GraphicsCommandList; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void LoadCapturedValues(ReadOnlySpan data) + { + this.d3D12GraphicsCommandList->SetComputeRoot32BitConstants(data); + } + + /// + public void LoadCapturedResources(ReadOnlySpan data) + { + ID3D12GraphicsCommandList* d3D12GraphicsCommandList = this.d3D12GraphicsCommandList; + ref ulong resourcesRef = ref MemoryMarshal.GetReference(data); + ref D3D12_GPU_DESCRIPTOR_HANDLE startRef = ref Unsafe.As(ref resourcesRef); + ref D3D12_GPU_DESCRIPTOR_HANDLE endRef = ref Unsafe.Add(ref startRef, data.Length); + uint offset = 1; + + while (Unsafe.IsAddressLessThan(ref startRef, ref endRef)) + { + d3D12GraphicsCommandList->SetComputeRootDescriptorTable(offset, startRef); + + startRef = ref Unsafe.Add(ref startRef, 1); + offset++; + } + } + } +} diff --git a/src/ComputeSharp/Shaders/Dispatching/PixelShaderDispatchDataLoader.cs b/src/ComputeSharp/Shaders/Dispatching/PixelShaderDispatchDataLoader.cs new file mode 100644 index 00000000..43fa5455 --- /dev/null +++ b/src/ComputeSharp/Shaders/Dispatching/PixelShaderDispatchDataLoader.cs @@ -0,0 +1,61 @@ +using System; +using System.Runtime.CompilerServices; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.__Internals; +using TerraFX.Interop; +using System.Runtime.InteropServices; + +#pragma warning disable CS0618 + +namespace ComputeSharp.Shaders.Dispatching +{ + /// + /// A data loader for pixel shaders. + /// + internal readonly unsafe struct PixelShaderDispatchDataLoader : IDispatchDataLoader + { + /// + /// The object in use. + /// + private readonly ID3D12GraphicsCommandList* d3D12GraphicsCommandList; + + /// + /// Creates a new instance. + /// + /// The object to use. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal PixelShaderDispatchDataLoader(ID3D12GraphicsCommandList* d3D12GraphicsCommandList) + { + this.d3D12GraphicsCommandList = d3D12GraphicsCommandList; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void LoadCapturedValues(ReadOnlySpan data) + { + this.d3D12GraphicsCommandList->SetComputeRoot32BitConstants(data); + } + + /// + public void LoadCapturedResources(ReadOnlySpan data) + { + ID3D12GraphicsCommandList* d3D12GraphicsCommandList = this.d3D12GraphicsCommandList; + ref ulong resourcesRef = ref MemoryMarshal.GetReference(data); + ref D3D12_GPU_DESCRIPTOR_HANDLE startRef = ref Unsafe.As(ref resourcesRef); + ref D3D12_GPU_DESCRIPTOR_HANDLE endRef = ref Unsafe.Add(ref startRef, data.Length); + uint offset = 2; + + // Skip the first target resource, as that is loaded explicitly by the shader runner using the + // target texture passed in by the user, which is not actually captured by the shader itself. + // The target root descriptor table index is therefore 2 in this case, as it needs to skip not + // only the this implicit texture to draw on, but also the constant buffer with capture values. + while (Unsafe.IsAddressLessThan(ref startRef, ref endRef)) + { + d3D12GraphicsCommandList->SetComputeRootDescriptorTable(offset, startRef); + + startRef = ref Unsafe.Add(ref startRef, 1); + offset++; + } + } + } +} diff --git a/src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs b/src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs new file mode 100644 index 00000000..29986b2c --- /dev/null +++ b/src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs @@ -0,0 +1,47 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.Shaders.Extensions; +using ComputeSharp.__Internals; +using Microsoft.Toolkit.Diagnostics; +using TerraFX.Interop; + +#pragma warning disable CS0618 + +namespace ComputeSharp.Shaders.Dispatching +{ + /// + /// A data loader for compute shaders. + /// + internal readonly unsafe struct ShaderDispatchMetadataLoader : IDispatchMetadataLoader + { + /// + /// The object in use. + /// + private readonly ID3D12Device* d3D12Device; + + /// + /// Creates a new instance. + /// + /// The object to use. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ShaderDispatchMetadataLoader(ID3D12Device* d3D12Device) + { + this.d3D12Device = d3D12Device; + } + + /// + public unsafe void LoadMetadataHandle(ReadOnlySpan serializedMetadata, ReadOnlySpan resourceDescriptors, out IntPtr result) + { + Guard.HasSizeEqualTo(serializedMetadata, 5, nameof(serializedMetadata)); + + fixed (IntPtr* p = &result) + { + *(ComPtr*)p = this.d3D12Device->CreateRootSignature( + MemoryMarshal.Read(serializedMetadata), + MemoryMarshal.Cast(resourceDescriptors), + MemoryMarshal.Read(serializedMetadata[4..])); + } + } + } +} diff --git a/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs b/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs index 3a83b4f0..4b8e7194 100644 --- a/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs +++ b/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs @@ -1,11 +1,13 @@ using System; using System.Runtime.CompilerServices; +using ComputeSharp.__Internals; using ComputeSharp.Core.Extensions; -using ComputeSharp.Shaders.Renderer; using ComputeSharp.Shaders.Translation; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; +#pragma warning disable CS0618 + namespace ComputeSharp.Interop { /// @@ -28,7 +30,7 @@ namespace ComputeSharp.Interop /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead. /// public static void GetShaderInfo(out ShaderInfo shaderInfo) - where T : struct, IComputeShader + where T : struct, IComputeShader, IShader { GetNonGenericShaderInfo(default(T), out shaderInfo); } @@ -45,7 +47,7 @@ namespace ComputeSharp.Interop /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead. /// public static unsafe void GetShaderInfo(in T shader, out ShaderInfo shaderInfo) - where T : struct, IComputeShader + where T : struct, IComputeShader, IShader { GetNonGenericShaderInfo(in shader, out shaderInfo); } @@ -66,7 +68,7 @@ namespace ComputeSharp.Interop /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead. /// public static void GetShaderInfo(out ShaderInfo shaderInfo) - where T : struct, IPixelShader + where T : struct, IPixelShader, IShader where TPixel : unmanaged { GetNonGenericShaderInfo(default(T), out shaderInfo); @@ -85,7 +87,7 @@ namespace ComputeSharp.Interop /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead. /// public static unsafe void GetShaderInfo(in T shader, out ShaderInfo shaderInfo) - where T : struct, IPixelShader + where T : struct, IPixelShader, IShader where TPixel : unmanaged { GetNonGenericShaderInfo(in shader, out shaderInfo); @@ -98,15 +100,16 @@ namespace ComputeSharp.Interop /// The input shader to retrieve info for. /// The resulting instance. private static unsafe void GetNonGenericShaderInfo(in T shader, out ShaderInfo shaderInfo) - where T : struct + where T : struct, IShader { - ShaderLoader shaderLoader = ShaderLoader.Load(in shader); - - using var shaderSource = HlslShaderRenderer.Render(1, 1, 1, shaderLoader); + shader.BuildHlslString(out ArrayPoolStringBuilder shaderSource, 1, 1, 1); using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(shaderSource.WrittenSpan); + shaderSource.Dispose(); + using ComPtr dxcUtils = default; + Guid dxcLibraryClsid = FX.CLSID_DxcLibrary; FX.DxcCreateInstance(&dxcLibraryClsid, FX.__uuidof(), dxcUtils.GetVoidAddressOf()).Assert(); diff --git a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs deleted file mode 100644 index 754709ee..00000000 --- a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs +++ /dev/null @@ -1,356 +0,0 @@ -using System; -using System.Buffers; -using System.Diagnostics; -using System.Diagnostics.Contracts; -using System.Runtime.CompilerServices; -using ComputeSharp.Shaders.Renderer.Models; -using ComputeSharp.Shaders.Translation; - -namespace ComputeSharp.Shaders.Renderer -{ - /// - /// A type that renders an HLSL template from the previously loaded shader data. - /// - internal static class HlslShaderRenderer - { - /// - /// Renders a new HLSL shader source with the given parameters. - /// - /// The number of threads in each thread group for the X axis. - /// The number of threads in each thread group for the Y axis. - /// The number of threads in each thread group for the Z axis. - /// The input instance with the shader information. - /// The source code for the new HLSL shader. - [Pure] - public static ArrayPoolStringBuilder Render(int threadsX, int threadsY, int threadsZ, IShaderLoader info) - { - var builder = ArrayPoolStringBuilder.Create(); - - // Header - builder.AppendLine("// ================================================"); - builder.AppendLine("// AUTO GENERATED"); - builder.AppendLine("// ================================================"); - builder.AppendLine("// This shader was created by ComputeSharp."); - builder.AppendLine("// See: https://github.com/Sergio0694/ComputeSharp."); - - // Group size constants - builder.AppendLine(); - builder.Append("#define __GroupSize__get_X "); - builder.AppendLine(threadsX.ToString()); - builder.Append("#define __GroupSize__get_Y "); - builder.AppendLine(threadsY.ToString()); - builder.Append("#define __GroupSize__get_Z "); - builder.AppendLine(threadsZ.ToString()); - - // Define declarations - foreach (var define in info.DefinesInfo) - { - builder.Append("#define "); - builder.Append(define.Key); - builder.Append(' '); - builder.AppendLine(define.Value); - } - - // Static fields - if (info.StaticFields.Count > 0) - { - builder.AppendLine(); - - foreach (var constant in info.StaticFields) - { - builder.Append(constant.Value.TypeDeclaration); - builder.Append(' '); - builder.Append(constant.Key); - - if (constant.Value.Assignment is string assignment) - { - builder.Append(" = "); - builder.Append(assignment); - } - - builder.AppendLine(";"); - } - } - - // Declared types - foreach (var type in info.DeclaredTypes) - { - builder.AppendLine(); - builder.AppendLine(type); - } - - // Captured variables - builder.AppendLine(); - builder.AppendLine("cbuffer _ : register(b0)"); - builder.AppendLine('{'); - builder.AppendLine(" uint __x;"); - builder.AppendLine(" uint __y;"); - - if (info.IsComputeShader) - { - builder.AppendLine(" uint __z;"); - } - - foreach (var local in info.FieldsInfo) - { - builder.Append(" "); - builder.Append(local.FieldType); - builder.Append(' '); - builder.Append(local.FieldName); - builder.AppendLine(';'); - } - - builder.AppendLine('}'); - - // Resources - foreach (var resource in info.HlslResourceInfo) - { - builder.AppendLine(); - - switch (resource) - { - // Constant buffer go to cbuffer fields with a dummy local - case HlslResourceInfo.Constant _: - builder.Append("cbuffer _"); - builder.Append(resource.FieldName); - builder.Append(" : register(b"); - builder.Append(resource.RegisterIndex.ToString()); - builder.AppendLine(')'); - builder.AppendLine('{'); - builder.Append(" "); - builder.Append(resource.FieldType); - builder.Append(' '); - builder.Append(resource.FieldName); - builder.AppendLine("[2];"); - builder.AppendLine('}'); - break; - - // Structured buffer have the same syntax but different id - case HlslResourceInfo.ReadOnly _: - char registerId = 't'; - goto StructuredBuffer; - case HlslResourceInfo.ReadWrite _: - registerId = 'u'; - StructuredBuffer: - builder.Append(resource.FieldType); - builder.Append(' '); - builder.Append(resource.FieldName); - builder.Append(" : register("); - builder.Append(registerId); - builder.Append(resource.RegisterIndex.ToString()); - builder.AppendLine(");"); - break; - - // Texture samplers - case HlslResourceInfo.Sampler _: - builder.Append(resource.FieldType); - builder.Append(' '); - builder.Append(resource.FieldName); - builder.Append(" : register("); - builder.Append('s'); - builder.Append(resource.RegisterIndex.ToString()); - builder.AppendLine(");"); - break; - } - } - - // Shared buffers - foreach (var buffer in info.SharedBuffers) - { - builder.AppendLine(); - builder.Append("groupshared "); - builder.Append(buffer.Value.Type); - builder.Append(' '); - builder.Append(buffer.Key); - builder.Append('['); - - if (buffer.Value.Count is int count) builder.Append(count.ToString()); - else builder.Append((threadsX * threadsY * threadsZ).ToString()); - - builder.AppendLine("];"); - } - - // Forward declarations - foreach (var declaration in info.ForwardDeclarations) - { - builder.AppendLine(); - builder.AppendLine(declaration); - } - - // Captured methods - foreach (var function in info.MethodsInfo) - { - builder.AppendLine(); - builder.AppendLine(function); - } - - // Entry point - builder.AppendLine(); - builder.AppendLine("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); - builder.AppendLine(info.EntryPoint); - - return builder; - } - - /// - /// A helper type that implements a pooled buffer writer for values. - /// - [DebuggerTypeProxy(typeof(DebugView))] - public ref struct ArrayPoolStringBuilder - { - /// - /// The underlying array. - /// - private char[] array; - - /// - /// The starting offset within . - /// - private int index; - - /// - /// Creates a new instance ready to use. - /// - /// A new instance with default values. - [Pure] - public static ArrayPoolStringBuilder Create() - { - ArrayPoolStringBuilder builder; - - builder.array = ArrayPool.Shared.Rent(1024); - builder.index = 0; - - return builder; - } - - /// - public ReadOnlySpan WrittenSpan - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => new(this.array, 0, this.index); - } - - /// - /// Appends the input sequence of characters to the current buffer. - /// - /// The input characters to write. - public void Append(string value) - { - EnsureCapacity(value.Length); - - value.AsSpan().CopyTo(this.array.AsSpan(this.index)); - - this.index += value.Length; - } - - /// - /// Appends a character to the current buffer. - /// - public void Append(char character) - { - EnsureCapacity(1); - - this.array[this.index++] = character; - } - - /// - /// Appends the input sequence of characters to the current buffer, with a trailing new line. - /// - /// The input characters to write. - public void AppendLine(string value) - { - EnsureCapacity(value.Length + 1); - - value.AsSpan().CopyTo(this.array.AsSpan(this.index)); - - this.index += value.Length; - - this.array[this.index++] = '\n'; - } - - /// - /// Appends a character and a new line to the current buffer. - /// - public void AppendLine(char character) - { - EnsureCapacity(2); - - this.array[this.index++] = character; - this.array[this.index++] = '\n'; - } - - /// - /// Appends a new line to the current buffer. - /// - public void AppendLine() - { - EnsureCapacity(1); - - this.array[this.index++] = '\n'; - } - - /// - /// Ensures that has enough free space to contain a given number of new items. - /// - /// The minimum number of items to ensure space for in . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void EnsureCapacity(int requestedSize) - { - if (requestedSize > this.array.Length - this.index) - { - ResizeBuffer(requestedSize); - } - } - - /// - /// Resizes to ensure it can fit the specified number of new items. - /// - /// The minimum number of items to ensure space for in . - [MethodImpl(MethodImplOptions.NoInlining)] - private void ResizeBuffer(int sizeHint) - { - int minimumSize = this.index + sizeHint; - - // Rent a new array with the specified size, and copy as many items from the current array - // as possible to the new array. This mirrors the behavior of the Array.Resize API from - // the BCL: if the new size is greater than the length of the current array, copy all the - // items from the original array into the new one. Otherwise, copy as many items as possible, - // until the new array is completely filled, and ignore the remaining items in the first array. - char[] newArray = ArrayPool.Shared.Rent(minimumSize); - int itemsToCopy = Math.Min(this.array.Length, minimumSize); - - Array.Copy(this.array, 0, newArray, 0, itemsToCopy); - - ArrayPool.Shared.Return(array); - - this.array = newArray; - } - - /// - public void Dispose() - { - ArrayPool.Shared.Return(this.array); - } - - /// - /// A debug proxy used for displaying debug info. - /// - internal sealed class DebugView - { - /// - /// Initializes a new instance of the class with the specified parameters. - /// - /// The input instance to display. - public DebugView(ArrayPoolStringBuilder builder) - { - Text = builder.WrittenSpan.ToString(); - } - - /// - /// Gets the text to display for the current instance. - /// - public string Text { get; } - } - } - } -} diff --git a/src/ComputeSharp/Shaders/Renderer/Models/HlslFieldInfo.cs b/src/ComputeSharp/Shaders/Renderer/Models/HlslFieldInfo.cs deleted file mode 100644 index baf1f12c..00000000 --- a/src/ComputeSharp/Shaders/Renderer/Models/HlslFieldInfo.cs +++ /dev/null @@ -1,11 +0,0 @@ -#pragma warning disable CS1572, CS1573 - -namespace ComputeSharp.Shaders.Renderer.Models -{ - /// - /// A model that contains info on a shader field. - /// - /// The type of the current field in the HLSL shader. - /// The name to use for the current field. - internal record CapturedFieldInfo(string FieldType, string FieldName); -} diff --git a/src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs b/src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs deleted file mode 100644 index af71a082..00000000 --- a/src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace ComputeSharp.Shaders.Renderer.Models -{ - /// - /// A model that contains info on a shader resource field. - /// - /// The type of the current field in the HLSL shader. - /// The name to use for the current field. - /// The register index to bind the resource to. - internal abstract record HlslResourceInfo(string FieldType, string FieldName, int RegisterIndex) - : CapturedFieldInfo(FieldType, FieldName) - { - /// - /// A model that represents a captured constant buffer in a shader. - /// - /// - public sealed record Constant(string FieldType, string FieldName, int RegisterIndex) - : HlslResourceInfo(FieldType, FieldName, RegisterIndex); - - /// - /// A model that represents a captured readonly typed resource in a shader. - /// Maps to either or . - /// - /// - public sealed record ReadOnly(string FieldType, string FieldName, int RegisterIndex) - : HlslResourceInfo(FieldType, FieldName, RegisterIndex); - - /// - /// A model that represents a captured writeable buffer in a shader. - /// Maps to either or . - /// - /// - public sealed record ReadWrite(string FieldType, string FieldName, int RegisterIndex) - : HlslResourceInfo(FieldType, FieldName, RegisterIndex); - - /// - /// A model that represents a captured sampler in a shader. - /// This resource type doesn't have a mapping to a public API. - /// - /// - public sealed record Sampler(string FieldType, string FieldName, int RegisterIndex) - : HlslResourceInfo(FieldType, FieldName, RegisterIndex); - } -} diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs index 220b2c2c..9fdcf83f 100644 --- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs @@ -2,11 +2,9 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Commands; -using ComputeSharp.Graphics.Extensions; +using ComputeSharp.Shaders.Dispatching; using ComputeSharp.Shaders.Extensions; -using ComputeSharp.Shaders.Renderer; using ComputeSharp.Shaders.Translation; -using ComputeSharp.Shaders.Translation.Interop; using ComputeSharp.Shaders.Translation.Models; using ComputeSharp.__Internals; using Microsoft.Toolkit.Diagnostics; @@ -23,12 +21,12 @@ namespace ComputeSharp.Shaders /// /// The type of compute shader to run. internal static class ShaderRunner - where T : struct + where T : struct, IShader { /// /// The mapping used to cache and reuse compiled shaders. /// - private static readonly Dictionary> ShadersCache = new(); + private static readonly Dictionary ShadersCache = new(); /// /// Compiles and runs the input shader on a target instance, with the specified parameters. @@ -120,7 +118,6 @@ namespace ComputeSharp.Shaders Guard.IsBetweenOrEqualTo(threadsZ, 1, 64, nameof(threadsZ)); Guard.IsLessThanOrEqualTo(threadsX * threadsY * threadsZ, 1024, "threadsXYZ"); - // Calculate the dispatch values int groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1), groupsY = Math.DivRem(y, threadsY, out int modY) + (modY == 0 ? 0 : 1), @@ -130,15 +127,13 @@ namespace ComputeSharp.Shaders Guard.IsBetweenOrEqualTo(groupsY, 1, FX.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); Guard.IsBetweenOrEqualTo(groupsZ, 1, FX.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); - // Create the shader key - ShaderKey key = new(ShaderHashCodeProvider.GetHashCode(in shader), threadsX, threadsY, threadsZ); - CachedShader shaderData; + ShaderKey key = new(shader.GetDispatchId(), threadsX, threadsY, threadsZ); PipelineData? pipelineData; lock (ShadersCache) { // Get or preload the shader - if (!ShadersCache.TryGetValue(key, out shaderData)) + if (!ShadersCache.TryGetValue(key, out CachedShader? shaderData)) { LoadShader(threadsX, threadsY, threadsZ, in shader, out shaderData); @@ -153,27 +148,15 @@ namespace ComputeSharp.Shaders } } - // Create the commands list and set the pipeline state using CommandList commandList = new(device, D3D12_COMMAND_LIST_TYPE_COMPUTE); commandList.D3D12GraphicsCommandList->SetComputeRootSignature(pipelineData.D3D12RootSignature); commandList.D3D12GraphicsCommandList->SetPipelineState(pipelineData.D3D12PipelineState); - // Extract the dispatch data for the shader invocation - using DispatchData dispatchData = shaderData.Loader.GetDispatchData(device, in shader, x, y, z); + ComputeShaderDispatchDataLoader dataLoader = new(commandList.D3D12GraphicsCommandList); - // Initialize the loop targets and the captured values - commandList.D3D12GraphicsCommandList->SetComputeRoot32BitConstants(dispatchData.Variables); + shader.LoadDispatchData(ref dataLoader, device, x, y, z); - ReadOnlySpan resources = dispatchData.Resources; - - for (int i = 0; i < resources.Length; i++) - { - // Load the captured buffers - commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable((uint)i + 1, resources[i]); - } - - // Dispatch and wait for completion commandList.D3D12GraphicsCommandList->Dispatch((uint)groupsX, (uint)groupsY, (uint)groupsZ); commandList.ExecuteAndWaitForCompletion(); } @@ -202,14 +185,13 @@ namespace ComputeSharp.Shaders Guard.IsBetweenOrEqualTo(groupsY, 1, FX.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); // Create the shader key - ShaderKey key = new(ShaderHashCodeProvider.GetHashCode(in shader), threadsX, threadsY, 1); - CachedShader shaderData; + ShaderKey key = new(shader.GetDispatchId(), threadsX, threadsY, 1); PipelineData? pipelineData; lock (ShadersCache) { // Get or preload the shader - if (!ShadersCache.TryGetValue(key, out shaderData)) + if (!ShadersCache.TryGetValue(key, out CachedShader? shaderData)) { LoadShader(threadsX, threadsY, 1, in shader, out shaderData); @@ -230,29 +212,15 @@ namespace ComputeSharp.Shaders commandList.D3D12GraphicsCommandList->SetComputeRootSignature(pipelineData.D3D12RootSignature); commandList.D3D12GraphicsCommandList->SetPipelineState(pipelineData.D3D12PipelineState); - // Extract the dispatch data for the shader invocation - using DispatchData dispatchData = shaderData.Loader.GetDispatchData(device, in shader, x, y, 1); + PixelShaderDispatchDataLoader dataLoader = new(commandList.D3D12GraphicsCommandList); - // Initialize the loop targets and the captured values - commandList.D3D12GraphicsCommandList->SetComputeRoot32BitConstants(dispatchData.Variables); + shader.LoadDispatchData(ref dataLoader, device, x, y, 1); // Load the implicit output texture commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable( 1, ((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetGpuDescriptorHandle(device)); - // Skip the last (missing) resource, as the internal counter is exceeding the number of explicit - // resources that the shader has actually captured (since it includes the target texture too). - // For the same reason, the target root descriptor table index is also offset by 2, as it needs - // to skip not only the constant buffer with capture values, but the implicit texture as well. - ReadOnlySpan resources = dispatchData.Resources[..^1]; - - for (int i = 0; i < resources.Length; i++) - { - // Load the captured buffers - commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable((uint)i + 2, resources[i]); - } - // Dispatch and wait for completion commandList.D3D12GraphicsCommandList->Dispatch((uint)groupsX, (uint)groupsY, 1); commandList.ExecuteAndWaitForCompletion(); @@ -265,34 +233,35 @@ namespace ComputeSharp.Shaders /// The number of threads in each thread group for the Y axis. /// The number of threads in each thread group for the Z axis. /// The input instance representing the compute shader to run. - /// The instance to return with the cached shader data. + /// The instance to return with the cached shader data. [MethodImpl(MethodImplOptions.NoInlining)] - private static void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader shaderData) + private static unsafe void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader shaderData) { - // Load the input shader - ShaderLoader shaderLoader = ShaderLoader.Load(in shader); + shader.BuildHlslString(out ArrayPoolStringBuilder builder, threadsX, threadsY, threadsZ); - // Render the loaded shader - using var shaderSource = HlslShaderRenderer.Render(threadsX, threadsY, threadsZ, shaderLoader); + using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(builder.WrittenSpan); - // Compile the loaded shader to HLSL bytecode - IDxcBlobObject shaderBytecode = new(ShaderCompiler.Instance.CompileShader(shaderSource.WrittenSpan)); + builder.Dispose(); - // Get the cached shader data - shaderData = new CachedShader(shaderLoader, shaderBytecode); + shaderData = new CachedShader(dxcBlobBytecode.Get()); } /// /// Creates and caches a instance for a given shader. /// /// The to use to run the shader. - /// The instance with the data on the loaded shader. + /// The instance with the data on the loaded shader. /// The resulting instance to use to run the shader. [MethodImpl(MethodImplOptions.NoInlining)] - private static unsafe void CreatePipelineData(GraphicsDevice device, in CachedShader shaderData, out PipelineData pipelineData) + private static unsafe void CreatePipelineData(GraphicsDevice device, CachedShader shaderData, out PipelineData pipelineData) { - using ComPtr d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12Root32BitConstantsCount, shaderData.Loader.D3D12DescriptorRanges1, shaderData.Loader.IsStaticSamplerUsed); - using ComPtr d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), shaderData.Bytecode.D3D12ShaderBytecode); + using ComPtr d3D12RootSignature = default; + + ShaderDispatchMetadataLoader metadataLoader = new(device.D3D12Device); + + default(T).LoadDispatchMetadata(ref metadataLoader, out *(IntPtr*)&d3D12RootSignature); + + using ComPtr d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), shaderData.D3D12ShaderBytecode); pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get()); diff --git a/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs b/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs deleted file mode 100644 index ccbdc33f..00000000 --- a/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System.Collections.Generic; -using ComputeSharp.Shaders.Renderer.Models; - -namespace ComputeSharp.Shaders.Translation -{ - /// - /// A responsible for loading and processing shaders of any type. - /// - internal interface IShaderLoader - { - /// - /// Gets the generated source code for the method in the current shader. - /// - string EntryPoint { get; } - - /// - /// Gets whether or not the current shader is a compute shader (and not a pixel shader). - /// - bool IsComputeShader { get; } - - /// - /// Gets the collection of items for the shader fields. - /// - IReadOnlyList HlslResourceInfo { get; } - - /// - /// Gets the collection of items for the shader fields. - /// - IReadOnlyList FieldsInfo { get; } - - /// - /// Gets the forward declarations for static methods. - /// - IReadOnlyCollection ForwardDeclarations { get; } - - /// - /// Gets the collection of methods to be used in the shader. - /// - IReadOnlyCollection MethodsInfo { get; } - - /// - /// Gets the collection of define declarations to be added to the shader. - /// - IReadOnlyDictionary DefinesInfo { get; } - - /// - /// Gets the collection of discovered static fields. - /// - IReadOnlyDictionary StaticFields { get; } - - /// - /// Gets the collection of declared types for the shader. - /// - IReadOnlyCollection DeclaredTypes { get; } - - /// - /// Gets the collection of discovered group shared buffers. - /// - IReadOnlyDictionary SharedBuffers { get; } - } -} diff --git a/src/ComputeSharp/Shaders/Translation/Interop/IDxcBlobObject.cs b/src/ComputeSharp/Shaders/Translation/Interop/IDxcBlobObject.cs deleted file mode 100644 index eb3cd02e..00000000 --- a/src/ComputeSharp/Shaders/Translation/Interop/IDxcBlobObject.cs +++ /dev/null @@ -1,38 +0,0 @@ -using ComputeSharp.Interop; -using TerraFX.Interop; - -namespace ComputeSharp.Shaders.Translation.Interop -{ - /// - /// An object wrapping an instance. - /// - internal sealed unsafe class IDxcBlobObject : NativeObject - { - /// - /// The instance currently in use. - /// - private ComPtr dxcBlob; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The instance to wrap. - public IDxcBlobObject(ComPtr dxcBlob) - { - this.dxcBlob = dxcBlob; - } - - /// - /// Gets a raw pointer to the instance in use. - /// - public D3D12_SHADER_BYTECODE D3D12ShaderBytecode => new((ID3DBlob*)this.dxcBlob.Get()); - - /// - protected override bool OnDispose() - { - this.dxcBlob.Dispose(); - - return true; - } - } -} diff --git a/src/ComputeSharp/Shaders/Translation/Mappings/HlslKnownTypes.cs b/src/ComputeSharp/Shaders/Translation/Mappings/HlslKnownTypes.cs deleted file mode 100644 index 90aae996..00000000 --- a/src/ComputeSharp/Shaders/Translation/Mappings/HlslKnownTypes.cs +++ /dev/null @@ -1,147 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Numerics; - -namespace ComputeSharp.Shaders.Mappings -{ - /// - /// A that contains and maps known HLSL type names to common .NET types. - /// - internal static class HlslKnownTypes - { - /// - /// The set of HLSL vector types. - /// - private static HashSet HlslMappedVectorTypes { get; } = new(new[] - { - typeof(Bool2), typeof(Bool3), typeof(Bool4), - typeof(Int2), typeof(Int3), typeof(Int4), - typeof(UInt2), typeof(UInt3), typeof(UInt4), - typeof(Float2), typeof(Float3), typeof(Float4), - typeof(Double2), typeof(Double3), typeof(Double4) - }); - - /// - /// The set of HLSL matrix types. - /// - private static HashSet HlslMappedMatrixTypes { get; } = new(new[] - { - typeof(Bool1x1), typeof(Bool1x2), typeof(Bool1x3), typeof(Bool1x4), - typeof(Bool2x1), typeof(Bool2x2), typeof(Bool2x3), typeof(Bool2x4), - typeof(Bool3x1), typeof(Bool3x2), typeof(Bool3x3), typeof(Bool3x4), - typeof(Bool4x1), typeof(Bool4x2), typeof(Bool4x3), typeof(Bool4x4), - typeof(Int1x1), typeof(Int1x2), typeof(Int1x3), typeof(Int1x4), - typeof(Int2x1), typeof(Int2x2), typeof(Int2x3), typeof(Int2x4), - typeof(Int3x1), typeof(Int3x2), typeof(Int3x3), typeof(Int3x4), - typeof(Int4x1), typeof(Int4x2), typeof(Int4x3), typeof(Int4x4), - typeof(UInt1x1), typeof(UInt1x2), typeof(UInt1x3), typeof(UInt1x4), - typeof(UInt2x1), typeof(UInt2x2), typeof(UInt2x3), typeof(UInt2x4), - typeof(UInt3x1), typeof(UInt3x2), typeof(UInt3x3), typeof(UInt3x4), - typeof(UInt4x1), typeof(UInt4x2), typeof(UInt4x3), typeof(UInt4x4), - typeof(Float1x1), typeof(Float1x2), typeof(Float1x3), typeof(Float1x4), - typeof(Float2x1), typeof(Float2x2), typeof(Float2x3), typeof(Float2x4), - typeof(Float3x1), typeof(Float3x2), typeof(Float3x3), typeof(Float3x4), - typeof(Float4x1), typeof(Float4x2), typeof(Float4x3), typeof(Float4x4), - typeof(Double1x1), typeof(Double1x2), typeof(Double1x3), typeof(Double1x4), - typeof(Double2x1), typeof(Double2x2), typeof(Double2x3), typeof(Double2x4), - typeof(Double3x1), typeof(Double3x2), typeof(Double3x3), typeof(Double3x4), - typeof(Double4x1), typeof(Double4x2), typeof(Double4x3), typeof(Double4x4) - }); - - /// - /// Checks whether or not the input type is a known scalar type. - /// - /// The input instance to check. - /// A indicating whether the input is in fact a known HLSL scalar type. - [Pure] - public static bool IsKnownScalarType(Type type) => type == typeof(bool) || - type == typeof(Bool) || - type == typeof(int) || - type == typeof(uint) || - type == typeof(float) || - type == typeof(double); - - /// - /// Checks whether or not the input type is a known vector type. - /// - /// The input instance to check. - /// A indicating whether the input is in fact a known HLSL vector type. - [Pure] - public static bool IsKnownVectorType(Type type) => HlslMappedVectorTypes.Contains(type) || - type == typeof(Vector2) || - type == typeof(Vector3) || - type == typeof(Vector4); - - /// - /// Checks whether or not the input type is a known matrix type. - /// - /// The input instance to check. - /// A indicating whether the input is in fact a known HLSL matrix type. - [Pure] - public static bool IsKnownMatrixType(Type type) => HlslMappedMatrixTypes.Contains(type); - - /// - /// Checks whether or not the input type is a known buffer type. - /// - /// The input instance to check. - /// A indicating whether the input is in fact a known buffer type. - [Pure] - public static bool IsKnownBufferType(Type type) => IsConstantBufferType(type) || - IsReadOnlyResourceType(type) || - IsReadWriteResourceType(type); - - /// - /// Checks whether or not the input type is a value. - /// - /// The input instance to check. - /// A indicating whether the input is in fact a instance. - [Pure] - public static bool IsConstantBufferType(Type type) => type.IsGenericType && - type.GetGenericTypeDefinition() == typeof(ConstantBuffer<>); - - /// - /// Checks whether or not the input type is a known readonly resource type (buffer or texture). - /// - /// The input instance to check. - /// A indicating whether the input is a readonly resource type. - [Pure] - public static bool IsReadOnlyResourceType(Type type) - { - if (!type.IsGenericType) return false; - - Type genericType = type.GetGenericTypeDefinition(); - - return - genericType == typeof(ReadOnlyBuffer<>) || - genericType == typeof(ReadOnlyTexture2D<>) || - genericType == typeof(ReadOnlyTexture2D<,>) || - genericType == typeof(ReadOnlyTexture3D<>) || - genericType == typeof(ReadOnlyTexture3D<,>) || - genericType == typeof(IReadOnlyTexture2D<>) || - genericType == typeof(IReadOnlyTexture3D<>); - } - - /// - /// Checks whether or not the input type is a known writeable resource type (buffer or texture). - /// - /// The input instance to check. - /// A indicating whether the input is a writeable resource type. - [Pure] - public static bool IsReadWriteResourceType(Type type) - { - if (!type.IsGenericType) return false; - - Type genericType = type.GetGenericTypeDefinition(); - - return - genericType == typeof(ReadWriteBuffer<>) || - genericType == typeof(ReadWriteTexture2D<>) || - genericType == typeof(ReadWriteTexture2D<,>) || - genericType == typeof(ReadWriteTexture3D<>) || - genericType == typeof(ReadWriteTexture3D<,>) || - genericType == typeof(IReadWriteTexture2D<>) || - genericType == typeof(IReadWriteTexture3D<>); ; - } - } -} diff --git a/src/ComputeSharp/Shaders/Translation/Models/CachedShader.cs b/src/ComputeSharp/Shaders/Translation/Models/CachedShader.cs new file mode 100644 index 00000000..8bf11804 --- /dev/null +++ b/src/ComputeSharp/Shaders/Translation/Models/CachedShader.cs @@ -0,0 +1,45 @@ +using System.Runtime.CompilerServices; +using ComputeSharp.Graphics.Commands; +using ComputeSharp.Interop; +using TerraFX.Interop; + +namespace ComputeSharp.Shaders.Translation.Models +{ + /// + /// A class that contains info on a cached shader. + /// + internal sealed unsafe class CachedShader : NativeObject + { + /// + /// The instance currently in use. + /// + private ComPtr dxcBlobBytecode; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The bytecode instance to wrap. + public CachedShader(IDxcBlob* dxcBlobBytecode) + { + this.dxcBlobBytecode = new ComPtr(dxcBlobBytecode); + } + + /// + /// Gets the map of cached instances for each GPU in use. + /// + public ConditionalWeakTable CachedPipelines { get; } = new(); + + /// + /// Gets a raw pointer to the instance in use. + /// + public D3D12_SHADER_BYTECODE D3D12ShaderBytecode => new((ID3DBlob*)this.dxcBlobBytecode.Get()); + + /// + protected override bool OnDispose() + { + this.dxcBlobBytecode.Dispose(); + + return true; + } + } +} diff --git a/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs b/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs deleted file mode 100644 index 39558fb1..00000000 --- a/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.Runtime.CompilerServices; -using ComputeSharp.Graphics.Commands; -using ComputeSharp.Shaders.Translation.Interop; - -namespace ComputeSharp.Shaders.Translation.Models -{ - /// - /// A that contains info on a cached shader. - /// - /// The type of compute shader in use. - internal readonly struct CachedShader - where T : struct - { - /// - /// The instance with the shader metadata. - /// - public readonly ShaderLoader Loader; - - /// - /// The compiled shader bytecode. - /// - public readonly IDxcBlobObject Bytecode; - - /// - /// The map of cached instances for each GPU in use. - /// - public readonly ConditionalWeakTable CachedPipelines; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The instance with the shader metadata. - /// The compiled shader bytecode. - public CachedShader(ShaderLoader loader, IDxcBlobObject bytecode) - { - Loader = loader; - Bytecode = bytecode; - CachedPipelines = new(); - } - } -} diff --git a/src/ComputeSharp/Shaders/Translation/Models/DispatchData.cs b/src/ComputeSharp/Shaders/Translation/Models/DispatchData.cs deleted file mode 100644 index 249a3279..00000000 --- a/src/ComputeSharp/Shaders/Translation/Models/DispatchData.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System; -using System.Buffers; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using TerraFX.Interop; - -namespace ComputeSharp.Shaders.Translation.Models -{ - /// - /// A that contains all the captured data to dispatch a shader. - /// - internal readonly ref struct DispatchData - { - /// - /// The array (actually values) with the captured buffers. - /// - private readonly ulong[] resourcesArray; - - /// - /// The number of values in . - /// - private readonly int resourcesCount; - - /// - /// The array with all the captured variables, with proper padding. - /// - private readonly byte[] variablesArray; - - /// - /// The actual size in bytes to use from . - /// - private readonly int variablesByteSize; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The array with the captured buffers. - /// The number of instances in . - /// The array with all the captured variables, with proper padding. - /// The actual size in bytes to use from . - public DispatchData(ulong[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize) - { - this.resourcesArray = resourcesArray; - this.variablesArray = variablesArray; - this.resourcesCount = resourcesCount; - this.variablesByteSize = variablesByteSize; - } - - /// - /// Gets a with all the captured buffers. - /// - public ReadOnlySpan Resources - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray); - ref D3D12_GPU_DESCRIPTOR_HANDLE r1 = ref Unsafe.As(ref r0); - - return MemoryMarshal.CreateReadOnlySpan(ref r1, this.resourcesCount); - } - } - - /// - /// Gets a with the padded data representing all the captured variables. - /// - public unsafe ReadOnlySpan Variables - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - ref byte r0 = ref MemoryMarshal.GetArrayDataReference(this.variablesArray); - ref uint r1 = ref Unsafe.As(ref r0); - int length = (int)((uint)this.variablesByteSize / sizeof(uint)); - - return MemoryMarshal.CreateReadOnlySpan(ref r1, length); - } - } - - /// - public void Dispose() - { - ArrayPool.Shared.Return(this.resourcesArray); - ArrayPool.Shared.Return(this.variablesArray); - } - } -} diff --git a/src/ComputeSharp/Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp/Shaders/Translation/ShaderHashCodeProvider.cs deleted file mode 100644 index 2304eba6..00000000 --- a/src/ComputeSharp/Shaders/Translation/ShaderHashCodeProvider.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; -using System.Diagnostics.Contracts; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace ComputeSharp.Shaders.Translation -{ - /// - /// A that handles the cache system for the generated shaders. - /// - internal static class ShaderHashCodeProvider - { - /// - /// A type containing static info for a given shader type . - /// - /// The type of compute shader currently in use. - private static class TypeInfo - where T : struct - { - /// - /// The id of the compute shader type in use. - /// - public static readonly int Id; - - /// - /// The optional instance, if needed. - /// - public static readonly Hasher? Hasher; - - /// - /// Initializes the static members of the type. - /// - static TypeInfo() - { - Id = HashCode.Combine(typeof(T)); - - // Get the generated hasher, if one if present - if (typeof(T).Assembly.GetType("ComputeSharp.__Internals.HashCodeProvider") is Type type && - type.GetMethod("CombineHash", new[] { typeof(int), typeof(T).MakeByRefType() }) is MethodInfo method) - { - Hasher = method.CreateDelegate>(); - } - } - } - - /// - /// Gets a unique hashcode for the input compute shader instance. - /// - /// The type of compute shader currently in use. - /// The input instance representing the shader to run. - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int GetHashCode(in T shader) - where T : struct - { - int hash = TypeInfo.Id; - - Hasher? hasher = TypeInfo.Hasher; - - if (hasher != null) hash = hasher(hash, in shader); - - return hash; - } - - /// - /// A that represents an aggregate hash function for a given instance. - /// - /// The type of compute shader currently in use. - /// The initial hash value. - /// The compute shader instance to use to compute the final hash value. - /// The final hash value for the input closure. - private delegate int Hasher(int hash, in T shader) - where T : struct; - } -} diff --git a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.DispatchData.cs b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.DispatchData.cs deleted file mode 100644 index 95c80c19..00000000 --- a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.DispatchData.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Buffers; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using ComputeSharp.__Internals; -using ComputeSharp.Shaders.Translation.Models; -using TerraFX.Interop; - -#pragma warning disable CS0419, CS0618 - -namespace ComputeSharp.Shaders.Translation -{ - /// - internal sealed partial class ShaderLoader - { - /// - /// A that loads all the captured members from a shader instance. - /// - /// The to use to run the shader. - /// The shader instance to load the data from. - /// - /// A reference to the buffer with all the captured instances. - /// This is just represented as a reference, to avoid exposing the type publicly. - /// - /// A reference to the buffer to use to store all the captured value types. - /// The returned value indicates the total number of written bytes into . - private delegate int DispatchDataLoader(GraphicsDevice device, in T shader, ref ulong r0, ref byte r1); - - /// - /// The number of captured graphics resources (buffers). - /// - private int totalResourceCount; - - /// - /// The cached instance to load dispatch data before execution. - /// - private DispatchDataLoader? dispatchDataLoader; - - /// - /// The of instances mapping the captured variables in the current shader. - /// - private readonly List capturedFields = new(); - - /// - /// Gets a new instance with all the captured data for the current shader instance. - /// - /// The to use to run the shader. - /// The input instance representing the compute shader to run. - /// The number of iterations to run on the X axis. - /// The number of iterations to run on the Y axis. - /// The number of iterations to run on the Z axis. - [Pure] - public DispatchData GetDispatchData(GraphicsDevice device, in T shader, int x, int y, int z) - { - // Resources and variables buffers - ulong[] resources = ArrayPool.Shared.Rent(this.totalResourceCount); - byte[] variables = ArrayPool.Shared.Rent(256); - - ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(resources); - ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables); - - // Set the x, y and (optionally) z counters - Unsafe.As(ref r1) = x; - Unsafe.Add(ref Unsafe.As(ref r1), 1) = y; - - if (IsComputeShader) - { - Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; - } - - // Invoke the dynamic method to extract the captured data - int totalVariablesByteSize = this.dispatchDataLoader!(device, in shader, ref r0, ref r1); - - return new(resources, this.totalResourceCount, variables, totalVariablesByteSize); - } - - /// - /// Initializes the instance that loads the dispatch data for the current shader type. - /// - private void InitializeDispatchDataLoader() - { - // Get the generated data loader - Type[] argumentTypes = new[] { typeof(GraphicsDevice), typeof(T).MakeByRefType(), typeof(ulong).MakeByRefType(), typeof(byte).MakeByRefType() }; - Type type = typeof(T).Assembly.GetType("ComputeSharp.__Internals.DispatchDataLoader")!; - MethodInfo method = type.GetMethod("LoadDispatchData", argumentTypes)!; - - // Extract the computed count of 32 bit root constants to load - D3D12Root32BitConstantsCount = ((ComputeRoot32BitConstantsAttribute)method.ReturnTypeCustomAttributes.GetCustomAttributes(false)[0]).Count; - - // Create a delegate from the generated shader data loader - this.dispatchDataLoader = method.CreateDelegate(); - } - } -} diff --git a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs deleted file mode 100644 index a13586e1..00000000 --- a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs +++ /dev/null @@ -1,295 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Reflection; -using ComputeSharp.__Internals; -using ComputeSharp.Shaders.Mappings; -using ComputeSharp.Shaders.Renderer.Models; -using Microsoft.Toolkit.Diagnostics; -using TerraFX.Interop; -using static TerraFX.Interop.D3D12_DESCRIPTOR_RANGE_TYPE; - -#pragma warning disable CS0419, CS0618, CS8618 - -namespace ComputeSharp.Shaders.Translation -{ - /// - /// A responsible for loading and processing shaders of a given type. - /// - /// The type of compute shader currently in use. - internal sealed partial class ShaderLoader : IShaderLoader - where T : struct - { - /// - /// The associated instance for the current shader type. - /// - private static readonly IComputeShaderSourceAttribute Attribute = IComputeShaderSourceAttribute.GetForType(); - - /// - /// The number of constant buffers to define in the shader. - /// - /// - /// This starts at 1 as there's always an initial constant buffer before user-defined ones, containing - /// the captured scalar and vector values as well as the iteration ranges for the shader dispatch. - /// - private uint constantBuffersCount = 1; - - /// - /// The number of readonly buffers to define in the shader. - /// - private uint readOnlyBuffersCount; - - /// - /// The number of read write buffers to define in the shader. - /// - private uint readWriteBuffersCount; - - /// - /// The number of samplers to define in the shader. - /// - private uint samplersCount; - - /// - /// The array of items that are required to load the captured values. - /// - private D3D12_DESCRIPTOR_RANGE1[] d3D12DescriptorRanges1; - - /// - /// The with the items for the shader fields. - /// - private readonly List hlslResourceInfo = new(); - - /// - /// The with the items for the shader fields. - /// - private readonly List fieldsInfo = new(); - - /// - /// The with the collected methods for the shader. - /// - private readonly List methodsInfo = new(); - - /// - /// The with the discovered define declarations for the shader. - /// - private readonly Dictionary definesInfo = new(); - - /// - /// The with the collected declared types for the shader. - /// - private readonly List declaredTypes = new(); - - /// - /// Creates a new instance. - /// - private ShaderLoader() - { - } - - /// - /// Gets the number of 32 bit constants in the root signature for the shader. - /// - public int D3D12Root32BitConstantsCount { get; private set; } - - /// - /// Gets a with the loaded items for the shader. - /// - public ReadOnlySpan D3D12DescriptorRanges1 - { - get => this.d3D12DescriptorRanges1; - } - - /// - public string EntryPoint { get; private set; } - - /// - public bool IsComputeShader { get; private set; } - - /// - /// Gets whether or not the current shader requires access to a static sampler. - /// - public bool IsStaticSamplerUsed { get; private set; } - - /// - public IReadOnlyList HlslResourceInfo => this.hlslResourceInfo; - - /// - public IReadOnlyList FieldsInfo => this.fieldsInfo; - - /// - public IReadOnlyCollection ForwardDeclarations { get; private set; } - - /// - public IReadOnlyCollection MethodsInfo => this.methodsInfo; - - /// - public IReadOnlyDictionary DefinesInfo => this.definesInfo; - - /// - public IReadOnlyCollection DeclaredTypes => this.declaredTypes; - - /// - public IReadOnlyDictionary StaticFields { get; private set; } - - /// - public IReadOnlyDictionary SharedBuffers { get; private set; } - - /// - /// Loads and processes an input shadeer. - /// - /// The instance to use to build the shader. - /// A new instance representing the input shader. - [Pure] - public static ShaderLoader Load(in T shader) - { - ShaderLoader @this = new(); - - @this.LoadMethodMetadata(); - - // Reading members through reflection requires an object parameter, so here we're just boxing - // the input shader once to avoid allocating it multiple times while processing the shader. - @this.d3D12DescriptorRanges1 = @this.LoadFieldsInfo(shader); - - @this.InitializeDispatchDataLoader(); - - return @this; - } - - /// - /// Loads the metadata info for the current shader. - /// - private void LoadMethodMetadata() - { - ForwardDeclarations = Attribute.ForwardDeclarations; - EntryPoint = Attribute.ExecuteMethod; - StaticFields = Attribute.StaticFields; - SharedBuffers = Attribute.SharedBuffers; - - this.declaredTypes.AddRange(Attribute.Types); - this.methodsInfo.AddRange(Attribute.Methods); - - foreach (var pair in Attribute.Defines) - { - this.definesInfo.Add(pair.Key, pair.Value); - } - } - - /// - /// Loads the fields info for the current shader being loaded. - /// - /// The boxed instance to use to build the shader. - /// The array of items that are required to load the captured values. - private D3D12_DESCRIPTOR_RANGE1[] LoadFieldsInfo(object shader) - { - IReadOnlyList shaderFields = typeof(T).GetFields( - BindingFlags.Instance | - BindingFlags.Public | - BindingFlags.NonPublic).ToArray(); - - List d3D12DescriptorRanges1 = new(); - - // Add the implicit texture descriptor if the shader is a pixel shader - foreach (Type interfaceType in typeof(T).GetInterfaces()) - { - if (interfaceType.IsGenericType && - interfaceType.GetGenericTypeDefinition() == typeof(IPixelShader<>)) - { - d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount)); - - (string hlslType, string hlslName) = Attribute.ImplicitTextureField!.Value; - - this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); - this.totalResourceCount++; - - break; - } - } - - // Set the current shader type - IsComputeShader = d3D12DescriptorRanges1.Count == 0; - - // Ensure the shader has a valid number of captured resources - if (shaderFields.Count == 0 && d3D12DescriptorRanges1.Count == 0) - { - ThrowHelper.ThrowInvalidOperationException("The shader body must contain at least one field"); - } - - // Add the implicit sampler descriptor if necessary - if (Attribute.ImplicitSamplerField is not null) - { - (string hlslType, string hlslName) = Attribute.ImplicitSamplerField!.Value; - - this.hlslResourceInfo.Add(new HlslResourceInfo.Sampler(hlslType, hlslName, (int)this.samplersCount++)); - - IsStaticSamplerUsed = true; - } - - // Inspect the captured fields - foreach (FieldInfo fieldInfo in shaderFields) - { - LoadFieldInfo(shader, fieldInfo, d3D12DescriptorRanges1); - } - - return d3D12DescriptorRanges1.ToArray(); - } - - /// - /// Loads a specified and adds it to the shader model. - /// - /// The boxed instance to use to build the shader. - /// The target to load. - /// The list of discovered values. - private void LoadFieldInfo(object shader, FieldInfo fieldInfo, List d3D12DescriptorRanges1) - { - Type fieldType = fieldInfo.FieldType; - (string hlslName, string hlslType) = Attribute.Fields[fieldInfo.Name]; - - if (HlslKnownTypes.IsConstantBufferType(fieldType)) - { - d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount)); - - this.capturedFields.Add(fieldInfo); - this.hlslResourceInfo.Add(new HlslResourceInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++)); - this.totalResourceCount++; - } - else if (HlslKnownTypes.IsReadOnlyResourceType(fieldType)) - { - d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, this.readOnlyBuffersCount)); - - this.capturedFields.Add(fieldInfo); - this.hlslResourceInfo.Add(new HlslResourceInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++)); - this.totalResourceCount++; - } - else if (HlslKnownTypes.IsReadWriteResourceType(fieldType)) - { - d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount)); - - this.capturedFields.Add(fieldInfo); - this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); - this.totalResourceCount++; - } - else if (fieldInfo.GetValue(shader) is Delegate func) - { - Guard.IsTrue(func.Method.IsStatic, fieldInfo.Name, "Captured delegates must be pointing to static methods"); - - // Captured static delegates with a return type - var methodSource = ShaderMethodSourceAttribute.GetForDelegate(func); - - this.declaredTypes.AddRange(methodSource.Types); - this.methodsInfo.Add(methodSource.GetMappedInvokeMethod(hlslName)); - this.methodsInfo.AddRange(methodSource.Methods); - - foreach (var pair in methodSource.Constants) - { - this.definesInfo[pair.Key] = pair.Value; - } - } - else - { - this.capturedFields.Add(fieldInfo); - this.fieldsInfo.Add(new CapturedFieldInfo(hlslType, hlslName)); - } - } - } -} diff --git a/src/ComputeSharp/Shaders/Translation/__Internals/ArrayPoolStringBuilder.cs b/src/ComputeSharp/Shaders/Translation/__Internals/ArrayPoolStringBuilder.cs new file mode 100644 index 00000000..b5f1069e --- /dev/null +++ b/src/ComputeSharp/Shaders/Translation/__Internals/ArrayPoolStringBuilder.cs @@ -0,0 +1,137 @@ +using System; +using System.Buffers; +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; + +namespace ComputeSharp.__Internals +{ + /// + /// A helper type that implements a pooled buffer writer for values. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This type is not intended to be used directly by user code")] + [DebuggerTypeProxy(typeof(DebugView))] + public ref struct ArrayPoolStringBuilder + { + /// + /// The underlying array. + /// + private char[] array; + + /// + /// The starting offset within . + /// + private int index; + + /// + /// Creates a new instance ready to use. + /// + /// The size hint for the internal buffer to allocate. + /// A new instance with default values. + [Pure] + public static ArrayPoolStringBuilder Create(int sizeHint) + { + ArrayPoolStringBuilder builder; + + builder.array = ArrayPool.Shared.Rent(sizeHint); + builder.index = 0; + + return builder; + } + + /// + public ReadOnlySpan WrittenSpan + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new(this.array, 0, this.index); + } + + /// + /// Appends the input sequence of characters to the current buffer. + /// + /// The input characters to write. + public void Append(string value) + { + EnsureCapacity(value.Length); + + value.AsSpan().CopyTo(this.array.AsSpan(this.index)); + + this.index += value.Length; + } + + /// + /// Appends the text representation of the input value to the current buffer. + /// + /// The input value to write. + public void Append(int value) + { + // TODO: switch to ISpanFormattable on .NET 6 + Append(value.ToString()); + } + + /// + /// Ensures that has enough free space to contain a given number of new items. + /// + /// The minimum number of items to ensure space for in . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void EnsureCapacity(int requestedSize) + { + if (requestedSize > this.array.Length - this.index) + { + ResizeBuffer(requestedSize); + } + } + + /// + /// Resizes to ensure it can fit the specified number of new items. + /// + /// The minimum number of items to ensure space for in . + [MethodImpl(MethodImplOptions.NoInlining)] + private void ResizeBuffer(int sizeHint) + { + int minimumSize = this.index + sizeHint; + + // Rent a new array with the specified size, and copy as many items from the current array + // as possible to the new array. This mirrors the behavior of the Array.Resize API from + // the BCL: if the new size is greater than the length of the current array, copy all the + // items from the original array into the new one. Otherwise, copy as many items as possible, + // until the new array is completely filled, and ignore the remaining items in the first array. + char[] newArray = ArrayPool.Shared.Rent(minimumSize); + int itemsToCopy = Math.Min(this.array.Length, minimumSize); + + Array.Copy(this.array, 0, newArray, 0, itemsToCopy); + + ArrayPool.Shared.Return(array); + + this.array = newArray; + } + + /// + public void Dispose() + { + ArrayPool.Shared.Return(this.array); + } + + /// + /// A debug proxy used for displaying debug info. + /// + internal sealed class DebugView + { + /// + /// Initializes a new instance of the class with the specified parameters. + /// + /// The input instance to display. + public DebugView(ArrayPoolStringBuilder builder) + { + Text = builder.WrittenSpan.ToString(); + } + + /// + /// Gets the text to display for the current instance. + /// + public string Text { get; } + } + } +} diff --git a/tests/ComputeSharp.Tests.Internals/Helpers/DebugDispatchDataLoader.cs b/tests/ComputeSharp.Tests.Internals/Helpers/DebugDispatchDataLoader.cs new file mode 100644 index 00000000..60d1ded4 --- /dev/null +++ b/tests/ComputeSharp.Tests.Internals/Helpers/DebugDispatchDataLoader.cs @@ -0,0 +1,56 @@ +using System; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; +using ComputeSharp.__Internals; + +#pragma warning disable CS0618 + +namespace ComputeSharp.Tests.Internals.Helpers +{ + /// + /// A debug data loader for generic shaders. + /// + internal readonly unsafe struct DebugDispatchDataLoader : IDispatchDataLoader + { + /// + /// The backing, mutable data for and . + /// + private readonly StrongBox<(uint[] Values, ulong[] Resources)> data; + + /// + /// Gets the captured values. + /// + public uint[] Values => this.data.Value.Values; + + /// + /// Gets the captured resources. + /// + public ulong[] Resources => this.data.Value.Resources; + + /// + /// Creates a new instance. + /// + /// A new instance to use. + [Pure] + public static DebugDispatchDataLoader Create() + { + DebugDispatchDataLoader @this = default; + + Unsafe.AsRef(in @this.data) = new StrongBox<(uint[], ulong[])>((Array.Empty(), Array.Empty())); + + return @this; + } + + /// + public void LoadCapturedValues(ReadOnlySpan data) + { + this.data.Value.Values = data.ToArray(); + } + + /// + public void LoadCapturedResources(ReadOnlySpan data) + { + this.data.Value.Resources = data.ToArray(); + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs index f6b11808..6626ef2e 100644 --- a/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs +++ b/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs @@ -1,4 +1,4 @@ -using ComputeSharp.__Internals; +using ComputeSharp.Tests.Internals.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; #pragma warning disable CS0618 @@ -22,16 +22,19 @@ namespace ComputeSharp.Tests.Internals [TestMethod] public unsafe void CapturedResource() { - ulong* p0 = stackalloc ulong[128]; - byte* p1 = stackalloc byte[256]; - using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(16); - int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, new CapturedResourceShader(buffer), ref *p0, ref *p1); + DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); - Assert.AreEqual(12, size); + new CapturedResourceShader(buffer).LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333); - Assert.AreEqual(p0[0], buffer.D3D12GpuDescriptorHandle.ptr); + Assert.AreEqual(3, dataLoader.Values.Length); + Assert.AreEqual(1, dataLoader.Resources.Length); + + Assert.AreEqual(111, (int)dataLoader.Values[0]); + Assert.AreEqual(222, (int)dataLoader.Values[1]); + Assert.AreEqual(333, (int)dataLoader.Values[2]); + Assert.AreEqual(buffer.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]); } [AutoConstructor] @@ -51,22 +54,24 @@ namespace ComputeSharp.Tests.Internals [TestMethod] public unsafe void LoadMultipleResourcesAndPrimitives() { - ulong* p0 = stackalloc ulong[128]; - byte* p1 = stackalloc byte[256]; - using ReadWriteBuffer buffer0 = Gpu.Default.AllocateReadWriteBuffer(16); using ReadWriteBuffer buffer1 = Gpu.Default.AllocateReadWriteBuffer(16); - int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, new MultipleResourcesAndPrimitivesShader(buffer0, buffer1, 1, 22, 77), ref *p0, ref *p1); + DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); - Assert.AreEqual(24, size); + new MultipleResourcesAndPrimitivesShader(buffer0, buffer1, 1, 22, 77).LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333); - Assert.AreEqual(p0[0], buffer0.D3D12GpuDescriptorHandle.ptr); - Assert.AreEqual(p0[1], buffer1.D3D12GpuDescriptorHandle.ptr); + Assert.AreEqual(6, dataLoader.Values.Length); + Assert.AreEqual(2, dataLoader.Resources.Length); - Assert.AreEqual(1, *(int*)&p1[12]); - Assert.AreEqual(22, *(int*)&p1[16]); - Assert.AreEqual(77, *(int*)&p1[20]); + Assert.AreEqual(111, (int)dataLoader.Values[0]); + Assert.AreEqual(222, (int)dataLoader.Values[1]); + Assert.AreEqual(333, (int)dataLoader.Values[2]); + Assert.AreEqual(1, (int)dataLoader.Values[3]); + Assert.AreEqual(22, (int)dataLoader.Values[4]); + Assert.AreEqual(77, (int)dataLoader.Values[5]); + Assert.AreEqual(buffer0.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]); + Assert.AreEqual(buffer1.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[1]); } [AutoConstructor] @@ -88,28 +93,36 @@ namespace ComputeSharp.Tests.Internals [TestMethod] public unsafe void LoadScalarAndVectorTypes() { - ulong* p0 = stackalloc ulong[128]; - byte* p1 = stackalloc byte[256]; - using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(16); + DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); ScalarAndVectorTypesShader shader = new(buffer, new(55, 44, 888), 22, 77, new(3.14, 6.28), 42, 9999); - int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, in shader, ref *p0, ref *p1); + shader.LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333); - Assert.AreEqual(72, size); + Assert.AreEqual(18, dataLoader.Values.Length); + Assert.AreEqual(1, dataLoader.Resources.Length); - Assert.AreEqual(p0[0], buffer.D3D12GpuDescriptorHandle.ptr); + Assert.AreEqual(111, (int)dataLoader.Values[0]); + Assert.AreEqual(222, (int)dataLoader.Values[1]); + Assert.AreEqual(333, (int)dataLoader.Values[2]); - Assert.AreEqual(55, *(float*)&p1[16]); - Assert.AreEqual(44, *(float*)&p1[20]); - Assert.AreEqual(888, *(float*)&p1[24]); - Assert.AreEqual(22, *(int*)&p1[28]); - Assert.AreEqual(77, *(int*)&p1[32]); - Assert.AreEqual(3.14, *(double*)&p1[48]); - Assert.AreEqual(6.28, *(double*)&p1[56]); - Assert.AreEqual(42, *(int*)&p1[64]); - Assert.AreEqual(9999, *(int*)&p1[68]); + Assert.AreEqual(buffer.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]); + + fixed (void* p0 = &dataLoader.Values[0]) + { + byte* p1 = (byte*)p0; + + Assert.AreEqual(55, *(float*)&p1[16]); + Assert.AreEqual(44, *(float*)&p1[20]); + Assert.AreEqual(888, *(float*)&p1[24]); + Assert.AreEqual(22, *(int*)&p1[28]); + Assert.AreEqual(77, *(int*)&p1[32]); + Assert.AreEqual(3.14, *(double*)&p1[48]); + Assert.AreEqual(6.28, *(double*)&p1[56]); + Assert.AreEqual(42, *(int*)&p1[64]); + Assert.AreEqual(9999, *(int*)&p1[68]); + } } [AutoConstructor] @@ -133,11 +146,9 @@ namespace ComputeSharp.Tests.Internals [TestMethod] public unsafe void LoadScalarVectorAndMatrixTypes() { - ulong* p0 = stackalloc ulong[128]; - byte* p1 = stackalloc byte[256]; - using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(16); + DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); ScalarVectorAndMatrixTypesShader shader = new( buffer, f2x3: new(55, 44, 888, 111, 222, 333), @@ -149,32 +160,42 @@ namespace ComputeSharp.Tests.Internals i2x2: new(11, 22, 33, 44), d: 9999); - int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, in shader, ref *p0, ref *p1); + shader.LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333); - Assert.AreEqual(124, size); + Assert.AreEqual(31, dataLoader.Values.Length); + Assert.AreEqual(1, dataLoader.Resources.Length); - Assert.AreEqual(p0[0], buffer.D3D12GpuDescriptorHandle.ptr); + Assert.AreEqual(111, (int)dataLoader.Values[0]); + Assert.AreEqual(222, (int)dataLoader.Values[1]); + Assert.AreEqual(333, (int)dataLoader.Values[2]); - Assert.AreEqual(55, *(float*)&p1[16]); - Assert.AreEqual(44, *(float*)&p1[20]); - Assert.AreEqual(888, *(float*)&p1[24]); - Assert.AreEqual(111, *(float*)&p1[32]); - Assert.AreEqual(222, *(float*)&p1[36]); - Assert.AreEqual(333, *(float*)&p1[40]); - Assert.AreEqual(22, *(int*)&p1[44]); - Assert.AreEqual(1, *(int*)&p1[48]); - Assert.AreEqual(2, *(int*)&p1[52]); - Assert.AreEqual(3, *(int*)&p1[56]); - Assert.AreEqual(3.14, *(double*)&p1[64]); - Assert.AreEqual(6.28, *(double*)&p1[72]); - Assert.AreEqual(42, *(int*)&p1[80]); - Assert.AreEqual(111, *(int*)&p1[84]); - Assert.AreEqual(222, *(int*)&p1[88]); - Assert.AreEqual(11, *(int*)&p1[96]); - Assert.AreEqual(22, *(int*)&p1[100]); - Assert.AreEqual(33, *(int*)&p1[112]); - Assert.AreEqual(44, *(int*)&p1[116]); - Assert.AreEqual(9999, *(int*)&p1[120]); + Assert.AreEqual(buffer.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]); + + fixed (void* p0 = &dataLoader.Values[0]) + { + byte* p1 = (byte*)p0; + + Assert.AreEqual(55, *(float*)&p1[16]); + Assert.AreEqual(44, *(float*)&p1[20]); + Assert.AreEqual(888, *(float*)&p1[24]); + Assert.AreEqual(111, *(float*)&p1[32]); + Assert.AreEqual(222, *(float*)&p1[36]); + Assert.AreEqual(333, *(float*)&p1[40]); + Assert.AreEqual(22, *(int*)&p1[44]); + Assert.AreEqual(1, *(int*)&p1[48]); + Assert.AreEqual(2, *(int*)&p1[52]); + Assert.AreEqual(3, *(int*)&p1[56]); + Assert.AreEqual(3.14, *(double*)&p1[64]); + Assert.AreEqual(6.28, *(double*)&p1[72]); + Assert.AreEqual(42, *(int*)&p1[80]); + Assert.AreEqual(111, *(int*)&p1[84]); + Assert.AreEqual(222, *(int*)&p1[88]); + Assert.AreEqual(11, *(int*)&p1[96]); + Assert.AreEqual(22, *(int*)&p1[100]); + Assert.AreEqual(33, *(int*)&p1[112]); + Assert.AreEqual(44, *(int*)&p1[116]); + Assert.AreEqual(9999, *(int*)&p1[120]); + } } [AutoConstructor] @@ -204,11 +225,9 @@ namespace ComputeSharp.Tests.Internals [TestMethod] public unsafe void LoadFlatCustomTypeShader() { - ulong* p0 = stackalloc ulong[128]; - byte* p1 = stackalloc byte[256]; - using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(16); + DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); FlatCustomTypeShader shader = new( buffer, new SimpleTypes( @@ -221,32 +240,42 @@ namespace ComputeSharp.Tests.Internals i2x2: new(11, 22, 33, 44), d: 9999)); - int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, in shader, ref *p0, ref *p1); + shader.LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333); - Assert.AreEqual(124, size); + Assert.AreEqual(31, dataLoader.Values.Length); + Assert.AreEqual(1, dataLoader.Resources.Length); - Assert.AreEqual(p0[0], buffer.D3D12GpuDescriptorHandle.ptr); + Assert.AreEqual(111, (int)dataLoader.Values[0]); + Assert.AreEqual(222, (int)dataLoader.Values[1]); + Assert.AreEqual(333, (int)dataLoader.Values[2]); - Assert.AreEqual(55, *(float*)&p1[16]); - Assert.AreEqual(44, *(float*)&p1[20]); - Assert.AreEqual(888, *(float*)&p1[24]); - Assert.AreEqual(111, *(float*)&p1[32]); - Assert.AreEqual(222, *(float*)&p1[36]); - Assert.AreEqual(333, *(float*)&p1[40]); - Assert.AreEqual(22, *(int*)&p1[44]); - Assert.AreEqual(1, *(int*)&p1[48]); - Assert.AreEqual(2, *(int*)&p1[52]); - Assert.AreEqual(3, *(int*)&p1[56]); - Assert.AreEqual(3.14, *(double*)&p1[64]); - Assert.AreEqual(6.28, *(double*)&p1[72]); - Assert.AreEqual(42, *(int*)&p1[80]); - Assert.AreEqual(111, *(int*)&p1[84]); - Assert.AreEqual(222, *(int*)&p1[88]); - Assert.AreEqual(11, *(int*)&p1[96]); - Assert.AreEqual(22, *(int*)&p1[100]); - Assert.AreEqual(33, *(int*)&p1[112]); - Assert.AreEqual(44, *(int*)&p1[116]); - Assert.AreEqual(9999, *(int*)&p1[120]); + Assert.AreEqual(buffer.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]); + + fixed (void* p0 = &dataLoader.Values[0]) + { + byte* p1 = (byte*)p0; + + Assert.AreEqual(55, *(float*)&p1[16]); + Assert.AreEqual(44, *(float*)&p1[20]); + Assert.AreEqual(888, *(float*)&p1[24]); + Assert.AreEqual(111, *(float*)&p1[32]); + Assert.AreEqual(222, *(float*)&p1[36]); + Assert.AreEqual(333, *(float*)&p1[40]); + Assert.AreEqual(22, *(int*)&p1[44]); + Assert.AreEqual(1, *(int*)&p1[48]); + Assert.AreEqual(2, *(int*)&p1[52]); + Assert.AreEqual(3, *(int*)&p1[56]); + Assert.AreEqual(3.14, *(double*)&p1[64]); + Assert.AreEqual(6.28, *(double*)&p1[72]); + Assert.AreEqual(42, *(int*)&p1[80]); + Assert.AreEqual(111, *(int*)&p1[84]); + Assert.AreEqual(222, *(int*)&p1[88]); + Assert.AreEqual(11, *(int*)&p1[96]); + Assert.AreEqual(22, *(int*)&p1[100]); + Assert.AreEqual(33, *(int*)&p1[112]); + Assert.AreEqual(44, *(int*)&p1[116]); + Assert.AreEqual(9999, *(int*)&p1[120]); + } } [AutoConstructor] @@ -288,11 +317,9 @@ namespace ComputeSharp.Tests.Internals [TestMethod] public unsafe void LoadNestedCustomTypes() { - ulong* p0 = stackalloc ulong[128]; - byte* p1 = stackalloc byte[256]; - using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(16); + DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); NestedCustomTypesShader shader = new( buffer, new CustomType1( @@ -317,45 +344,104 @@ namespace ComputeSharp.Tests.Internals a: 888888, b: new(333.3f, 444.4f)))); - int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, in shader, ref *p0, ref *p1); + shader.LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333); - Assert.AreEqual(188, size); + Assert.AreEqual(47, dataLoader.Values.Length); + Assert.AreEqual(1, dataLoader.Resources.Length); - Assert.AreEqual(p0[0], buffer.D3D12GpuDescriptorHandle.ptr); + Assert.AreEqual(111, (int)dataLoader.Values[0]); + Assert.AreEqual(222, (int)dataLoader.Values[1]); + Assert.AreEqual(333, (int)dataLoader.Values[2]); - Assert.AreEqual(3.14f, *(float*)&p1[16]); - Assert.AreEqual(6.28f, *(float*)&p1[20]); - Assert.AreEqual(123.4f, *(float*)&p1[24]); - Assert.AreEqual(55, *(float*)&p1[32]); - Assert.AreEqual(44, *(float*)&p1[36]); - Assert.AreEqual(888, *(float*)&p1[40]); - Assert.AreEqual(111, *(float*)&p1[48]); - Assert.AreEqual(222, *(float*)&p1[52]); - Assert.AreEqual(333, *(float*)&p1[56]); - Assert.AreEqual(22, *(int*)&p1[60]); - Assert.AreEqual(1, *(int*)&p1[64]); - Assert.AreEqual(2, *(int*)&p1[68]); - Assert.AreEqual(3, *(int*)&p1[72]); - Assert.AreEqual(3.14, *(double*)&p1[80]); - Assert.AreEqual(6.28, *(double*)&p1[88]); - Assert.AreEqual(42, *(int*)&p1[96]); - Assert.AreEqual(111, *(int*)&p1[100]); - Assert.AreEqual(222, *(int*)&p1[104]); - Assert.AreEqual(11, *(int*)&p1[112]); - Assert.AreEqual(22, *(int*)&p1[116]); - Assert.AreEqual(33, *(int*)&p1[128]); - Assert.AreEqual(44, *(int*)&p1[132]); - Assert.AreEqual(9999, *(int*)&p1[136]); - Assert.AreEqual(42, *(int*)&p1[140]); - Assert.AreEqual(1234567, *(int*)&p1[144]); - Assert.AreEqual(44.4f, *(float*)&p1[148]); - Assert.AreEqual(55.5f, *(float*)&p1[152]); - Assert.AreEqual(7654321, *(int*)&p1[160]); - Assert.AreEqual(111.1f, *(float*)&p1[164]); - Assert.AreEqual(222.2f, *(float*)&p1[168]); - Assert.AreEqual(888888, *(int*)&p1[176]); - Assert.AreEqual(333.3f, *(float*)&p1[180]); - Assert.AreEqual(444.4f, *(float*)&p1[184]); + Assert.AreEqual(buffer.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]); + + fixed (void* p0 = &dataLoader.Values[0]) + { + byte* p1 = (byte*)p0; + + Assert.AreEqual(3.14f, *(float*)&p1[16]); + Assert.AreEqual(6.28f, *(float*)&p1[20]); + Assert.AreEqual(123.4f, *(float*)&p1[24]); + Assert.AreEqual(55, *(float*)&p1[32]); + Assert.AreEqual(44, *(float*)&p1[36]); + Assert.AreEqual(888, *(float*)&p1[40]); + Assert.AreEqual(111, *(float*)&p1[48]); + Assert.AreEqual(222, *(float*)&p1[52]); + Assert.AreEqual(333, *(float*)&p1[56]); + Assert.AreEqual(22, *(int*)&p1[60]); + Assert.AreEqual(1, *(int*)&p1[64]); + Assert.AreEqual(2, *(int*)&p1[68]); + Assert.AreEqual(3, *(int*)&p1[72]); + Assert.AreEqual(3.14, *(double*)&p1[80]); + Assert.AreEqual(6.28, *(double*)&p1[88]); + Assert.AreEqual(42, *(int*)&p1[96]); + Assert.AreEqual(111, *(int*)&p1[100]); + Assert.AreEqual(222, *(int*)&p1[104]); + Assert.AreEqual(11, *(int*)&p1[112]); + Assert.AreEqual(22, *(int*)&p1[116]); + Assert.AreEqual(33, *(int*)&p1[128]); + Assert.AreEqual(44, *(int*)&p1[132]); + Assert.AreEqual(9999, *(int*)&p1[136]); + Assert.AreEqual(42, *(int*)&p1[140]); + Assert.AreEqual(1234567, *(int*)&p1[144]); + Assert.AreEqual(44.4f, *(float*)&p1[148]); + Assert.AreEqual(55.5f, *(float*)&p1[152]); + Assert.AreEqual(7654321, *(int*)&p1[160]); + Assert.AreEqual(111.1f, *(float*)&p1[164]); + Assert.AreEqual(222.2f, *(float*)&p1[168]); + Assert.AreEqual(888888, *(int*)&p1[176]); + Assert.AreEqual(333.3f, *(float*)&p1[180]); + Assert.AreEqual(444.4f, *(float*)&p1[184]); + } + } + + [AutoConstructor] + public partial struct AmbiguousNamesShader : IComputeShader + { + public ReadWriteBuffer a; + public ReadWriteBuffer b; + public ReadWriteBuffer c; + public ReadWriteBuffer x; + public ReadWriteBuffer y; + public ReadWriteBuffer z; + public int dataLoader; + public int device; + public int dummy; + + public void Execute() + { + } + } + + [TestMethod] + public unsafe void AmbiguousNames() + { + using ReadWriteBuffer a = Gpu.Default.AllocateReadWriteBuffer(16); + using ReadWriteBuffer b = Gpu.Default.AllocateReadWriteBuffer(16); + using ReadWriteBuffer c = Gpu.Default.AllocateReadWriteBuffer(16); + using ReadWriteBuffer x = Gpu.Default.AllocateReadWriteBuffer(16); + using ReadWriteBuffer y = Gpu.Default.AllocateReadWriteBuffer(16); + using ReadWriteBuffer z = Gpu.Default.AllocateReadWriteBuffer(16); + + DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); + + new AmbiguousNamesShader(a, b, c, x, y, z, 7777, 8888, 9999).LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333); + + Assert.AreEqual(6, dataLoader.Values.Length); + Assert.AreEqual(6, dataLoader.Resources.Length); + + Assert.AreEqual(111, (int)dataLoader.Values[0]); + Assert.AreEqual(222, (int)dataLoader.Values[1]); + Assert.AreEqual(333, (int)dataLoader.Values[2]); + Assert.AreEqual(7777, (int)dataLoader.Values[3]); + Assert.AreEqual(8888, (int)dataLoader.Values[4]); + Assert.AreEqual(9999, (int)dataLoader.Values[5]); + Assert.AreEqual(a.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]); + Assert.AreEqual(b.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[1]); + Assert.AreEqual(c.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[2]); + Assert.AreEqual(x.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[3]); + Assert.AreEqual(y.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[4]); + Assert.AreEqual(z.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[5]); } } } diff --git a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs index 241ce61b..5d8b7d59 100644 --- a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs +++ b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs @@ -1,14 +1,15 @@ using System; -using ComputeSharp.Shaders.Translation; using Microsoft.VisualStudio.TestTools.UnitTesting; +#pragma warning disable CS0618 + namespace ComputeSharp.Tests.Internals { [TestClass] [TestCategory("ShaderHashCode")] - public class ShaderHashCodeTests + public partial class ShaderHashCodeTests { - public struct Shader1 : IComputeShader + public partial struct Shader1 : IComputeShader { public float A; public ReadWriteBuffer B; @@ -28,19 +29,19 @@ namespace ComputeSharp.Tests.Internals Shader1 shader1 = new() { A = value, B = buffer }; int - hash1 = ShaderHashCodeProvider.GetHashCode(shader1), - hash2 = ShaderHashCodeProvider.GetHashCode(shader1); + hash1 = shader1.GetDispatchId(), + hash2 = shader1.GetDispatchId(); Assert.IsTrue(hash1 == hash2); Shader1 shader2 = new() { A = value, B = buffer }; - int hash3 = ShaderHashCodeProvider.GetHashCode(shader2); + int hash3 = shader2.GetDispatchId(); Assert.IsTrue(hash1 == hash3); } - public struct Shader2 : IComputeShader + public partial struct Shader2 : IComputeShader { public float A; public ReadWriteBuffer B; @@ -62,8 +63,8 @@ namespace ComputeSharp.Tests.Internals Shader2 shader1 = new() { A = 1, B = buffer, F = f }; int - hash1 = ShaderHashCodeProvider.GetHashCode(shader1), - hash2 = ShaderHashCodeProvider.GetHashCode(shader1); + hash1 = shader1.GetDispatchId(), + hash2 = shader1.GetDispatchId(); Assert.IsTrue(hash1 == hash2); @@ -71,7 +72,7 @@ namespace ComputeSharp.Tests.Internals Shader2 shader2 = new() { A = 1, B = buffer, F = f }; - int hash3 = ShaderHashCodeProvider.GetHashCode(shader2); + int hash3 = shader2.GetDispatchId(); Assert.IsFalse(hash1 == hash3); } diff --git a/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs index 1e46d676..92a4e006 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs @@ -75,7 +75,7 @@ namespace ComputeSharp.Tests.SourceGenerators /// The input source to process. /// The target index to check in the resulting output. /// The expected body to compare with the generated code. - private void VerifyGeneratedMethodLines(string source, int index, string expectedBody) + private static void VerifyGeneratedMethodLines(string source, int index, string expectedBody) where TGenerator : class, ISourceGenerator, new() { SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source); @@ -97,8 +97,8 @@ namespace ComputeSharp.Tests.SourceGenerators string outputBody = outputCompilation.SyntaxTrees.Skip(index + 1).First().ToString(); string[] - outputLines = outputBody.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), - expectedLines = expectedBody.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + outputLines = outputBody.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), + expectedLines = expectedBody.Replace("\r", "").Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); Assert.AreEqual(expectedLines.Length, outputLines.Length); diff --git a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs index 021a575f..55d7f58d 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs @@ -35,7 +35,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0001"); + VerifyGeneratedDiagnostics(source, "CMPS0001"); } [TestMethod] @@ -60,7 +60,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0001"); + VerifyGeneratedDiagnostics(source, "CMPS0001"); } [TestMethod] @@ -88,7 +88,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0002"); + VerifyGeneratedDiagnostics(source, "CMPS0002"); } [TestMethod] @@ -116,7 +116,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0003"); + VerifyGeneratedDiagnostics(source, "CMPS0003"); } [TestMethod] @@ -142,7 +142,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0004"); + VerifyGeneratedDiagnostics(source, "CMPS0004"); } [TestMethod] @@ -159,7 +159,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0005"); + VerifyGeneratedDiagnostics(source, "CMPS0005"); } [TestMethod] @@ -194,7 +194,7 @@ namespace ComputeSharp.Tests.SourceGenerators }} }}"; - VerifyGeneratedDiagnostics(source, diagnosticsId); + VerifyGeneratedDiagnostics(source, diagnosticsId); } [TestMethod] @@ -226,7 +226,7 @@ namespace ComputeSharp.Tests.SourceGenerators }} }}"; - VerifyGeneratedDiagnostics(source, diagnosticsId); + VerifyGeneratedDiagnostics(source, diagnosticsId); } [TestMethod] @@ -256,7 +256,7 @@ namespace ComputeSharp.Tests.SourceGenerators }} }}"; - VerifyGeneratedDiagnostics(source, "CMPS0006"); + VerifyGeneratedDiagnostics(source, "CMPS0006"); } [TestMethod] @@ -283,7 +283,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0010"); + VerifyGeneratedDiagnostics(source, "CMPS0010", "CMPS0031"); } [TestMethod] @@ -310,7 +310,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0010"); + VerifyGeneratedDiagnostics(source, "CMPS0010", "CMPS0031"); } [TestMethod] @@ -337,7 +337,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0011"); + VerifyGeneratedDiagnostics(source, "CMPS0011", "CMPS0031"); } [TestMethod] @@ -366,7 +366,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0012"); + VerifyGeneratedDiagnostics(source, "CMPS0012"); } [TestMethod] @@ -392,7 +392,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0012"); + VerifyGeneratedDiagnostics(source, "CMPS0012"); } [TestMethod] @@ -419,7 +419,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0012", "CMPS0013"); + VerifyGeneratedDiagnostics(source, "CMPS0012", "CMPS0013"); } [TestMethod] @@ -448,7 +448,7 @@ namespace ComputeSharp.Tests.SourceGenerators }} }}"; - VerifyGeneratedDiagnostics(source, "CMPS0014"); + VerifyGeneratedDiagnostics(source, "CMPS0014"); } [TestMethod] @@ -480,7 +480,7 @@ namespace ComputeSharp.Tests.SourceGenerators }} }}"; - VerifyGeneratedDiagnostics(source, "CMPS0015"); + VerifyGeneratedDiagnostics(source, "CMPS0015"); } [TestMethod] @@ -512,7 +512,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0016", "CMPS0032"); + VerifyGeneratedDiagnostics(source, "CMPS0016", "CMPS0032"); } [TestMethod] @@ -544,7 +544,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0017"); + VerifyGeneratedDiagnostics(source, "CMPS0017"); } [TestMethod] @@ -573,7 +573,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0018"); + VerifyGeneratedDiagnostics(source, "CMPS0018"); } [TestMethod] @@ -603,7 +603,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0019"); + VerifyGeneratedDiagnostics(source, "CMPS0019"); } [TestMethod] @@ -633,7 +633,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0020"); + VerifyGeneratedDiagnostics(source, "CMPS0020"); } [TestMethod] @@ -665,7 +665,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0021"); + VerifyGeneratedDiagnostics(source, "CMPS0021"); } [TestMethod] @@ -695,7 +695,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0022"); + VerifyGeneratedDiagnostics(source, "CMPS0022"); } [TestMethod] @@ -727,7 +727,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0023"); + VerifyGeneratedDiagnostics(source, "CMPS0023"); } [TestMethod] @@ -754,7 +754,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0024"); + VerifyGeneratedDiagnostics(source, "CMPS0024"); } [TestMethod] @@ -781,7 +781,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0032", "CMPS0025"); + VerifyGeneratedDiagnostics(source, "CMPS0032", "CMPS0025"); } [TestMethod] @@ -808,7 +808,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0026"); + VerifyGeneratedDiagnostics(source, "CMPS0026"); } [TestMethod] @@ -840,7 +840,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0027"); + VerifyGeneratedDiagnostics(source, "CMPS0027"); } [TestMethod] @@ -867,7 +867,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0028"); + VerifyGeneratedDiagnostics(source, "CMPS0028"); } [TestMethod] @@ -894,7 +894,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0029"); + VerifyGeneratedDiagnostics(source, "CMPS0029", "CMPS0031"); } [TestMethod] @@ -923,7 +923,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0029"); + VerifyGeneratedDiagnostics(source, "CMPS0029", "CMPS0031"); } [TestMethod] @@ -956,7 +956,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0030"); + VerifyGeneratedDiagnostics(source, "CMPS0030"); } [TestMethod] @@ -983,7 +983,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0031"); + VerifyGeneratedDiagnostics(source, "CMPS0031"); } [TestMethod] @@ -1010,7 +1010,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0032"); + VerifyGeneratedDiagnostics(source, "CMPS0032"); } [TestMethod] @@ -1037,7 +1037,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0033"); + VerifyGeneratedDiagnostics(source, "CMPS0033"); } [TestMethod] @@ -1066,7 +1066,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0034"); + VerifyGeneratedDiagnostics(source, "CMPS0034"); } [TestMethod] @@ -1095,7 +1095,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0035"); + VerifyGeneratedDiagnostics(source, "CMPS0035"); } [TestMethod] @@ -1124,7 +1124,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0035"); + VerifyGeneratedDiagnostics(source, "CMPS0035"); } [TestMethod] @@ -1151,7 +1151,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0036"); + VerifyGeneratedDiagnostics(source, "CMPS0036"); } [TestMethod] @@ -1192,7 +1192,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0042"); + VerifyGeneratedDiagnostics(source, "CMPS0042"); } [TestMethod] @@ -1220,7 +1220,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0043"); + VerifyGeneratedDiagnostics(source, "CMPS0043"); } [TestMethod] @@ -1248,7 +1248,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0045"); + VerifyGeneratedDiagnostics(source, "CMPS0045"); } [TestMethod] @@ -1279,7 +1279,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0045"); + VerifyGeneratedDiagnostics(source, "CMPS0045"); } [TestMethod] @@ -1307,7 +1307,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0045"); + VerifyGeneratedDiagnostics(source, "CMPS0045"); } [TestMethod] @@ -1335,7 +1335,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0045"); + VerifyGeneratedDiagnostics(source, "CMPS0045"); } [TestMethod] @@ -1367,7 +1367,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0046"); + VerifyGeneratedDiagnostics(source, "CMPS0046"); } [TestMethod] @@ -1392,7 +1392,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0047"); + VerifyGeneratedDiagnostics(source, "CMPS0047"); } /// @@ -1402,7 +1402,7 @@ namespace ComputeSharp.Tests.SourceGenerators /// The input source to process. /// The target index to check in the resulting output. /// The expected body to compare with the generated code. - private void VerifyGeneratedDiagnostics(string source, params string[] diagnosticsIds) + private static void VerifyGeneratedDiagnostics(string source, params string[] diagnosticsIds) where TGenerator : class, ISourceGenerator, new() { SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source); diff --git a/tests/ComputeSharp.Tests/MetaprogrammingTests.cs b/tests/ComputeSharp.Tests/MetaprogrammingTests.cs new file mode 100644 index 00000000..70bb9d22 --- /dev/null +++ b/tests/ComputeSharp.Tests/MetaprogrammingTests.cs @@ -0,0 +1,240 @@ +using System; +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#pragma warning disable IDE0062 + +namespace ComputeSharp.Tests +{ + [TestClass] + [TestCategory("Metaprogramming")] + public partial class MetaprogrammingTests + { + [AutoConstructor] + internal readonly partial struct ActivationWithDelegateShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + public readonly Func activation; + + public void Execute() + { + buffer[ThreadIds.X] = activation(ThreadIds.X); + } + } + + public static class Activations + { + [ShaderMethod] + public static int Square(int x) => x * x; + + [ShaderMethod] + public static int AddOne(int x) => x + 1; + + // Missing attribute + public static int Identity(int x) => x; + + [ShaderMethod] + public static int FunctionWithConstants(int x) => (int)(x + FourAndAHalf); + + [ShaderMethod] + public static Position FunctionWithTypes(int x) + { + Point point = default; + point.A = x; + point.B = x * x; + + Position position = default; + position.X = point.A; + position.Y = point.B; + + return position; + } + + public struct Point + { + public int A; + public int B; + } + + [ShaderMethod] + public static int FunctionWithLocalFunctionAndStaticMethod(int x) + { + static int AddTwo(int x) => x + 2; + + return Square(3 + AddOne(x) + AddTwo(x)); + } + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void ActivationWithDelegate(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.Square)); + + int[] result = buffer.ToArray(); + + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(result[i], Activations.Square(i)); + } + + device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.AddOne)); + + result = buffer.ToArray(); + + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(result[i], Activations.AddOne(i)); + } + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(ArgumentException))] + public unsafe void DelegateWithMissingAttributeOnMethod(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.Identity)); + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(ArgumentException))] + public unsafe void DelegateWrappingNonStaticMethod(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + [ShaderMethod] + int Dummy(int x) => x; + + device.Get().For(100, new ActivationWithDelegateShader(buffer, Dummy)); + } + + [AutoConstructor] + internal readonly partial struct ActivationWithMultipleDelegatesShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + public readonly Func f1; + public readonly Func f2; + + public void Execute() + { + buffer[ThreadIds.X] = f2(f1(ThreadIds.X)); + } + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void ActivationWithMultipleDelegates(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + device.Get().For(100, new ActivationWithMultipleDelegatesShader(buffer, Activations.Square, Activations.AddOne)); + + int[] result = buffer.ToArray(); + + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(result[i], Activations.AddOne(Activations.Square(i))); + } + } + + public const float FourAndAHalf = 4.5f; + public const int MagicNumber = 42; + + [AutoConstructor] + internal readonly partial struct DelegateWithConstantsShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + public readonly Func activation; + + public void Execute() + { + buffer[ThreadIds.X] = MagicNumber + activation(ThreadIds.X); + } + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void DelegateWithConstants(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + device.Get().For(100, new DelegateWithConstantsShader(buffer, Activations.FunctionWithConstants)); + + int[] result = buffer.ToArray(); + + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(result[i], MagicNumber + Activations.FunctionWithConstants(i)); + } + } + + public struct Position + { + public int X; + public int Y; + } + + [AutoConstructor] + internal readonly partial struct DelegateWithTypesShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + public readonly Func activation; + + public void Execute() + { + buffer[ThreadIds.X] = activation(ThreadIds.X); + } + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void DelegateWithTypes(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + device.Get().For(100, new DelegateWithTypesShader(buffer, Activations.FunctionWithTypes)); + + Position[] result = buffer.ToArray(); + + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(result[i].X, Activations.FunctionWithTypes(i).X); + Assert.AreEqual(result[i].Y, Activations.FunctionWithTypes(i).Y); + } + } + + [AutoConstructor] + internal readonly partial struct DelegateWithLocalFunctionsAndStaticMethodsShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + public readonly Func activation; + + public void Execute() + { + buffer[ThreadIds.X] = Activations.AddOne(ThreadIds.X) + activation(ThreadIds.X); + } + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void DelegateWithLocalFunctionsAndStaticMethods(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + device.Get().For(100, new DelegateWithLocalFunctionsAndStaticMethodsShader(buffer, Activations.FunctionWithLocalFunctionAndStaticMethod)); + + int[] result = buffer.ToArray(); + + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(result[i], Activations.AddOne(i) + Activations.FunctionWithLocalFunctionAndStaticMethod(i)); + } + } + } +} diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs index 50e72d30..08f3a20e 100644 --- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs +++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs @@ -1,3 +1,4 @@ +using ComputeSharp; using ComputeSharp.Interop; using ComputeSharp.Tests.Misc; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -171,5 +172,55 @@ namespace ComputeSharp.Tests return new(1, 1, 1, 1); } } + + [AutoConstructor] + public readonly partial struct LoopWithVarCounterShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + + /// + public void Execute() + { + for (var i = 0; i < 10; i++) + { + buffer[ThreadIds.X * 10 + i] = i; + } + } + } + + [TestMethod] + public void LoopWithVarCounter() + { + ReflectionServices.GetShaderInfo(out var info); + } + } +} + +namespace ExternalNamespace +{ + [TestClass] + [TestCategory("ShaderCompiler")] + public partial class ShaderCompilerTestsInExternalNamespace + { + [AutoConstructor] + public readonly partial struct UserDefinedTypeShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + + /// + public void Execute() + { + for (var i = 0; i < 10; i++) + { + buffer[ThreadIds.X * 10 + i] = i; + } + } + } + + [TestMethod] + public void UserDefinedType() + { + ReflectionServices.GetShaderInfo(out var info); + } } } diff --git a/tests/ComputeSharp.Tests/ShaderMembersTests.cs b/tests/ComputeSharp.Tests/ShaderMembersTests.cs index cff85204..00d40cf7 100644 --- a/tests/ComputeSharp.Tests/ShaderMembersTests.cs +++ b/tests/ComputeSharp.Tests/ShaderMembersTests.cs @@ -1,4 +1,3 @@ -using System; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/tests/ComputeSharp.Tests/ShadersTests.cs b/tests/ComputeSharp.Tests/ShadersTests.cs index f8bad618..1021eb9e 100644 --- a/tests/ComputeSharp.Tests/ShadersTests.cs +++ b/tests/ComputeSharp.Tests/ShadersTests.cs @@ -2,6 +2,7 @@ using System; using System.IO; using System.Reflection; using System.Runtime.InteropServices; +using ComputeSharp.__Internals; using ComputeSharp.SwapChain.Shaders; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; @@ -10,6 +11,8 @@ using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Png; using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; +#pragma warning disable CS0618 + namespace ComputeSharp.Tests { [TestClass] @@ -112,7 +115,7 @@ namespace ComputeSharp.Tests shaderType, texture => new SwapChain.Shaders.Compute.ContouredLayers(texture, 0, background), texture => new ContouredLayers(0, background), - 0.0007f); + 0.000703f); } /// @@ -137,7 +140,7 @@ namespace ComputeSharp.Tests if (shaderType.IsAssignableTo(typeof(IComputeShader))) { static void RunComputeShader(ReadWriteTexture2D texture) - where T : struct, IComputeShader + where T : struct, IComputeShader, IShader { texture.GraphicsDevice.For(texture.Width, texture.Height, (T)Activator.CreateInstance(typeof(T), texture, 0f)!); } @@ -149,7 +152,7 @@ namespace ComputeSharp.Tests else { static void RunPixelShader(ReadWriteTexture2D texture) - where T : struct, IPixelShader + where T : struct, IPixelShader, IShader { texture.GraphicsDevice.ForEach(texture, (T)Activator.CreateInstance(typeof(T), 0f)!); } @@ -188,8 +191,8 @@ namespace ComputeSharp.Tests Func, TCompute> computeFactory, Func, TPixel> pixelFactory, float delta) - where TCompute : struct, IComputeShader - where TPixel : struct, IPixelShader + where TCompute : struct, IComputeShader, IShader + where TPixel : struct, IPixelShader, IShader { _ = device.Get();