diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj
index 09697080..9f52daa2 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj
@@ -78,7 +78,6 @@
-
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs
index 3dd66174..0ac2d906 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs
@@ -22,63 +22,34 @@ partial class ID2D1ShaderGenerator
partial class LoadBytecode
{
///
- /// Creates a instance for the TryGetBytecode method.
+ /// Creates a instance for the ShaderProfile property.
///
/// The input bytecode info.
- /// An opaque instance to transform the final tree into text.
- /// The resulting instance for the BuildHlslSource method.
- public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, out Func fixup)
+ /// The resulting instance for the ShaderProfile property.
+ public static PropertyDeclarationSyntax GetShaderProfileSyntax(EmbeddedBytecodeInfo bytecodeInfo)
{
- BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals);
-
- if (bytecodeLiterals is not null)
- {
- fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals), Encoding.UTF8);
- }
- else
- {
- fixup = static tree => tree.GetText(Encoding.UTF8);
- }
-
// This code produces a method declaration as follows:
//
- // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadBytecode(ref TLoader loader, ref global::ComputeSharp.D2D1.D2D1ShaderProfile? shaderProfile, ref global::ComputeSharp.D2D1.D2D1CompileOptions? compileOptions)
- // {
- //
- // }
+ // readonly ComputeSharp.D2D1.D2D1ShaderProfile global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ShaderProfile => ;
return
- MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(nameof(LoadBytecode)))
+ PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1ShaderProfile"), Identifier(nameof(ID2D1Shader.ShaderProfile)))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
- .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader")))
- .AddParameterListParameters(
- Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader")),
- Parameter(Identifier("shaderProfile")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(NullableType(IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"))),
- Parameter(Identifier("compileOptions")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(NullableType(IdentifierName("global::ComputeSharp.D2D1.D2D1CompileOptions"))))
- .WithBody(block);
+ .WithExpressionBody(ArrowExpressionClause(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"),
+ IdentifierName(bytecodeInfo.ShaderProfile.ToString(CultureInfo.InvariantCulture)))))
+ .WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
}
///
- /// Gets a instance with the logic to try to get a compiled shader bytecode.
+ /// Creates a instance for the CompileOptions property.
///
/// The input bytecode info.
- /// The resulting bytecode literals to insert into the final source code.
- /// The instance trying to retrieve the precompiled shader.
- private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals)
+ /// The resulting instance for the CompileOptions property.
+ public static PropertyDeclarationSyntax GetCompileOptionsSyntax(EmbeddedBytecodeInfo bytecodeInfo)
{
- // This method needs to handle several different scenarions, which are as follows:
- // 1) If [EmbeddedBytecode] is used, then the shader is precompiled and stored as a ReadOnlySpan. In this case,
- // this bytecode would have been generated with some specific D2D1ShaderProfile and D2D1CompileOptions values. So,
- // a branch is generated to try to retrieve this precompiled bytecode, which can be returned if and only if the
- // requested shader profile and compile options are either null, or either matches the values that have been used
- // to generate that bytecode. If this is the case, then no further work is done and that binary data is returned.
- // 2) If either the requested shader profile or options do not match the values used to create the shader bytecode,
- // then a call to the internal D2D1ShaderCompiler.LoadDynamicBytecode API is used, to create the shader on the fly.
- // 3) If [EmbeddedBytecode] is not used, then regardless of the requested profile and options, a new shader is compiled.
- // 4) If this is the case and either the shader profile or the options are null, then this method will manually set the
- // value being null to the default one to use. That is, D2D1ShaderProfile.PixelShader50 will be used as the target,
- // and the options will be set to D2D1CompileOptions.Default (and optionally, D2D1CompileOptions.EnableLinking too).
-
// Get a formatted representation of the compile options being used
ExpressionSyntax compileOptionsExpression =
ParseExpression(
@@ -88,134 +59,280 @@ partial class ID2D1ShaderGenerator
.Select(static name => $"global::ComputeSharp.D2D1.D2D1CompileOptions.{name.Trim()}")
.Aggregate("", static (left, right) => left.Length > 0 ? $"{left} | {right}" : right));
- // Add parantheses if needed
- if (compileOptionsExpression is BinaryExpressionSyntax)
+ // This code produces a method declaration as follows:
+ //
+ // readonly ComputeSharp.D2D1.D2D1CompileOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.CompileOptions => ;
+ return
+ PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1CompileOptions"), Identifier(nameof(ID2D1Shader.CompileOptions)))
+ .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
+ .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
+ .WithExpressionBody(ArrowExpressionClause(compileOptionsExpression))
+ .WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
+ }
+
+ ///
+ /// Creates a instance for the HlslBytecode property.
+ ///
+ /// The input bytecode info.
+ /// An opaque instance to transform the final tree into text.
+ /// Any additional instances needed by the generated code, if needed.
+ /// The resulting instance for the HlslBytecode property.
+ public static PropertyDeclarationSyntax GetHlslBytecodeSyntax(
+ EmbeddedBytecodeInfo bytecodeInfo,
+ out Func fixup,
+ out TypeDeclarationSyntax[] additionalTypes)
+ {
+ ExpressionSyntax memoryExpression;
+
+ // If there is no bytecode, simply return a default expression.
+ // Otherwise, declare the memory manager and access it.
+ if (bytecodeInfo.Bytecode.Length == 0)
{
- compileOptionsExpression = ParenthesizedExpression(compileOptionsExpression);
+ memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword));
+ fixup = static tree => tree.GetText(Encoding.UTF8);
+ additionalTypes = Array.Empty();
+ }
+ else
+ {
+ // Create a ReadOnlyMemory instance from the memory manager:
+ //
+ // HlslBytecodeMemoryManager.Instance.Memory
+ memoryExpression =
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("HlslBytecodeMemoryManager"),
+ IdentifierName("Instance")),
+ IdentifierName("Memory"));
+
+ TypeDeclarationSyntax memoryManagerDeclaration = GetMemoryManagerDeclaration(bytecodeInfo);
+ string bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(bytecodeInfo.Bytecode.AsSpan());
+
+ additionalTypes = new TypeDeclarationSyntax[] { memoryManagerDeclaration };
+ fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals), Encoding.UTF8);
}
- // This code produces a block declaration as follows:
+ // This code produces a method declaration as follows:
//
- // global::ComputeSharp.D2D1.D2D1ShaderProfile effectiveShaderProfile = shaderProfile ??= ;
- // global::ComputeSharp.D2D1.D2D1CompileOptions effectiveCompileOptions = compileOptions ??= ;
+ // readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslBytecode => ;
+ return
+ PropertyDeclaration(
+ GenericName(Identifier("global::System.ReadOnlyMemory"))
+ .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))),
+ Identifier(nameof(ID2D1Shader.HlslBytecode)))
+ .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
+ .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
+ .WithExpressionBody(ArrowExpressionClause(memoryExpression))
+ .WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
+ }
+
+ ///
+ /// Gets a instance with the logic to try to get a compiled shader bytecode.
+ ///
+ /// The input bytecode info.
+ /// The instance trying to retrieve the precompiled shader.
+ private static unsafe TypeDeclarationSyntax GetMemoryManagerDeclaration(EmbeddedBytecodeInfo bytecodeInfo)
+ {
+ // Create the MemoryManager declaration:
//
- // global::ComputeSharp.D2D1.__Internals.D2D1ShaderCompiler.LoadDynamicBytecode(ref loader, in this, effectiveShaderProfile, effectiveCompileOptions);
- BlockSyntax dynamicLoadingBlock =
- Block(
- LocalDeclarationStatement(
- VariableDeclaration(IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"))
- .AddVariables(
- VariableDeclarator(Identifier("effectiveShaderProfile"))
- .WithInitializer(EqualsValueClause(
- AssignmentExpression(
- SyntaxKind.CoalesceAssignmentExpression,
- IdentifierName("shaderProfile"),
- IdentifierName($"global::ComputeSharp.D2D1.D2D1ShaderProfile.{D2D1ShaderProfile.PixelShader50}")))))),
- LocalDeclarationStatement(
- VariableDeclaration(IdentifierName("global::ComputeSharp.D2D1.D2D1CompileOptions"))
- .AddVariables(
- VariableDeclarator(Identifier("effectiveCompileOptions"))
- .WithInitializer(EqualsValueClause(
- AssignmentExpression(
- SyntaxKind.CoalesceAssignmentExpression,
- IdentifierName("compileOptions"),
- compileOptionsExpression))))),
- ExpressionStatement(
- InvocationExpression(
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName("global::ComputeSharp.D2D1.__Internals.D2D1ShaderCompiler"),
- IdentifierName("LoadDynamicBytecode")))
- .AddArgumentListArguments(
- Argument(IdentifierName("loader")).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)),
- Argument(ThisExpression()).WithRefKindKeyword(Token(SyntaxKind.InKeyword)),
- Argument(IdentifierName("effectiveShaderProfile")),
- Argument(IdentifierName("effectiveCompileOptions")))));
-
- // If there is no precompiled bytecode, just return the dynamic path
- if (bytecodeInfo.Bytecode.IsDefaultOrEmpty)
- {
- bytecodeLiterals = null;
-
- return dynamicLoadingBlock;
- }
-
- bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(bytecodeInfo.Bytecode.AsSpan());
-
- // Prepare the expression for the default shader profile to use
- ExpressionSyntax shaderProfileExpression =
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"),
- IdentifierName(bytecodeInfo.ShaderProfile.ToString(CultureInfo.InvariantCulture)));
-
- // This code produces a branch as follows:
- //
- // if (shaderProfile is null or && compileOptions is null or )
+ // ///
+ // /// implementation to get the HLSL bytecode.
+ // ///
+ // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")]
+ // [global::System.Diagnostics.DebuggerNonUserCode]
+ // [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
+ // file sealed HlslBytecodeMemoryManager : global::System.Buffers.MemoryManager
// {
- // global::System.ReadOnlySpan bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE };
- //
- // loader.LoadEmbeddedBytecode(bytecode);
- //
- // shaderProfile = ;
- // compileOptions = ;
// }
+ TypeDeclarationSyntax typeDeclaration =
+ ClassDeclaration("HlslBytecodeMemoryManager")
+ .AddModifiers(Token(SyntaxKind.FileKeyword), Token(SyntaxKind.SealedKeyword))
+ .AddBaseListTypes(SimpleBaseType(
+ GenericName(Identifier("global::System.Buffers.MemoryManager"))
+ .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))))
+ .AddAttributeLists(
+ AttributeList(SingletonSeparatedList(
+ Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments(
+ AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))),
+ AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))),
+ AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))),
+ AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))))
+ .WithLeadingTrivia(
+ Comment("/// "),
+ Comment("""/// A implementation to get the HLSL bytecode."""),
+ Comment("/// "));
+
+ using ImmutableArrayBuilder memberDeclarations = ImmutableArrayBuilder.Rent();
+
+ // Declare the singleton property to get the memory manager:
//
- // Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string
- // is created by the generator. This greatly speeds up the code generation, as it avoids
- // having to create/parse tens of thousands of literal expression nodes for every shader.
- IfStatementSyntax embeddedBranch =
- IfStatement(
- BinaryExpression(
- SyntaxKind.LogicalAndExpression,
- IsPatternExpression(
- IdentifierName("shaderProfile"),
- BinaryPattern(
- SyntaxKind.OrPattern,
- ConstantPattern(LiteralExpression(SyntaxKind.NullLiteralExpression)),
- ConstantPattern(shaderProfileExpression))),
- IsPatternExpression(
- IdentifierName("compileOptions"),
- BinaryPattern(
- SyntaxKind.OrPattern,
- ConstantPattern(LiteralExpression(SyntaxKind.NullLiteralExpression)),
- ConstantPattern(compileOptionsExpression)))),
- Block(
- LocalDeclarationStatement(
- VariableDeclaration(
- GenericName(Identifier("global::System.ReadOnlySpan"))
- .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
- .AddVariables(
- VariableDeclarator(Identifier("bytecode"))
- .WithInitializer(
- EqualsValueClause(
- ArrayCreationExpression(
- ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
- .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression()))))
- .WithInitializer(
- InitializerExpression(
- SyntaxKind.ArrayInitializerExpression,
- SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))))),
- ExpressionStatement(
- InvocationExpression(
+ // /// The singleton instance to use.
+ // public static readonly HlslBytecodeMemoryManager Instance = new();
+ memberDeclarations.Add(
+ FieldDeclaration(
+ VariableDeclaration(IdentifierName("HlslBytecodeMemoryManager"))
+ .AddVariables(
+ VariableDeclarator(Identifier("Instance"))
+ .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression()))))
+ .AddModifiers(
+ Token(SyntaxKind.PublicKeyword),
+ Token(SyntaxKind.StaticKeyword),
+ Token(SyntaxKind.ReadOnlyKeyword))
+ .WithLeadingTrivia(Comment("""/// The singleton instance to use.""")));
+
+ // Construct the RVA span property:
+ //
+ // /// The RVA data with the HLSL bytecode.
+ // private static global::System.ReadOnlySpan Data => new byte[] { __EMBEDDED_SHADER_BYTECODE };
+ memberDeclarations.Add(
+ PropertyDeclaration(
+ GenericName(Identifier("global::System.ReadOnlySpan"))
+ .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))),
+ Identifier("Data"))
+ .AddModifiers(Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword))
+ .WithExpressionBody(
+ ArrowExpressionClause(
+ ArrayCreationExpression(
+ ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
+ .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression()))),
+ InitializerExpression(
+ SyntaxKind.ArrayInitializerExpression,
+ SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE"))))))
+ .WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
+ .WithLeadingTrivia(Comment("/// The RVA data with the HLSL bytecode.")));
+
+ // Override the Memory property:
+ //
+ // ///
+ // public override global::System.Memory Memory
+ // {
+ // [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
+ // get => CreateMemory(Data.Length);
+ // }
+ memberDeclarations.Add(
+ PropertyDeclaration(
+ GenericName(Identifier("global::System.Memory"))
+ .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))),
+ Identifier("Memory"))
+ .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword))
+ .AddAccessorListAccessors(
+ AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
+ .AddAttributeLists(
+ AttributeList(
+ SingletonSeparatedList(
+ Attribute(IdentifierName("global::System.Runtime.CompilerServices.MethodImpl"))
+ .AddArgumentListArguments(
+ AttributeArgument(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("global::System.Runtime.CompilerServices.MethodImplOptions"),
+ IdentifierName("AggressiveInlining")))))))
+ .WithExpressionBody(
+ ArrowExpressionClause(
+ InvocationExpression(IdentifierName("CreateMemory"))
+ .AddArgumentListArguments(
+ Argument(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("Data"),
+ IdentifierName("Length"))))))
+ .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)))
+ .WithLeadingTrivia(Comment("/// ")));
+
+ // Add the GetSpan() method:
+ //
+ // ///
+ // public override unsafe global::System.Span GetSpan
+ // {
+ // return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal(Data)), Data.Length);
+ // }
+ memberDeclarations.Add(
+ MethodDeclaration(
+ GenericName(Identifier("global::System.Span"))
+ .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))),
+ Identifier("GetSpan"))
+ .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword), Token(SyntaxKind.UnsafeKeyword))
+ .AddBodyStatements(
+ ReturnStatement(
+ ImplicitObjectCreationExpression()
+ .AddArgumentListArguments(
+ Argument(
+ InvocationExpression(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("global::System.Runtime.CompilerServices.Unsafe"),
+ IdentifierName("AsPointer")))
+ .AddArgumentListArguments(
+ Argument(
+ InvocationExpression(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"),
+ IdentifierName("GetReference")))
+ .AddArgumentListArguments(Argument(IdentifierName("Data"))))
+ .WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)))),
+ Argument(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName("loader"),
- IdentifierName("LoadEmbeddedBytecode")))
- .AddArgumentListArguments(Argument(IdentifierName("bytecode")))),
- ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- IdentifierName("shaderProfile"),
- shaderProfileExpression)),
- ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- IdentifierName("compileOptions"),
- compileOptionsExpression))));
+ IdentifierName("Data"),
+ IdentifierName("Length"))))))
+ .WithLeadingTrivia(Comment("/// ")));
- // Return the combined block
- return Block(embeddedBranch.WithElse(ElseClause(dynamicLoadingBlock)));
+ // Add the Pin(int elementIndex) method:
+ //
+ // ///
+ // public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex)
+ // {
+ // return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this);
+ // }
+ memberDeclarations.Add(
+ MethodDeclaration(IdentifierName("global::System.Buffers.MemoryHandle"), Identifier("Pin"))
+ .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword), Token(SyntaxKind.UnsafeKeyword))
+ .AddParameterListParameters(Parameter(Identifier("elementIndex")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
+ .AddBodyStatements(
+ ReturnStatement(
+ ImplicitObjectCreationExpression()
+ .AddArgumentListArguments(
+ Argument(
+ InvocationExpression(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("global::System.Runtime.CompilerServices.Unsafe"),
+ IdentifierName("AsPointer")))
+ .AddArgumentListArguments(
+ Argument(
+ InvocationExpression(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("global::System.Runtime.CompilerServices.Unsafe"),
+ IdentifierName("AsRef")))
+ .AddArgumentListArguments(
+ Argument(
+ ElementAccessExpression(IdentifierName("Data"))
+ .AddArgumentListArguments(Argument(IdentifierName("elementIndex"))))
+ .WithRefOrOutKeyword(Token(SyntaxKind.InKeyword))))
+ .WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)))),
+ Argument(ThisExpression()).WithNameColon(NameColon(IdentifierName("pinnable"))))))
+ .WithLeadingTrivia(Comment("/// ")));
+
+ // Add the empty Unpin() method
+ memberDeclarations.Add(
+ MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("Unpin"))
+ .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword))
+ .WithBody(Block())
+ .WithLeadingTrivia(Comment("/// ")));
+
+ // Add the empty Dispose(bool disposing) method
+ memberDeclarations.Add(
+ MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("Dispose"))
+ .AddModifiers(Token(SyntaxKind.ProtectedKeyword), Token(SyntaxKind.OverrideKeyword))
+ .AddParameterListParameters(
+ Parameter(Identifier("disposing")).WithType(PredefinedType(Token(SyntaxKind.BoolKeyword))))
+ .WithBody(Block())
+ .WithLeadingTrivia(Comment("/// ")));
+
+ return typeDeclaration.AddMembers(memberDeclarations.ToArray());
}
}
}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs
index 9957023c..7632b4a9 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs
@@ -362,11 +362,21 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
// Generate the LoadBytecode() methods
context.RegisterSourceOutput(embeddedBytecode, static (context, item) =>
{
- MethodDeclarationSyntax loadBytecodeMethod = LoadBytecode.GetSyntax(item.BytecodeInfo, out Func fixup);
- CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, loadBytecodeMethod, skipLocalsInit: false);
- SourceText text = fixup(compilationUnit);
+ PropertyDeclarationSyntax hlslBytecodeProperty = LoadBytecode.GetHlslBytecodeSyntax(item.BytecodeInfo, out Func fixup, out TypeDeclarationSyntax[] additionalTypes);
+ CompilationUnitSyntax hlslBytecodeCompilationUnit = GetCompilationUnitFromMember(item.Hierarchy, hlslBytecodeProperty, skipLocalsInit: false, additionalMemberDeclarations: additionalTypes);
+ SourceText text = fixup(hlslBytecodeCompilationUnit);
- context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadBytecode)}.g.cs", text);
+ context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.HlslBytecode.g.cs", text);
+
+ PropertyDeclarationSyntax shaderProfileProperty = LoadBytecode.GetShaderProfileSyntax(item.BytecodeInfo);
+ CompilationUnitSyntax shaderProfileCompilationUnit = GetCompilationUnitFromMember(item.Hierarchy, shaderProfileProperty, skipLocalsInit: false);
+
+ context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.ShaderProfile.g.cs", shaderProfileCompilationUnit.GetText(Encoding.UTF8));
+
+ PropertyDeclarationSyntax compileOptionsProperty = LoadBytecode.GetCompileOptionsSyntax(item.BytecodeInfo);
+ CompilationUnitSyntax compileOptionsCompilationUnit = GetCompilationUnitFromMember(item.Hierarchy, compileOptionsProperty, skipLocalsInit: false);
+
+ context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.CompileOptions.g.cs", compileOptionsCompilationUnit.GetText(Encoding.UTF8));
});
// Get the output buffer info (hierarchy and output buffers)
diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1BytecodeLoader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1BytecodeLoader.cs
deleted file mode 100644
index 3d4ccfa6..00000000
--- a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1BytecodeLoader.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using System;
-using System.ComponentModel;
-
-namespace ComputeSharp.D2D1.__Internals;
-
-///
-/// A base representing a bytecode loader for a D2D1 shader.
-///
-[EditorBrowsable(EditorBrowsableState.Never)]
-[Obsolete("This interface is not intended to be used directly by user code")]
-public interface ID2D1BytecodeLoader
-{
- ///
- /// Loads a dynamic shader bytecode.
- ///
- /// An opaque handle to the shader bytecode.
- /// Thrown if the shader has already been initialized or a precompiled bytecode was requested when not available.
- void LoadDynamicBytecode(IntPtr handle);
-
- ///
- /// Loads the embedded shader bytecode for the shader.
- ///
- /// The shader bytecode.
- /// Thrown if the shader has already been initialized.
- void LoadEmbeddedBytecode(ReadOnlySpan bytecode);
-}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs
index e3de74cf..3da044d0 100644
--- a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs
+++ b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs
@@ -1,6 +1,5 @@
using System;
using System.ComponentModel;
-using System.Diagnostics.CodeAnalysis;
using ComputeSharp.D2D1.Interop;
namespace ComputeSharp.D2D1.__Internals;
@@ -128,16 +127,32 @@ public interface ID2D1Shader
string HlslSource { get; }
///
- /// Loads the bytecode for the current shader.
+ /// Gets the shader profile for the current shader.
///
- /// The type of bytecode loader being used.
- /// The instance to use to load the bytecode.
- /// The shader profile to use to get the shader bytecode (if , the precompiled shader will be used).
- /// The compile options to use to get the shader bytecode (if , the precompiled shader will be used).
- /// Thrown if a precompiled bytecode was requested ( is ), but it wasn't availablle.
- /// When this method returns, and will be set to the effective laues used to create the shader bytecode that was loaded.
+ ///
+ /// This shader profile is either explicitly set by users, or the default one for D2D1 shaders.
+ ///
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be used directly by user code")]
- void LoadBytecode(ref TLoader loader, [NotNull] ref D2D1ShaderProfile? shaderProfile, [NotNull] ref D2D1CompileOptions? compileOptions)
- where TLoader : struct, ID2D1BytecodeLoader;
+ D2D1ShaderProfile ShaderProfile { get; }
+
+ ///
+ /// Gets the compile options for the current shader.
+ ///
+ ///
+ /// This compile options are either explicitly set by users, or the default one for D2D1 shaders.
+ ///
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ [Obsolete("This method is not intended to be used directly by user code")]
+ D2D1CompileOptions CompileOptions { get; }
+
+ ///
+ /// Gets the HLSL bytecode for the current shader, if available.
+ ///
+ ///
+ /// If no precompiled HLSL bytecode is available, the returned instance will be empty.
+ ///
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ [Obsolete("This method is not intended to be used directly by user code")]
+ ReadOnlyMemory HlslBytecode { get; }
}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs
index 60f63619..473af757 100644
--- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs
@@ -1,7 +1,7 @@
using System;
using System.Runtime.CompilerServices;
-using ComputeSharp.D2D1.Shaders.Interop.Buffers;
using ComputeSharp.D2D1.Shaders.Loaders;
+using ComputeSharp.D2D1.Shaders.Translation;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
@@ -29,7 +29,18 @@ public static class D2D1PixelShader
public static ReadOnlyMemory LoadBytecode()
where T : unmanaged, ID2D1PixelShader
{
- return LoadOrCompileBytecode(null, null, out _, out _);
+ Unsafe.SkipInit(out T shader);
+
+ // This method is the one used by the built-in ID2D1Effect, so it has special optimization
+ // to help both performance and especially trimming. That is, we first check whether the
+ // HLSL code is already available, which should get completely inlined when using the
+ // generated code. This allows the entire fallback path below to be trimmed out.
+ if (shader.HlslBytecode is ReadOnlyMemory { Length: > 0 } hlslBytecode)
+ {
+ return hlslBytecode;
+ }
+
+ return CompileBytecode(null, null, out _, out _);
}
///
@@ -191,6 +202,40 @@ public static class D2D1PixelShader
return LoadOrCompileBytecode(shaderProfile, compileOptions | D2D1CompileOptions.PackMatrixRowMajor, out _, out _);
}
+ ///
+ /// Compiles the bytecode from an input D2D1 pixel shader.
+ ///
+ /// The type of D2D1 pixel shader to load the bytecode for.
+ /// The requested shader profile to use to get the shader bytecode.
+ /// The requested compile options to use to get the shader bytecode.
+ /// The effective shader profile that was used to get the shader bytecode.
+ /// The effective compile options that were used to get the shader bytecode.
+ /// A instance with the resulting shader bytecode.
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static unsafe ReadOnlyMemory CompileBytecode(
+ D2D1ShaderProfile? requestedShaderProfile,
+ D2D1CompileOptions? requestedCompileOptions,
+ out D2D1ShaderProfile effectiveShaderProfile,
+ out D2D1CompileOptions effectiveCompileOptions)
+ where T : unmanaged, ID2D1PixelShader
+ {
+ Unsafe.SkipInit(out T shader);
+
+ string hlslSource = shader.HlslSource;
+
+ // Set the effective profile and option to the requested ones or the default values
+ effectiveShaderProfile = requestedShaderProfile ?? shader.ShaderProfile;
+ effectiveCompileOptions = requestedCompileOptions ?? shader.CompileOptions;
+
+ // Compile the shader with the current settings
+ using ComPtr dynamicBytecode = D3DCompiler.Compile(hlslSource.AsSpan(), effectiveShaderProfile, effectiveCompileOptions);
+
+ byte* bytecodePtr = (byte*)dynamicBytecode.Get()->GetBufferPointer();
+ int bytecodeSize = (int)dynamicBytecode.Get()->GetBufferSize();
+
+ return new ReadOnlySpan(bytecodePtr, bytecodeSize).ToArray();
+ }
+
///
/// Loads or compiles the bytecode from an input D2D1 pixel shader.
///
@@ -200,7 +245,6 @@ public static class D2D1PixelShader
/// The effective shader profile that was used to get the shader bytecode.
/// The effective compile options that were used to get the shader bytecode.
/// A instance with the resulting shader bytecode.
- /// Thrown if the input shader has not been precompiled.
private static unsafe ReadOnlyMemory LoadOrCompileBytecode(
D2D1ShaderProfile? requestedShaderProfile,
D2D1CompileOptions? requestedCompileOptions,
@@ -208,28 +252,21 @@ public static class D2D1PixelShader
out D2D1CompileOptions effectiveCompileOptions)
where T : unmanaged, ID2D1PixelShader
{
- D2D1ShaderBytecodeLoader bytecodeLoader = default;
-
Unsafe.SkipInit(out T shader);
- shader.LoadBytecode(ref bytecodeLoader, ref requestedShaderProfile, ref requestedCompileOptions);
-
- effectiveShaderProfile = requestedShaderProfile.GetValueOrDefault();
- effectiveCompileOptions = requestedCompileOptions.GetValueOrDefault();
-
- using ComPtr dynamicBytecode = bytecodeLoader.GetResultingShaderBytecode(out ReadOnlySpan precompiledBytecode);
-
- // If a precompiled shader is available, return it
- if (!precompiledBytecode.IsEmpty)
+ // Check whether there is precompiled bytecode we can use
+ if (shader.HlslBytecode is ReadOnlyMemory { Length: > 0 } hlslBytecode &&
+ (requestedShaderProfile is null || shader.ShaderProfile == requestedShaderProfile.GetValueOrDefault()) &&
+ (requestedCompileOptions is null || shader.CompileOptions == requestedCompileOptions.GetValueOrDefault()))
{
- return new PinnedBufferMemoryManager(precompiledBytecode).Memory;
+ effectiveShaderProfile = shader.ShaderProfile;
+ effectiveCompileOptions = shader.CompileOptions;
+
+ return hlslBytecode;
}
- // Otherwise, return the dynamic shader instead
- byte* bytecodePtr = (byte*)dynamicBytecode.Get()->GetBufferPointer();
- int bytecodeSize = (int)dynamicBytecode.Get()->GetBufferSize();
-
- return new ReadOnlySpan(bytecodePtr, bytecodeSize).ToArray();
+ // Fallback path just compiling the HLSL code on the fly
+ return CompileBytecode(requestedShaderProfile, requestedCompileOptions, out effectiveShaderProfile, out effectiveCompileOptions);
}
///
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs
index 3ad440b7..8be0483b 100644
--- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs
@@ -1,8 +1,7 @@
using System;
using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
using ComputeSharp.D2D1.Extensions;
-using ComputeSharp.D2D1.Shaders.Loaders;
+using ComputeSharp.D2D1.Shaders.Translation;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
@@ -35,37 +34,35 @@ public static class D2D1ReflectionServices
string hlslSource = shader.HlslSource;
- D2D1ShaderBytecodeLoader bytecodeLoader = default;
+ using ComPtr d3D11ShaderReflection = default;
- D2D1ShaderProfile? shaderProfile = null;
- D2D1CompileOptions? compileOptions = null;
-
- shader.LoadBytecode(ref bytecodeLoader, ref shaderProfile, ref compileOptions);
-
- using ComPtr dynamicBytecode = bytecodeLoader.GetResultingShaderBytecode(out ReadOnlySpan precompiledBytecode);
-
- byte* bytecodePtr;
- int bytecodeSize;
-
- if (!precompiledBytecode.IsEmpty)
+ // If the shader already has embedded bytecode, use that directly
+ if (shader.HlslBytecode is ReadOnlyMemory { Length: > 0 } hlslBytecode)
{
- bytecodePtr = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(precompiledBytecode));
- bytecodeSize = precompiledBytecode.Length;
+ fixed (byte* hlslBytecodePtr = hlslBytecode.Span)
+ {
+ DirectX.D3DReflect(
+ pSrcData: hlslBytecodePtr,
+ SrcDataSize: (nuint)hlslBytecode.Length,
+ pInterface: Windows.__uuidof(),
+ ppReflector: d3D11ShaderReflection.GetVoidAddressOf()).Assert();
+ }
}
else
{
- bytecodePtr = (byte*)dynamicBytecode.Get()->GetBufferPointer();
- bytecodeSize = (int)dynamicBytecode.Get()->GetBufferSize();
+ // Otherwise, compile it with default shader profile and compile options and use that.
+ // Note that we're intentionally retrieving an ID3DBlob instance here to avoid having
+ // to allocate a ReadOnlyMemory object to throw away immediately, as we don't
+ // actually need to keep the bytecode for later.
+ using ComPtr dynamicBytecode = D3DCompiler.Compile(hlslSource.AsSpan(), shader.ShaderProfile, shader.CompileOptions);
+
+ DirectX.D3DReflect(
+ pSrcData: (byte*)dynamicBytecode.Get()->GetBufferPointer(),
+ SrcDataSize: dynamicBytecode.Get()->GetBufferSize(),
+ pInterface: Windows.__uuidof(),
+ ppReflector: d3D11ShaderReflection.GetVoidAddressOf()).Assert();
}
- using ComPtr d3D11ShaderReflection = default;
-
- DirectX.D3DReflect(
- pSrcData: bytecodePtr,
- SrcDataSize: (nuint)bytecodeSize,
- pInterface: Windows.__uuidof(),
- ppReflector: d3D11ShaderReflection.GetVoidAddressOf()).Assert();
-
D3D11_SHADER_DESC d3D11ShaderDescription;
d3D11ShaderReflection.Get()->GetDesc(&d3D11ShaderDescription).Assert();
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ShaderCompiler.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ShaderCompiler.cs
index 9e635129..da2188c1 100644
--- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ShaderCompiler.cs
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ShaderCompiler.cs
@@ -74,7 +74,7 @@ public static class D2D1ShaderCompiler
options &= ~D2D1CompileOptions.EnableLinking;
// Compile the standalone D2D1 full shader
- using ComPtr d3DBlobFullShader = D3DCompiler.CompileShader(
+ using ComPtr d3DBlobFullShader = D3DCompiler.Compile(
source: hlslSourceAscii,
macro: D3DCompiler.ASCII.D2D_FULL_SHADER,
d2DEntry: entryPointAscii,
@@ -91,7 +91,7 @@ public static class D2D1ShaderCompiler
}
// Compile the export function
- using ComPtr d3DBlobFunction = D3DCompiler.CompileShader(
+ using ComPtr d3DBlobFunction = D3DCompiler.Compile(
source: hlslSourceAscii,
macro: D3DCompiler.ASCII.D2D_FUNCTION,
d2DEntry: entryPointAscii,
diff --git a/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ShaderBytecodeLoader.cs b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ShaderBytecodeLoader.cs
deleted file mode 100644
index 26592bff..00000000
--- a/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1ShaderBytecodeLoader.cs
+++ /dev/null
@@ -1,68 +0,0 @@
-using System;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using ComputeSharp.D2D1.__Internals;
-using ComputeSharp.D2D1.Extensions;
-using TerraFX.Interop.DirectX;
-using TerraFX.Interop.Windows;
-
-#pragma warning disable CS0618
-
-namespace ComputeSharp.D2D1.Shaders.Loaders;
-
-///
-/// A bytecode loader for D2D1 shaders.
-///
-internal unsafe struct D2D1ShaderBytecodeLoader : ID2D1BytecodeLoader
-{
- ///
- /// A pointer to the precompiled shader, if available.
- ///
- private byte* embeddedBytecodePtr;
-
- ///
- /// The length of the precompiled shader buffer, if available.
- ///
- private int embeddedBytecodeSize;
-
- ///
- /// The dynamically compiled shader bytecode blob, if available.
- ///
- private ComPtr d3DBlob;
-
- ///
- /// Gets the resulting shader bytecode that was available.
- ///
- /// The precompiled bytecode, if available.
- /// An with the shader bytecode, if dynamically compiled.
- /// Either is empty, or the returned pointer is .
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public readonly ComPtr GetResultingShaderBytecode(out ReadOnlySpan precompiledBytecode)
- {
- precompiledBytecode = new ReadOnlySpan(this.embeddedBytecodePtr, this.embeddedBytecodeSize);
-
- return this.d3DBlob.Move();
- }
-
- ///
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- unsafe void ID2D1BytecodeLoader.LoadDynamicBytecode(IntPtr handle)
- {
- default(InvalidOperationException).ThrowIf(this.embeddedBytecodePtr is not null);
- default(InvalidOperationException).ThrowIf(this.d3DBlob.Get() is not null);
- default(NotSupportedException).ThrowIf(handle == IntPtr.Zero);
-
- this.d3DBlob = new ComPtr((ID3DBlob*)handle);
- }
-
- ///
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- void ID2D1BytecodeLoader.LoadEmbeddedBytecode(ReadOnlySpan bytecode)
- {
- default(InvalidOperationException).ThrowIf(this.embeddedBytecodePtr is not null);
- default(InvalidOperationException).ThrowIf(this.d3DBlob.Get() is not null);
-
- this.embeddedBytecodePtr = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(bytecode));
- this.embeddedBytecodeSize = bytecode.Length;
- }
-}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1/Shaders/Translation/D3DCompiler.cs b/src/ComputeSharp.D2D1/Shaders/Translation/D3DCompiler.cs
index 8038b1a7..3159873f 100644
--- a/src/ComputeSharp.D2D1/Shaders/Translation/D3DCompiler.cs
+++ b/src/ComputeSharp.D2D1/Shaders/Translation/D3DCompiler.cs
@@ -9,8 +9,6 @@ using ComputeSharp.D2D1.Extensions;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
-#pragma warning disable IDE1006
-
namespace ComputeSharp.D2D1.Shaders.Translation;
///
@@ -39,7 +37,7 @@ internal static unsafe partial class D3DCompiler
try
{
// Compile the standalone D2D1 full shader
- using ComPtr d3DBlobFullShader = CompileShader(
+ using ComPtr d3DBlobFullShader = Compile(
source: buffer.AsSpan(0, writtenBytes),
macro: ASCII.D2D_FULL_SHADER,
d2DEntry: ASCII.Execute,
@@ -53,7 +51,7 @@ internal static unsafe partial class D3DCompiler
}
// Compile the export function
- using ComPtr d3DBlobFunction = CompileShader(
+ using ComPtr d3DBlobFunction = Compile(
source: buffer.AsSpan(0, writtenBytes),
macro: ASCII.D2D_FUNCTION,
d2DEntry: ASCII.Execute,
@@ -73,7 +71,7 @@ internal static unsafe partial class D3DCompiler
}
///
- /// Compiles a D2D1 pixel shader with the specified parameters.
+ /// Compiles an HLSL shader with the specified parameters.
///
/// The HLSL source code to compile (in ASCII).
/// The target macro to define for the shader (either D2D_FULL_SHADER or D2D_FUNCTION).
@@ -83,7 +81,7 @@ internal static unsafe partial class D3DCompiler
/// The compilationm flag to use.
/// The bytecode for the compiled shader.
/// Thrown if the compilation fails.
- public static ComPtr CompileShader(
+ public static ComPtr Compile(
ReadOnlySpan source,
ReadOnlySpan macro,
ReadOnlySpan d2DEntry,
diff --git a/src/ComputeSharp.D2D1/Shaders/Translation/__Internals/D2D1ShaderCompiler.cs b/src/ComputeSharp.D2D1/Shaders/Translation/__Internals/D2D1ShaderCompiler.cs
deleted file mode 100644
index 95414a68..00000000
--- a/src/ComputeSharp.D2D1/Shaders/Translation/__Internals/D2D1ShaderCompiler.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using System;
-using System.ComponentModel;
-using System.Runtime.CompilerServices;
-using TerraFX.Interop.DirectX;
-using TerraFX.Interop.Windows;
-
-namespace ComputeSharp.D2D1.__Internals;
-
-///
-/// A that uses the DXC APIs to compile compute shaders.
-///
-[EditorBrowsable(EditorBrowsableState.Never)]
-[Obsolete("This type is not intended to be used directly by user code")]
-public static class D2D1ShaderCompiler
-{
- ///
- /// Compiles a new HLSL shader from the input source code.
- ///
- /// The type of bytecode loader being used.
- /// The type of D2D1 shader being dispatched.
- /// The instance to use to load the bytecode.
- /// The input instance representing the D2D1 shader to run.
- /// The shader profile to use to compile the shader.
- /// The compiler options to use to compile the shader.
- public static unsafe void LoadDynamicBytecode(ref TLoader loader, in T shader, D2D1ShaderProfile shaderProfile, D2D1CompileOptions options)
- where TLoader : struct, ID2D1BytecodeLoader
- where T : struct, ID2D1Shader
- {
- string hlslSource = Unsafe.AsRef(in shader).HlslSource;
-
- using ComPtr d3DBlobBytecode = Shaders.Translation.D3DCompiler.Compile(
- hlslSource.AsSpan(),
- shaderProfile,
- options);
-
- loader.LoadDynamicBytecode((IntPtr)d3DBlobBytecode.Get());
- }
-}
\ No newline at end of file
diff --git a/tests/ComputeSharp.D2D1.Tests.AssemblyLevelAttributes/D2D1PixelShaderTests.cs b/tests/ComputeSharp.D2D1.Tests.AssemblyLevelAttributes/D2D1PixelShaderTests.cs
index 9c3b0f3e..566facc4 100644
--- a/tests/ComputeSharp.D2D1.Tests.AssemblyLevelAttributes/D2D1PixelShaderTests.cs
+++ b/tests/ComputeSharp.D2D1.Tests.AssemblyLevelAttributes/D2D1PixelShaderTests.cs
@@ -17,15 +17,32 @@ public partial class D2D1PixelShaderTests
// Verify the shader was precompiled
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? manager));
- Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
+ Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
- _ = D2D1PixelShader.LoadBytecode(
+ // Compile with the same assembly level options
+ bytecode = D2D1PixelShader.LoadBytecode(
shaderProfile: D2D1ShaderProfile.PixelShader41,
compileOptions: D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.PartialPrecision);
- // Verify the expected options were used
+ // Verify the same bytecode is returned
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
- Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
+ Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
+
+ // Incorrect profile
+ bytecode = D2D1PixelShader.LoadBytecode(D2D1ShaderProfile.PixelShader50);
+
+ Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? _));
+ Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out ArraySegment segment));
+ Assert.AreEqual(0, segment.Offset);
+ Assert.IsTrue(segment.Count > 0);
+
+ // Incorrect options
+ bytecode = D2D1PixelShader.LoadBytecode(D2D1CompileOptions.Default);
+
+ Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? _));
+ Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out segment));
+ Assert.AreEqual(0, segment.Offset);
+ Assert.IsTrue(segment.Count > 0);
}
[D2DInputCount(3)]
@@ -51,14 +68,25 @@ public partial class D2D1PixelShaderTests
ReadOnlyMemory bytecode = D2D1PixelShader.LoadBytecode();
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? manager));
- Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
+ Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
- _ = D2D1PixelShader.LoadBytecode(
+ // Try to recompile with the correct combined options
+ bytecode = D2D1PixelShader.LoadBytecode(
shaderProfile: D2D1ShaderProfile.PixelShader50,
compileOptions: D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.PartialPrecision);
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
- Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
+ Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
+
+ // Incorrect profile (overridden profile)
+ bytecode = D2D1PixelShader.LoadBytecode(
+ shaderProfile: D2D1ShaderProfile.PixelShader41,
+ compileOptions: D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.PartialPrecision);
+
+ Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? _));
+ Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out ArraySegment segment));
+ Assert.AreEqual(0, segment.Offset);
+ Assert.IsTrue(segment.Count > 0);
}
[D2DInputCount(3)]
@@ -85,14 +113,25 @@ public partial class D2D1PixelShaderTests
ReadOnlyMemory bytecode = D2D1PixelShader.LoadBytecode();
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? manager));
- Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
+ Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
- _ = D2D1PixelShader.LoadBytecode(
+ // Try to recompile with the correct combined options
+ bytecode = D2D1PixelShader.LoadBytecode(
shaderProfile: D2D1ShaderProfile.PixelShader41,
compileOptions: D2D1CompileOptions.Debug | D2D1CompileOptions.AvoidFlowControl | D2D1CompileOptions.PartialPrecision);
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
- Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
+ Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
+
+ // Incorrect profile (overridden compile options)
+ bytecode = D2D1PixelShader.LoadBytecode(
+ shaderProfile: D2D1ShaderProfile.PixelShader41,
+ compileOptions: D2D1CompileOptions.Default);
+
+ Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? _));
+ Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out ArraySegment segment));
+ Assert.AreEqual(0, segment.Offset);
+ Assert.IsTrue(segment.Count > 0);
}
[D2DInputCount(3)]
@@ -119,14 +158,15 @@ public partial class D2D1PixelShaderTests
ReadOnlyMemory bytecode = D2D1PixelShader.LoadBytecode();
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? manager));
- Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
+ Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
- _ = D2D1PixelShader.LoadBytecode(
+ // Try to get the new bytecode
+ bytecode = D2D1PixelShader.LoadBytecode(
shaderProfile: D2D1ShaderProfile.PixelShader50,
compileOptions: D2D1CompileOptions.Debug | D2D1CompileOptions.AvoidFlowControl | D2D1CompileOptions.PartialPrecision);
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
- Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
+ Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
}
[D2DInputCount(3)]
diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs
index 689e3890..e8405d0a 100644
--- a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs
+++ b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs
@@ -273,6 +273,26 @@ public partial class D2D1PixelShaderTests
}
}
+ [TestMethod]
+ public unsafe void GetBytecode_FromDynamicBytecode()
+ {
+ ReadOnlyMemory bytecode = D2D1PixelShader.LoadBytecode();
+
+ Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? _));
+ Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out ArraySegment segment));
+ Assert.AreEqual(0, segment.Offset);
+ Assert.IsTrue(segment.Count > 0);
+ }
+
+ [D2DInputCount(0)]
+ private readonly partial struct ShaderWithoutEmbeddedBytecode : ID2D1PixelShader
+ {
+ public float4 Execute()
+ {
+ return 0;
+ }
+ }
+
[TestMethod]
public unsafe void GetBytecode_FromEmbeddedBytecode()
{
@@ -280,25 +300,41 @@ public partial class D2D1PixelShaderTests
ReadOnlyMemory bytecode = D2D1PixelShader.LoadBytecode();
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? manager));
- Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
+ Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
// Matching shader profile
bytecode = D2D1PixelShader.LoadBytecode(D2D1ShaderProfile.PixelShader40Level91);
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
- Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
+ Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
// Matching compile options
bytecode = D2D1PixelShader.LoadBytecode(D2D1CompileOptions.Default | D2D1CompileOptions.EnableLinking);
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
- Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
+ Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
// Matching shader profile and compile options
bytecode = D2D1PixelShader.LoadBytecode(D2D1ShaderProfile.PixelShader40Level91, D2D1CompileOptions.Default | D2D1CompileOptions.EnableLinking);
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
- Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
+ Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
+
+ // Incorrect profile
+ bytecode = D2D1PixelShader.LoadBytecode(D2D1ShaderProfile.PixelShader50);
+
+ Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? _));
+ Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out ArraySegment segment));
+ Assert.AreEqual(0, segment.Offset);
+ Assert.IsTrue(segment.Count > 0);
+
+ // Incorrect options
+ bytecode = D2D1PixelShader.LoadBytecode(D2D1CompileOptions.Default | D2D1CompileOptions.EnableStrictness);
+
+ Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? _));
+ Assert.IsTrue(MemoryMarshal.TryGetArray(bytecode, out segment));
+ Assert.AreEqual(0, segment.Offset);
+ Assert.IsTrue(segment.Count > 0);
}
[TestMethod]
@@ -340,7 +376,7 @@ public partial class D2D1PixelShaderTests
ReadOnlyMemory bytecode = D2D1PixelShader.LoadBytecode();
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? manager));
- Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
+ Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
// Bytecode with all output parameters
ReadOnlyMemory bytecode2 = D2D1PixelShader.LoadBytecode(out D2D1ShaderProfile shaderProfile, out D2D1CompileOptions compileOptions);
@@ -354,13 +390,13 @@ public partial class D2D1PixelShaderTests
bytecode = D2D1PixelShader.LoadBytecode(D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2);
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
- Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
+ Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
// Matching shader profile and compile options
bytecode = D2D1PixelShader.LoadBytecode(D2D1ShaderProfile.PixelShader40Level91, D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2);
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager));
- Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name);
+ Assert.IsTrue(manager!.GetType().Name.Contains("HlslBytecodeMemoryManager"));
}
[D2DInputCount(3)]