diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs new file mode 100644 index 00000000..fcdb1248 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs @@ -0,0 +1,127 @@ +using System.Collections.Immutable; +using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.SourceGenerators.Models; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + partial class InitializeFromDispatchData + { + /// + /// Creates a instance for the InitializeFromDispatchData method. + /// + /// The dispatch info gathered for the current shader. + /// The resulting instance for the InitializeFromDispatchData method. + public static MethodDeclarationSyntax GetSyntax(DispatchDataInfo dispatchInfo) + { + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InitializeFromDispatchData(global::System.ReadOnlySpan data) + // { + // + // } + return + MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("InitializeFromDispatchData")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) + .AddParameterListParameters(Parameter(Identifier("data")).WithType( + GenericName(Identifier("global::System.ReadOnlySpan")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))) + .WithBody(Block(GetDispatchDataUnloadingStatements(dispatchInfo.FieldInfos))); + } + + /// + /// Gets a sequence of statements to initialize a shader from a serialized dispatch data buffer. + /// + /// The array of values for all captured fields. + /// The sequence of instances to initialize a shader from the serialized dispatch data buffer. + private static ImmutableArray GetDispatchDataUnloadingStatements(ImmutableArray fieldInfos) + { + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + + // Insert the fallback for empty shaders. This will generate the following code: + // + // if (data.IsEmpty) + // { + // return; + // } + statements.Add( + IfStatement( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("data"), + IdentifierName("IsEmpty")), + Block(ReturnStatement()))); + + // ref byte r0 = ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(data); + statements.Add( + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"), + IdentifierName("GetReference"))) + .AddArgumentListArguments(Argument(IdentifierName("data"))))))))); + + // Generate loading statements for each captured field + foreach (FieldInfo fieldInfo in fieldInfos) + { + switch (fieldInfo) + { + case FieldInfo.Primitive primitive: + + // Read a primitive value from the target buffer. This will generate: + // + // Unsafe.AsRef(in ) = global::System.Runtime.CompilerServices.Unsafe.As>( + // ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint))) + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", primitive.FieldPath)})"), + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))")))); + break; + + case FieldInfo.NonLinearMatrix matrix: + string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}"; + string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0"; + + // Declare a local to index into individual rows. This will generate: + // + // ref = ref global::System.Runtime.CompilerServices.Unsafe.As, >( + // ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in )); + statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));")); + + // Generate the loading code for each individual row, with proper alignment. + // This will result in the following (assuming Float2x3 m): + // + // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m)); + // global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0) = global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)); + // global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1) = global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))); + for (int j = 0; j < matrix.Rows; j++) + { + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})"), + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))")))); + } + break; + } + } + + return statements.ToImmutable(); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index e05a6d25..848298d9 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -79,7 +79,7 @@ partial class ID2D1ShaderGenerator // This will result in the following (assuming Float2x3 m): // // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m)); - // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0); + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0); // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1); for (int j = 0; j < matrix.Rows; j++) { @@ -93,14 +93,14 @@ partial class ID2D1ShaderGenerator } } - // global::System.Span span0 = stackalloc uint[]; + // global::System.Span data = stackalloc uint[]; statements.Insert(0, LocalDeclarationStatement( VariableDeclaration( GenericName(Identifier("global::System.Span")) .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword)))) .AddVariables( - VariableDeclarator(Identifier("span0")) + VariableDeclarator(Identifier("data")) .WithInitializer(EqualsValueClause( StackAllocArrayCreationExpression( ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword))) @@ -108,7 +108,7 @@ partial class ID2D1ShaderGenerator ArrayRankSpecifier(SingletonSeparatedList( LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount))))))))))); - // ref uint r0 = ref span0[0]; + // ref uint r0 = ref data[0]; statements.Insert(1, LocalDeclarationStatement( VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword)))) @@ -116,13 +116,13 @@ partial class ID2D1ShaderGenerator VariableDeclarator(Identifier("r0")) .WithInitializer(EqualsValueClause( RefExpression( - ElementAccessExpression(IdentifierName("span0")) + ElementAccessExpression(IdentifierName("data")) .AddArgumentListArguments(Argument( LiteralExpression( SyntaxKind.NumericLiteralExpression, Literal(0)))))))))); - // loader.LoadConstantBuffer(span0); + // loader.LoadConstantBuffer(data); statements.Add( ExpressionStatement( InvocationExpression( @@ -130,7 +130,7 @@ partial class ID2D1ShaderGenerator SyntaxKind.SimpleMemberAccessExpression, IdentifierName("loader"), IdentifierName("LoadConstantBuffer"))) - .AddArgumentListArguments(Argument(IdentifierName("span0"))))); + .AddArgumentListArguments(Argument(IdentifierName("data"))))); return statements.ToImmutable(); } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index 5d7dd509..aac82e56 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -119,6 +119,15 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadDispatchData)}", compilationUnit.ToFullString()); }); + // Generate the InitializeFromDispatchData() methods + context.RegisterSourceOutput(dispatchDataInfo, static (context, item) => + { + MethodDeclarationSyntax loadDispatchDataMethod = InitializeFromDispatchData.GetSyntax(item.Dispatch); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, loadDispatchDataMethod, false); + + context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(InitializeFromDispatchData)}", compilationUnit.ToFullString()); + }); + // Get the filtered sequence to enable caching IncrementalValuesProvider<(HierarchyInfo Hierarchy, string HlslSource)> hlslSourceInfo = shaderInfo diff --git a/src/ComputeSharp.D2D1/Interfaces/ID2D1DrawTransformMapper.cs b/src/ComputeSharp.D2D1/Interfaces/ID2D1TransformMapper{T}.cs similarity index 64% rename from src/ComputeSharp.D2D1/Interfaces/ID2D1DrawTransformMapper.cs rename to src/ComputeSharp.D2D1/Interfaces/ID2D1TransformMapper{T}.cs index f026098a..ef12cbe1 100644 --- a/src/ComputeSharp.D2D1/Interfaces/ID2D1DrawTransformMapper.cs +++ b/src/ComputeSharp.D2D1/Interfaces/ID2D1TransformMapper{T}.cs @@ -6,11 +6,44 @@ namespace ComputeSharp.D2D1; /// /// An providing support for custom, stateful draw transform mappings for shaders. /// -public interface ID2D1DrawTransformMapper +public interface ID2D1TransformMapper + where T : unmanaged, ID2D1PixelShader { + /// + /// + /// Allows a transform to state how it would map a a set of sample rectangles on its input to an output rectangle. + /// + /// + /// This is effectively the inverse mapping of . + /// + /// + /// The input D2D1 pixel shader being executed on the current effect (this can be used to retrieve shader properties). + /// The input rectangles to be mapped to the output rectangle. This parameter is always equal to the input bounds. + /// The input rectangles to be mapped to the opaque output rectangle. + /// The output rectangle that maps to the corresponding input rectangle. + /// The output rectangle that maps to the corresponding opaque input rectangle. + /// + /// + /// Unlike and , this method is explicitly called by the renderer at + /// a determined place in its rendering algorithm. The transform implementation may change its state based on the input rectangles + /// and use this information to control its rendering information. This method is always called before the + /// and methods. + /// + /// + /// For more info, see . + /// + /// + void MapInputsToOutput( + in T shader, + ReadOnlySpan inputs, + ReadOnlySpan opaqueInputs, + out Rectangle output, + out Rectangle opaqueOutput); + /// /// Allows a transform to state how it would map a rectangle requested on its output to a set of sample rectangles on its input. /// + /// The input D2D1 pixel shader being executed on the current effect (this can be used to retrieve shader properties). /// The output rectangle from which the inputs must be mapped. /// The corresponding set of inputs. The inputs will directly correspond to the transform inputs. /// @@ -23,31 +56,12 @@ public interface ID2D1DrawTransformMapper /// For more info, see . /// /// - void MapOutputToInputs(in Rectangle output, Span inputs); - - /// - /// Performs the inverse mapping of . - /// - /// The input rectangles to be mapped to the output rectangle. This parameter is always equal to the input bounds. - /// The input rectangles to be mapped to the opaque output rectangle. - /// The output rectangle that maps to the corresponding input rectangle. - /// The output rectangle that maps to the corresponding opaque input rectangle. - /// - /// - /// Unlike and , this - /// method is explicitly called by the renderer at a determined place in its rendering algorithm. The transform implementation may change its state - /// based on the input rectangles and use this information to control its rendering information. This method is always called before the - /// and methods. - /// - /// - /// For more info, see . - /// - /// - void MapInputsToOutput(ReadOnlySpan inputs, ReadOnlySpan opaqueInputs, out Rectangle output, out Rectangle opaqueOutput); + void MapOutputToInputs(in T shader, in Rectangle output, Span inputs); /// /// Sets the input rectangles for this rendering pass into the transform. /// + /// The input D2D1 pixel shader being executed on the current effect (this can be used to retrieve shader properties). /// The index of the input rectangle. /// The invalid input rectangle. /// The output rectangle to which the input rectangle must be mapped. @@ -55,12 +69,12 @@ public interface ID2D1DrawTransformMapper /// /// The transform implementation must regard this method as purely functional. The transform implementation can base the mapped input rectangle on /// the transform implementation's current state as specified by the encapsulating effect properties. But the transform implementation can't change - /// its own state in response to a call to . Direct2D can call this method at any time - /// and in any sequence following a call to . + /// its own state in response to a call to . Direct2D can call this method at any time + /// and in any sequence following a call to . /// /// /// For more info, see . /// /// - void MapInvalidOutput(int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput); + void MapInvalidOutput(in T shader, int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput); } diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs index da52d5db..ef8f36db 100644 --- a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs +++ b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs @@ -10,6 +10,22 @@ namespace ComputeSharp.D2D1.__Internals; [Obsolete("This interface is not intended to be used directly by user code")] public interface ID2D1Shader { + /// + /// Initializes the current shader from a buffer with the serialized dispatch data. + /// + /// The input buffer with the serialized dispatch data. + /// The input buffer must be retrieved from . + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + void InitializeFromDispatchData(ReadOnlySpan data) +#if NET6_0_OR_GREATER + { + throw new NotImplementedException(); + } +#else + ; +#endif + /// /// Loads the dispatch data for the shader. /// diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.Effects.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.Effects.cs index 4907311c..3be601a8 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.Effects.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.Effects.cs @@ -34,13 +34,13 @@ unsafe partial class D2D1InteropServices /// Registers an effect from an input D2D1 pixel shader, by calling ID2D1Factory1::RegisterEffectFromString. /// /// The type of D2D1 pixel shader to register. - /// The type of implementation to register. + /// The type of implementation to register. /// A pointer to the ID2D1Factory1 instance to use. /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. /// For more info, see . public static unsafe void RegisterPixelShaderEffectForD2D1Factory1(void* d2D1Factory1, out Guid effectId) where T : unmanaged, ID2D1PixelShader - where TMapper : class, ID2D1DrawTransformMapper, new() + where TMapper : class, ID2D1TransformMapper, new() { RegisterPixelShaderEffectForD2D1Factory1(d2D1Factory1, static () => new TMapper(), out effectId); } @@ -50,10 +50,10 @@ unsafe partial class D2D1InteropServices /// /// The type of D2D1 pixel shader to register. /// A pointer to the ID2D1Factory1 instance to use. - /// An optional factory of instances to use for the transform. + /// An optional factory of instances to use for the transform. /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. /// For more info, see . - public static unsafe void RegisterPixelShaderEffectForD2D1Factory1(void* d2D1Factory1, Func? mapperFactory, out Guid effectId) + public static unsafe void RegisterPixelShaderEffectForD2D1Factory1(void* d2D1Factory1, Func>? mapperFactory, out Guid effectId) where T : unmanaged, ID2D1PixelShader { effectId = default; diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/D2D1TransformMapper.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/D2D1TransformMapper.cs new file mode 100644 index 00000000..7a60e8d4 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/D2D1TransformMapper.cs @@ -0,0 +1,106 @@ +using System; +using System.Drawing; +using System.Runtime.CompilerServices; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.Interop.Effects; + +/// +/// A base type to support non-generic uses. +/// +internal abstract class D2D1TransformMapper +{ + /// + /// The buffer with the serialized shader dispatch data, if any. + /// The input rectangles to be mapped to the output rectangle. This parameter is always equal to the input bounds. + /// The input rectangles to be mapped to the opaque output rectangle. + /// The output rectangle that maps to the corresponding input rectangle. + /// The output rectangle that maps to the corresponding opaque input rectangle. + public abstract void MapInputsToOutput( + ReadOnlySpan buffer, + ReadOnlySpan inputs, + ReadOnlySpan opaqueInputs, + out Rectangle output, + out Rectangle opaqueOutput); + + /// + /// The buffer with the serialized shader dispatch data, if any. + /// The output rectangle from which the inputs must be mapped. + /// The corresponding set of inputs. The inputs will directly correspond to the transform inputs. + public abstract void MapOutputToInputs(ReadOnlySpan buffer, in Rectangle output, Span inputs); + + /// + /// The buffer with the serialized shader dispatch data, if any. + /// The index of the input rectangle. + /// The invalid input rectangle. + /// The output rectangle to which the input rectangle must be mapped. + public abstract void MapInvalidOutput(ReadOnlySpan buffer, int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput); + + /// + /// A generic implementation for a specific shader type. + /// + /// The target shader type. + public sealed class For : D2D1TransformMapper + where T : unmanaged, ID2D1PixelShader + { + /// + /// The instance to use. + /// + private readonly ID2D1TransformMapper transformMapper; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance to use. + private For(ID2D1TransformMapper transformMapper) + { + this.transformMapper = transformMapper; + } + + /// + /// Creates a new instance for a given transform mapper, if there is one. + /// + /// The instance to usse, if there is one. + /// A new instance wrapping , or . + public static For? Get(ID2D1TransformMapper? transformMapper) + { + if (transformMapper is null) + { + return null; + } + + return new(transformMapper); + } + + /// + public override void MapInputsToOutput(ReadOnlySpan buffer, ReadOnlySpan inputs, ReadOnlySpan opaqueInputs, out Rectangle output, out Rectangle opaqueOutput) + { + Unsafe.SkipInit(out T shader); + + shader.InitializeFromDispatchData(buffer); + + this.transformMapper.MapInputsToOutput(in shader, inputs, opaqueInputs, out output, out opaqueOutput); + } + + /// + public override void MapOutputToInputs(ReadOnlySpan buffer, in Rectangle output, Span inputs) + { + Unsafe.SkipInit(out T shader); + + shader.InitializeFromDispatchData(buffer); + + this.transformMapper.MapOutputToInputs(in shader, in output, inputs); + } + + /// + public override void MapInvalidOutput(ReadOnlySpan buffer, int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput) + { + Unsafe.SkipInit(out T shader); + + shader.InitializeFromDispatchData(buffer); + + this.transformMapper.MapInvalidOutput(in shader, inputIndex, invalidInput, out invalidOutput); + } + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs index 7ea4cce1..a40b0bc6 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs @@ -127,7 +127,7 @@ partial struct PixelShaderEffect return E.E_INVALIDARG; } - if (@this->d2D1DrawTransformMapperFactoryHandle.Target is ID2D1DrawTransformMapper d2D1DrawTransformMapper) + if (@this->d2D1TransformMapperHandle.Target is D2D1TransformMapper d2D1TransformMapper) { Rectangle output = outputRect->ToRectangle(); Span inputs = stackalloc Rectangle[8].Slice(0, (int)inputRectsCount); @@ -137,10 +137,12 @@ partial struct PixelShaderEffect inputs[i] = inputRects[i].ToRectangle(); } + ReadOnlySpan buffer = new(@this->constantBuffer, @this->constantBufferSize); + // Invoke MapOutputToInputs and handle exceptions so they don't cross the ABI boundary try { - d2D1DrawTransformMapper.MapOutputToInputs(in output, inputs); + d2D1TransformMapper.MapOutputToInputs(buffer, in output, inputs); } catch (Exception e) { @@ -175,7 +177,7 @@ partial struct PixelShaderEffect return E.E_INVALIDARG; } - if (@this->d2D1DrawTransformMapperFactoryHandle.Target is ID2D1DrawTransformMapper d2D1DrawTransformMapper) + if (@this->d2D1TransformMapperHandle.Target is D2D1TransformMapper d2D1TransformMapper) { Span inputs = stackalloc Rectangle[8].Slice(0, (int)inputRectCount); Span opaqueInputs = stackalloc Rectangle[8].Slice(0, (int)inputRectCount); @@ -186,13 +188,15 @@ partial struct PixelShaderEffect opaqueInputs[i] = inputOpaqueSubRects[i].ToRectangle(); } + ReadOnlySpan buffer = new(@this->constantBuffer, @this->constantBufferSize); + Rectangle output; Rectangle opaqueOutput; // Handle exceptions, as mentioned above try { - d2D1DrawTransformMapper.MapInputsToOutput(inputs, opaqueInputs, out output, out opaqueOutput); + d2D1TransformMapper.MapInputsToOutput(buffer, inputs, opaqueInputs, out output, out opaqueOutput); } catch (Exception e) { @@ -230,15 +234,17 @@ partial struct PixelShaderEffect { @this = (PixelShaderEffect*)&((void**)@this)[-1]; - if (@this->d2D1DrawTransformMapperFactoryHandle.Target is ID2D1DrawTransformMapper d2D1DrawTransformMapper) + if (@this->d2D1TransformMapperHandle.Target is D2D1TransformMapper d2D1TransformMapper) { Rectangle invalidInput = invalidInputRect.ToRectangle(); Rectangle invalidOutput; + ReadOnlySpan buffer = new(@this->constantBuffer, @this->constantBufferSize); + // Handle exceptions once again try { - d2D1DrawTransformMapper.MapInvalidOutput((int)inputIndex, invalidInput, out invalidOutput); + d2D1TransformMapper.MapInvalidOutput(buffer, (int)inputIndex, invalidInput, out invalidOutput); } catch (Exception e) { diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs index 01307788..5d9c40e9 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs @@ -97,16 +97,16 @@ internal unsafe partial struct PixelShaderEffect private static int bytecodeSize; /// - /// The factory of instances to use for each created effect. + /// The factory of instances to use for each created effect. /// - private static Func? d2D1DrawTransformMapperFactory; + private static Func>? d2D1DrawTransformMapperFactory; /// /// Initializes the shared state. /// - /// The factory of instances to use for each created effect. + /// The factory of instances to use for each created effect. /// Thrown if initialization is attempted with a mismatched transform factory. - public static void Initialize(Func? factory) + public static void Initialize(Func>? factory) { // This conceptually acts as a static constructor, and this type is // internal, so in this very specific case locking on the type is fine. @@ -161,9 +161,15 @@ internal unsafe partial struct PixelShaderEffect /// private static int CreateEffect(IUnknown** effectImpl) { - ID2D1DrawTransformMapper? d2D1DrawTransformMapper = d2D1DrawTransformMapperFactory?.Invoke(); + ID2D1TransformMapper? d2D1DrawTransformMapper = d2D1DrawTransformMapperFactory?.Invoke(); - return PixelShaderEffect.Factory(shaderId, numberOfInputs, bytecode, bytecodeSize, d2D1DrawTransformMapper, effectImpl); + return PixelShaderEffect.Factory( + shaderId, + numberOfInputs, + bytecode, + bytecodeSize, + D2D1TransformMapper.For.Get(d2D1DrawTransformMapper), + effectImpl); } } @@ -272,9 +278,9 @@ internal unsafe partial struct PixelShaderEffect private int bytecodeSize; /// - /// The handle for the instance in use, if any. + /// The handle for the instance in use, if any. /// - private GCHandle d2D1DrawTransformMapperFactoryHandle; + private GCHandle d2D1TransformMapperHandle; /// /// The current input rectangle. @@ -293,7 +299,7 @@ internal unsafe partial struct PixelShaderEffect /// The number of inputs for the shader. /// The shader bytecode. /// The size of . - /// The instance to use for the effect. + /// The instance to use for the effect. /// The resulting effect instance. /// This always returns 0. private static int Factory( @@ -301,7 +307,7 @@ internal unsafe partial struct PixelShaderEffect int numberOfInputs, byte* bytecode, int bytecodeSize, - ID2D1DrawTransformMapper? d2D1DrawTransformMapper, + D2D1TransformMapper? d2D1TransformMapper, IUnknown** effectImpl) { PixelShaderEffect* @this = (PixelShaderEffect*)NativeMemory.Alloc((nuint)sizeof(PixelShaderEffect)); @@ -315,7 +321,7 @@ internal unsafe partial struct PixelShaderEffect @this->numberOfInputs = numberOfInputs; @this->bytecode = bytecode; @this->bytecodeSize = bytecodeSize; - @this->d2D1DrawTransformMapperFactoryHandle = GCHandle.Alloc(d2D1DrawTransformMapper); + @this->d2D1TransformMapperHandle = GCHandle.Alloc(d2D1TransformMapper); *effectImpl = (IUnknown*)@this; @@ -419,7 +425,7 @@ internal unsafe partial struct PixelShaderEffect NativeMemory.Free(this.constantBuffer); } - this.d2D1DrawTransformMapperFactoryHandle.Free(); + this.d2D1TransformMapperHandle.Free(); NativeMemory.Free(Unsafe.AsPointer(ref this)); } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index efee70cc..006f1058 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -148,7 +148,7 @@ partial class IShaderGenerator // This will result in the following (assuming Float2x3 m): // // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m)); - // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0); + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0); // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1); for (int j = 0; j < matrix.Rows; j++) {