Merge pull request #570 from Sergio0694/dev/input-types-memory

Generate D2D1 input types as file local ReadOnlyMemory<T>
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-09-27 21:46:46 +02:00
コミット 62988f10fe
11ファイル変更
+385 -136

検索条件に一致するファイルはありません

+1
ファイルの表示
@@ -85,6 +85,7 @@
<Compile Include="..\ComputeSharp.D2D1\Interfaces\__Internals\ID2D1Shader.cs" Link="ComputeSharp.D2D1\Interfaces\__Internals\ID2D1Shader.cs" />
<Compile Include="..\ComputeSharp.D2D1\Intrinsics\D2D.cs" Link="ComputeSharp.D2D1\Intrinsics\D2D.cs" />
<Compile Include="..\ComputeSharp.D2D1\Shaders\Exceptions\FxcCompilationException.cs" Link="ComputeSharp.D2D1\Shaders\Exceptions\FxcCompilationException.cs" />
<Compile Include="..\ComputeSharp.D2D1\Shaders\Interop\D2D1PixelShaderInputType.cs" Link="ComputeSharp.D2D1\Shaders\Interop\D2D1PixelShaderInputType.cs" />
<Compile Include="..\ComputeSharp.D2D1\Shaders\Translation\D3DCompiler.cs" Link="ComputeSharp.D2D1\Shaders\Translation\D3DCompiler.cs" />
<Compile Include="..\ComputeSharp.D2D1\Shaders\Translation\D3DCompiler.ID3DInclude.cs" Link="ComputeSharp.D2D1\Shaders\Translation\D3DCompiler.ID3DInclude.cs" />
<Compile Include="..\ComputeSharp.D2D1\Shaders\Translation\Headers\d2d1effecthelpers.hlsli.cs" Link="ComputeSharp.D2D1\Shaders\Translation\Headers\d2d1effecthelpers.hlsli.cs" />
@@ -1,81 +0,0 @@
using System.Collections.Immutable;
using ComputeSharp.D2D1.__Internals;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.D2D1.SourceGenerators;
/// <inheritdoc/>
partial class ID2D1ShaderGenerator
{
/// <inheritdoc/>
partial class GetInputType
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>GetInputTypeMethod</c> method.
/// </summary>
/// <param name="inputTypes">The input types for the shader.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>GetInputTypeMethod</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(ImmutableArray<uint> inputTypes)
{
// This code produces a method declaration as follows:
//
// readonly uint global::ComputeSharp.D2D1.__Internals.ID2D1Shader.GetInputType(uint index)
// {
// return <INPUT_TYPE>;
// }
return
MethodDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword)), Identifier(nameof(GetInputType)))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddParameterListParameters(Parameter(Identifier("index")).WithType(PredefinedType(Token(SyntaxKind.UIntKeyword))))
.WithBody(Block(ReturnStatement(GetInputTypesSwitchExpression(inputTypes))));
}
/// <summary>
/// Gets the expression to get the type of a given shader input from its index.
/// </summary>
/// <param name="inputTypes">The input types for the shader.</param>
/// <returns>The expression to extract the values from <paramref name="inputTypes"/>.</returns>
private static ExpressionSyntax GetInputTypesSwitchExpression(ImmutableArray<uint> inputTypes)
{
// If there are no inputs, just return an unspecified value.
if (inputTypes.IsEmpty)
{
return LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0));
}
// In order to avoid repeated branches, we can build a bitmask that stores in each
// bit whether the corresponding pixel shader input is simple or complex. This will
// allow the logic to be branchless and to just extract the target bit from the mask.
uint bitmask = 0;
for (int i = 0; i < inputTypes.Length; i++)
{
bitmask |= inputTypes[i] << i;
}
// If all inputs are simple, also just return 0
if (bitmask == 0)
{
return LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0));
}
// This code produces a bitmask flag extraction expression as follows:
//
// (<BITMASK> >> (int)index) & 1;
return
BinaryExpression(
SyntaxKind.BitwiseAndExpression,
ParenthesizedExpression(
BinaryExpression(
SyntaxKind.RightShiftExpression,
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bitmask)),
CastExpression(PredefinedType(Token(SyntaxKind.IntKeyword)), IdentifierName("index")))),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)));
}
}
}
@@ -0,0 +1,287 @@
using System;
using System.Collections.Immutable;
using ComputeSharp.D2D1.__Internals;
using ComputeSharp.SourceGeneration.Helpers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.D2D1.SourceGenerators;
/// <inheritdoc/>
partial class ID2D1ShaderGenerator
{
/// <inheritdoc/>
partial class InputTypes
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>InputTypes</c> property.
/// </summary>
/// <param name="inputTypes">The input types for the shader.</param>
/// <param name="additionalTypes">Any additional <see cref="TypeDeclarationSyntax"/> instances needed by the generated code, if needed.</param>
/// <returns>The resulting <see cref="MemberDeclarationSyntax"/> instance for the <c>InputTypes</c> property.</returns>
public static PropertyDeclarationSyntax GetSyntax(ImmutableArray<uint> inputTypes, out TypeDeclarationSyntax[] additionalTypes)
{
ExpressionSyntax memoryExpression;
// If there are no inputs, simply return a default expression.
// Otherwise, declare the memory manager and access it.
if (inputTypes.Length == 0)
{
memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword));
additionalTypes = Array.Empty<TypeDeclarationSyntax>();
}
else
{
// Create a ReadOnlyMemory<D2D1PixelShaderInputType> instance from the memory manager:
//
// InputTypesMemoryManager.Instance.Memory
memoryExpression =
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("InputTypesMemoryManager"),
IdentifierName("Instance")),
IdentifierName("Memory"));
additionalTypes = new TypeDeclarationSyntax[] { GetMemoryManagerDeclaration(inputTypes) };
}
// This code produces a method declaration as follows:
//
// readonly global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputTypes => <MEMORY_EXPRESSION>;
return
PropertyDeclaration(
GenericName(Identifier("global::System.ReadOnlyMemory"))
.AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")),
Identifier(nameof(InputTypes)))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.WithExpressionBody(ArrowExpressionClause(memoryExpression))
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
}
/// <summary>
/// Gets the memory manager declaration for the input type data.
/// </summary>
/// <param name="inputTypes">The input types for the shader.</param>
/// <returns>The memory manager declaration for the input type data.</returns>
private static TypeDeclarationSyntax GetMemoryManagerDeclaration(ImmutableArray<uint> inputTypes)
{
// Create the MemoryManager<T> declaration:
//
// /// <summary>
// /// <see cref="global::System.Buffers.MemoryManager{T}"/> implementation to get the input types.
// /// </summary>
// [global::System.CodeDom.Compiler.GeneratedCode("...", "...")]
// [global::System.Diagnostics.DebuggerNonUserCode]
// [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
// file sealed InputTypesMemoryManager : global::System.Buffers.MemoryManager<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType>
// {
// }
TypeDeclarationSyntax typeDeclaration =
ClassDeclaration("InputTypesMemoryManager")
.AddModifiers(Token(SyntaxKind.FileKeyword), Token(SyntaxKind.SealedKeyword))
.AddBaseListTypes(SimpleBaseType(
GenericName(Identifier("global::System.Buffers.MemoryManager"))
.AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType"))))
.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("/// <summary>"),
Comment("""/// A <see cref="global::System.Buffers.MemoryManager{T}"/> implementation to get the input types."""),
Comment("/// </summary>"));
using ImmutableArrayBuilder<MemberDeclarationSyntax> memberDeclarations = ImmutableArrayBuilder<MemberDeclarationSyntax>.Rent();
// Declare the singleton property to get the memory manager:
//
// /// <summary>The singleton <see cref="InputTypesMemoryManager"/> instance to use.</summary>
// public static readonly InputTypesMemoryManager Instance = new();
memberDeclarations.Add(
FieldDeclaration(
VariableDeclaration(IdentifierName("InputTypesMemoryManager"))
.AddVariables(
VariableDeclarator(Identifier("Instance"))
.WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression()))))
.AddModifiers(
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.StaticKeyword),
Token(SyntaxKind.ReadOnlyKeyword))
.WithLeadingTrivia(Comment("""/// <summary>The singleton <see cref="InputTypesMemoryManager"/> instance to use.</summary>""")));
using (ImmutableArrayBuilder<ExpressionSyntax> inputTypeExpressions = ImmutableArrayBuilder<ExpressionSyntax>.Rent())
{
// Build the sequence of expressions for all input types
foreach (uint inputType in inputTypes)
{
inputTypeExpressions.Add(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType"),
IdentifierName(inputType == 0 ? "Simple" : "Complex")));
}
// Construct the RVA span property:
//
// /// <summary>The RVA data with the input type info.</summary>
// private static global::System.ReadOnlySpan<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> Data => new[] { <INPUT_TYPES> };
memberDeclarations.Add(
PropertyDeclaration(
GenericName(Identifier("global::System.ReadOnlySpan"))
.AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")),
Identifier("Data"))
.AddModifiers(Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword))
.WithExpressionBody(
ArrowExpressionClause(
ImplicitArrayCreationExpression(
InitializerExpression(
SyntaxKind.ArrayInitializerExpression,
SeparatedList(inputTypeExpressions.ToArray())))))
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
.WithLeadingTrivia(Comment("/// <summary>The RVA data with the input type info.</summary>")));
}
// Add the GetSpan() method:
//
// /// <inheritdoc/>
// public override unsafe global::System.Span<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> 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(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")),
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("Data"),
IdentifierName("Length"))))))
.WithLeadingTrivia(Comment("/// <inheritdoc/>")));
// Override the Memory<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> property:
//
// /// <inheritdoc/>
// public override global::System.Memory<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> 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(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")),
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("/// <inheritdoc/>")));
// Add the Pin(int elementIndex) method:
//
// /// <inheritdoc/>
// 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("/// <inheritdoc/>")));
// 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("/// <inheritdoc/>")));
// 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("/// <inheritdoc/>")));
return typeDeclaration.AddMembers(memberDeclarations.ToArray());
}
}
}
@@ -12,9 +12,9 @@ namespace ComputeSharp.D2D1.SourceGenerators;
partial class ID2D1ShaderGenerator
{
/// <summary>
/// A helper with all logic to generate the <c>GetInputType</c> method.
/// A helper with all logic to generate the <c>InputTypes</c> properties.
/// </summary>
private static partial class GetInputType
private static partial class InputTypes
{
/// <summary>
/// Extracts the input info for the current shader.
+7 -5
ファイルの表示
@@ -38,13 +38,15 @@ partial class ID2D1ShaderGenerator
/// Creates a <see cref="CompilationUnitSyntax"/> instance wrapping the given method.
/// </summary>
/// <param name="hierarchyInfo">The <see cref="HierarchyInfo"/> instance for the current type.</param>
/// <param name="memberDeclarationSyntax">The <see cref="MemberDeclarationSyntax"/> item to insert.</param>
/// <param name="memberDeclaration">The <see cref="MemberDeclarationSyntax"/> item to insert.</param>
/// <param name="canUseSkipLocalsInit">Whether <c>[SkipLocalsInit]</c> can be used.</param>
/// <returns>A <see cref="CompilationUnitSyntax"/> object wrapping <paramref name="memberDeclarationSyntax"/>.</returns>
/// <param name="additionalMemberDeclarations">Additional member declarations to also emit, if any.</param>
/// <returns>A <see cref="CompilationUnitSyntax"/> object wrapping <paramref name="memberDeclaration"/>.</returns>
private static CompilationUnitSyntax GetCompilationUnitFromMember(
HierarchyInfo hierarchyInfo,
MemberDeclarationSyntax memberDeclarationSyntax,
bool canUseSkipLocalsInit)
MemberDeclarationSyntax memberDeclaration,
bool canUseSkipLocalsInit,
params MemberDeclarationSyntax[] additionalMemberDeclarations)
{
// Method attributes
List<AttributeListSyntax> attributes = new()
@@ -71,6 +73,6 @@ partial class ID2D1ShaderGenerator
attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit")))));
}
return hierarchyInfo.GetSyntax(memberDeclarationSyntax.AddAttributeLists(attributes.ToArray()));
return hierarchyInfo.GetSyntax(new MemberDeclarationSyntax[] { memberDeclaration.AddAttributeLists(attributes.ToArray()) }, additionalMemberDeclarations);
}
}
+7 -7
ファイルの表示
@@ -91,8 +91,8 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
token.ThrowIfCancellationRequested();
// Get the input info for GetInputInfo()
GetInputType.GetInfo(
// Get the input info for InputTypes
InputTypes.GetInfo(
diagnostics,
typeSymbol,
out int inputCount,
@@ -257,18 +257,18 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(GetInputCount)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the GetInputType() info (hierarchy and input types)
// Get the InputTypes info (hierarchy and input types)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, InputTypesInfo InputTypes)> inputTypesInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.InputTypes));
// Generate the GetInputType() methods
// Generate the InputTypes properties
context.RegisterSourceOutput(inputTypesInfo, static (context, item) =>
{
MethodDeclarationSyntax getInputTypeMethod = GetInputType.GetSyntax(item.InputTypes.InputTypes);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, getInputTypeMethod, canUseSkipLocalsInit: false);
MemberDeclarationSyntax inputTypesProperty = InputTypes.GetSyntax(item.InputTypes.InputTypes, out TypeDeclarationSyntax[] additionalTypes);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, inputTypesProperty, canUseSkipLocalsInit: false, additionalMemberDeclarations: additionalTypes);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(GetInputType)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(InputTypes)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the LoadResourceTextureDescriptions() info (hierarchy and resource texture descriptions)
+3 -5
ファイルの表示
@@ -1,6 +1,7 @@
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using ComputeSharp.D2D1.Interop;
namespace ComputeSharp.D2D1.__Internals;
@@ -77,14 +78,11 @@ public interface ID2D1Shader
uint GetInputCount();
/// <summary>
/// Gets the input type for the input at the input index.
/// Gets the input types for the current shader.
/// </summary>
/// <param name="index">The index of the shader input to get the type for.</param>
/// <returns>The type of input at the specified index.</returns>
/// <remarks>The return value if the input is out of range is undefined.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be used directly by user code")]
uint GetInputType(uint index);
ReadOnlyMemory<D2D1PixelShaderInputType> InputTypes { get; }
/// <summary>
/// Loads the input descriptions for the shader, if any.
+5 -9
ファイルの表示
@@ -259,20 +259,16 @@ public static class D2D1PixelShader
}
/// <summary>
/// Gets the type of a given input for a D2D1 pixel shader.
/// Gets the input types for a D2D1 pixel shader.
/// </summary>
/// <typeparam name="T">The type of D2D1 pixel shader to get the input type for.</typeparam>
/// <param name="index">The index of the input to get the type for.</param>
/// <returns>The type of the input of the target D2D1 pixel shader at the specified index.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="index"/> is not in range for the available inputs for the shader type.</exception>
public static D2D1PixelShaderInputType GetInputType<T>(int index)
/// <typeparam name="T">The type of D2D1 pixel shader to get the input types for.</typeparam>
/// <returns>The input types of the target D2D1 pixel shader.</returns>
public static ReadOnlyMemory<D2D1PixelShaderInputType> GetInputTypes<T>()
where T : unmanaged, ID2D1PixelShader
{
Unsafe.SkipInit(out T shader);
default(ArgumentOutOfRangeException).ThrowIfNotInRange(index, 0, (int)shader.GetInputCount());
return (D2D1PixelShaderInputType)shader.GetInputType((uint)index);
return shader.InputTypes;
}
/// <summary>
+1 -4
ファイルの表示
@@ -175,10 +175,7 @@ internal unsafe partial struct PixelShaderEffect
int inputCount = D2D1PixelShader.GetInputCount<T>();
D2D1PixelShaderInputType* inputTypes = (D2D1PixelShaderInputType*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For<T>), sizeof(D2D1PixelShaderInputType) * inputCount);
for (int i = 0; i < inputCount; i++)
{
inputTypes[i] = D2D1PixelShader.GetInputType<T>(i);
}
D2D1PixelShader.GetInputTypes<T>().Span.CopyTo(new Span<D2D1PixelShaderInputType>(inputTypes, inputCount));
// Prepare the input descriptions
ReadOnlyMemory<D2D1InputDescription> inputDescriptionsInfo = D2D1PixelShader.GetInputDescriptions<T>();
+39 -16
ファイルの表示
@@ -1,3 +1,4 @@
using System;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using Microsoft.CodeAnalysis;
@@ -47,6 +48,17 @@ internal sealed partial record HierarchyInfo(string FullyQualifiedMetadataName,
/// <param name="memberDeclarations">The member declarations to add to the generated type.</param>
/// <returns>A <see cref="CompilationUnitSyntax"/> instance for the current hierarchy.</returns>
public CompilationUnitSyntax GetSyntax(params MemberDeclarationSyntax[] memberDeclarations)
{
return GetSyntax(memberDeclarations, Array.Empty<MemberDeclarationSyntax>());
}
/// <summary>
/// Creates a <see cref="CompilationUnitSyntax"/> instance for the current hierarchy.
/// </summary>
/// <param name="memberDeclarations">The member declarations to add to the generated type.</param>
/// <param name="additionalMemberDeclarations">Additional top-level member declarations, if any.</param>
/// <returns>A <see cref="CompilationUnitSyntax"/> instance for the current hierarchy.</returns>
public CompilationUnitSyntax GetSyntax(MemberDeclarationSyntax[] memberDeclarations, params MemberDeclarationSyntax[] additionalMemberDeclarations)
{
// Create the partial type declaration with for the current hierarchy.
// This code produces a type declaration as follows:
@@ -78,6 +90,8 @@ internal sealed partial record HierarchyInfo(string FullyQualifiedMetadataName,
Comment("// <auto-generated/>"),
Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true)));
CompilationUnitSyntax compilationUnitSyntax;
if (Namespace is "")
{
// If there is no namespace, attach the pragma directly to the declared type,
@@ -85,24 +99,33 @@ internal sealed partial record HierarchyInfo(string FullyQualifiedMetadataName,
//
// <SYNTAX_TRIVIA>
// <TYPE_HIERARCHY>
return
compilationUnitSyntax =
CompilationUnit()
.AddMembers(typeDeclarationSyntax.WithLeadingTrivia(syntaxTriviaList))
.NormalizeWhitespace(eol: "\n");
.AddMembers(typeDeclarationSyntax.WithLeadingTrivia(syntaxTriviaList));
}
else
{
// Create the compilation unit with disabled warnings, target namespace and generated type.
// This will produce code as follows:
//
// <SYNTAX_TRIVIA>
// namespace <NAMESPACE>;
//
// <TYPE_HIERARCHY>
compilationUnitSyntax =
CompilationUnit().AddMembers(
FileScopedNamespaceDeclaration(IdentifierName(Namespace))
.WithLeadingTrivia(syntaxTriviaList)
.AddMembers(typeDeclarationSyntax));
}
// Create the compilation unit with disabled warnings, target namespace and generated type.
// This will produce code as follows:
//
// <SYNTAX_TRIVIA>
// namespace <NAMESPACE>;
//
// <TYPE_HIERARCHY>
return
CompilationUnit().AddMembers(
FileScopedNamespaceDeclaration(IdentifierName(Namespace))
.WithLeadingTrivia(syntaxTriviaList)
.AddMembers(typeDeclarationSyntax))
.NormalizeWhitespace(eol: "\n");
// Add any additional members, if any
if (additionalMemberDeclarations.Length > 0)
{
compilationUnitSyntax = compilationUnitSyntax.AddMembers(additionalMemberDeclarations);
}
// Normalize and return the tree
return compilationUnitSyntax.NormalizeWhitespace(eol: "\n");
}
}
+33 -7
ファイルの表示
@@ -23,14 +23,40 @@ public partial class D2D1PixelShaderTests
}
[TestMethod]
public unsafe void GetInputType()
public unsafe void GetInputTypes_NoInputs()
{
Assert.AreEqual(D2D1PixelShader.GetInputType<ShaderWithMultipleInputs>(0), D2D1PixelShaderInputType.Simple);
Assert.AreEqual(D2D1PixelShader.GetInputType<ShaderWithMultipleInputs>(1), D2D1PixelShaderInputType.Complex);
Assert.AreEqual(D2D1PixelShader.GetInputType<ShaderWithMultipleInputs>(2), D2D1PixelShaderInputType.Simple);
Assert.AreEqual(D2D1PixelShader.GetInputType<ShaderWithMultipleInputs>(3), D2D1PixelShaderInputType.Complex);
Assert.AreEqual(D2D1PixelShader.GetInputType<ShaderWithMultipleInputs>(4), D2D1PixelShaderInputType.Complex);
Assert.AreEqual(D2D1PixelShader.GetInputType<ShaderWithMultipleInputs>(5), D2D1PixelShaderInputType.Complex);
ReadOnlyMemory<D2D1PixelShaderInputType> inputTypes = D2D1PixelShader.GetInputTypes<ZonePlateEffect>();
Assert.AreEqual(0, inputTypes.Length);
Assert.IsFalse(MemoryMarshal.TryGetMemoryManager(inputTypes, out MemoryManager<D2D1PixelShaderInputType>? _));
}
[TestMethod]
public unsafe void GetInputTypes_MultipleInputs()
{
CollectionAssert.AreEqual(new[]
{
D2D1PixelShaderInputType.Simple,
D2D1PixelShaderInputType.Complex,
D2D1PixelShaderInputType.Simple,
D2D1PixelShaderInputType.Complex,
D2D1PixelShaderInputType.Complex,
D2D1PixelShaderInputType.Complex,
D2D1PixelShaderInputType.Simple
}, D2D1PixelShader.GetInputTypes<ShaderWithMultipleInputs>().ToArray());
}
[TestMethod]
public unsafe void GetInputTypes_SameManager()
{
ReadOnlyMemory<D2D1PixelShaderInputType> inputTypes1 = D2D1PixelShader.GetInputTypes<ShaderWithMultipleInputs>();
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(inputTypes1, out MemoryManager<D2D1PixelShaderInputType>? memoryManager1));
ReadOnlyMemory<D2D1PixelShaderInputType> inputTypes2 = D2D1PixelShader.GetInputTypes<ShaderWithMultipleInputs>();
Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(inputTypes2, out MemoryManager<D2D1PixelShaderInputType>? memoryManager2));
Assert.AreSame(memoryManager1, memoryManager2);
}
[D2DInputCount(7)]