diff --git a/src/ComputeSharp.D2D1/Interfaces/ID2D1TransformMapperFactory{T}.cs b/src/ComputeSharp.D2D1/Interfaces/ID2D1TransformMapperFactory{T}.cs deleted file mode 100644 index a5b122ea..00000000 --- a/src/ComputeSharp.D2D1/Interfaces/ID2D1TransformMapperFactory{T}.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace ComputeSharp.D2D1; - -/// -/// An acting as a factory for instances. -/// -/// The type of shader this factory creates transform mapper instances for. -public interface ID2D1TransformMapperFactory - where T : unmanaged, ID2D1PixelShader -{ - /// - /// Creates a new instance for a given shader. - /// - /// A new instance for the input shader. - ID2D1TransformMapper Create(); -} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Interfaces/ID2D1TransformMapper{T}.cs b/src/ComputeSharp.D2D1/Interfaces/ID2D1TransformMapper{T}.cs deleted file mode 100644 index 7d4ae285..00000000 --- a/src/ComputeSharp.D2D1/Interfaces/ID2D1TransformMapper{T}.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; -using System.Drawing; - -namespace ComputeSharp.D2D1; - -/// -/// An providing support for custom, stateful draw transform mappings for shaders. -/// -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 output rectangle from which the inputs must be mapped. - /// The corresponding set of inputs. The inputs will directly correspond to the transform inputs. - /// - /// - /// The transform implementation must regard this method as purely functional. It can base the mapped input and output rectangles on its - /// current state as specified by the encapsulating effect properties. However, it must not change its own state in response to this method - /// being invoked. The Direct2D renderer implementation reserves the right to call this method at any time and in any sequence. - /// - /// - /// For more info, see . - /// - /// - void MapOutputToInputs(in Rectangle output, Span inputs); - - /// - /// Sets the input rectangles for this rendering pass into the transform. - /// - /// The index of the input rectangle. - /// The invalid input rectangle. - /// The output rectangle to which the input rectangle must be mapped. - /// - /// - /// 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 . - /// - /// - /// For more info, see . - /// - /// - void MapInvalidOutput(int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput); -} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1DrawInfoUpdateContext{T}.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1DrawInfoUpdateContext{T}.cs new file mode 100644 index 00000000..e725eaa1 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1DrawInfoUpdateContext{T}.cs @@ -0,0 +1,68 @@ +using System.Buffers; +using System.Runtime.CompilerServices; +using ComputeSharp.D2D1.Extensions; +using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; +using ComputeSharp.D2D1.Shaders.Loaders; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.Interop; + +/// +/// An object allowing to interact with the shader data from within a transform. +/// +/// The type of shader the transform will interact with. +public readonly unsafe ref struct D2D1DrawInfoUpdateContext + where T : unmanaged, ID2D1PixelShader +{ + /// + /// The instance associated with the current object. + /// + private readonly ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance associated with the current object. + internal D2D1DrawInfoUpdateContext(ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext) + { + this.d2D1DrawInfoUpdateContext = d2D1DrawInfoUpdateContext; + } + + /// + /// Retrieves the instance currently being used in the associated effect. + /// + /// The instance currently being used in the associated effect. + public T GetConstantBuffer() + { + uint constantBufferSize; + + this.d2D1DrawInfoUpdateContext->GetConstantBufferSize(&constantBufferSize).Assert(); + + byte[] buffer = ArrayPool.Shared.Rent((int)constantBufferSize); + + fixed (byte* pBuffer = buffer) + { + this.d2D1DrawInfoUpdateContext->GetConstantBuffer(pBuffer, constantBufferSize).Assert(); + } + + Unsafe.SkipInit(out T shader); + + shader.InitializeFromDispatchData(buffer); + + ArrayPool.Shared.Return(buffer); + + return shader; + } + + /// + /// Updates the instance to be used in the associated effect. + /// + /// The instance to be used in the associated effect. + public void SetConstantBuffer(in T shader) + { + D2D1DrawInfoUpdateContextDispatchDataLoader dataLoader = new(this.d2D1DrawInfoUpdateContext); + + Unsafe.AsRef(in shader).LoadDispatchData(ref dataLoader); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs index 4e88db45..b0b63c86 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs @@ -5,6 +5,7 @@ using ComputeSharp.D2D1.Helpers; using ComputeSharp.D2D1.Interop.Effects; using ComputeSharp.D2D1.Shaders.Interop.Buffers; using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; +using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; using ComputeSharp.D2D1.Shaders.Loaders; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -35,53 +36,8 @@ public static unsafe class D2D1PixelShaderEffect ThrowHelper.ThrowArgumentNullException(nameof(d2D1Factory1), "The input ID2D1Factory1 object cannot be null."); } - RegisterForD2D1Factory1(d2D1Factory1, null, out effectId); - } - - /// - /// 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. - /// A pointer to the ID2D1Factory1 instance to use. - /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. - /// Thrown if is . - /// Thrown if an effect is registered multiple times with different properties. - /// For more info, see . - public static void RegisterForD2D1Factory1(void* d2D1Factory1, out Guid effectId) - where T : unmanaged, ID2D1PixelShader - where TMapper : class, ID2D1TransformMapper, new() - { - if (d2D1Factory1 is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(d2D1Factory1), "The input ID2D1Factory1 object cannot be null."); - } - - RegisterForD2D1Factory1(d2D1Factory1, D2D1TransformMapper.FactoryOf.Instance, out effectId); - } - - /// - /// Registers an effect from an input D2D1 pixel shader, by calling ID2D1Factory1::RegisterEffectFromString. - /// - /// 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. - /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. - /// Thrown if is . - /// Thrown if an effect is registered multiple times with different properties. - /// For more info, see . - public static void RegisterForD2D1Factory1(void* d2D1Factory1, ID2D1TransformMapperFactory? mapperFactory, out Guid effectId) - where T : unmanaged, ID2D1PixelShader - { - if (d2D1Factory1 is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(d2D1Factory1), "The input ID2D1Factory1 object cannot be null."); - } - effectId = default; - PixelShaderEffect.For.Initialize(mapperFactory); - ArrayPoolBufferWriter writer = new(ArrayPoolBinaryWriter.DefaultInitialBufferSize); // Build the XML text @@ -101,7 +57,7 @@ public static unsafe class D2D1PixelShaderEffect """); // Add the input nodes - for (int i = 0; i < PixelShaderEffect.For.InputCount; i++) + for (int i = 0; i < PixelShaderEffect.For.Instance.InputCount; i++) { writer.WriteRaw(" + + + """); @@ -172,26 +131,27 @@ public static unsafe class D2D1PixelShaderEffect writer.WriteRaw('\0'); fixed (char* pXml = writer.WrittenSpan) - fixed (char* pBufferPropertyName = "ConstantBuffer") - fixed (char* pResourceTextureManager0PropertyName = "ResourceTextureManager0") - fixed (char* pResourceTextureManager1PropertyName = "ResourceTextureManager1") - fixed (char* pResourceTextureManager2PropertyName = "ResourceTextureManager2") - fixed (char* pResourceTextureManager3PropertyName = "ResourceTextureManager3") - fixed (char* pResourceTextureManager4PropertyName = "ResourceTextureManager4") - fixed (char* pResourceTextureManager5PropertyName = "ResourceTextureManager5") - fixed (char* pResourceTextureManager6PropertyName = "ResourceTextureManager6") - fixed (char* pResourceTextureManager7PropertyName = "ResourceTextureManager7") - fixed (char* pResourceTextureManager8PropertyName = "ResourceTextureManager8") - fixed (char* pResourceTextureManager9PropertyName = "ResourceTextureManager9") - fixed (char* pResourceTextureManager10PropertyName = "ResourceTextureManager10") - fixed (char* pResourceTextureManager11PropertyName = "ResourceTextureManager11") - fixed (char* pResourceTextureManager12PropertyName = "ResourceTextureManager12") - fixed (char* pResourceTextureManager13PropertyName = "ResourceTextureManager13") - fixed (char* pResourceTextureManager14PropertyName = "ResourceTextureManager14") - fixed (char* pResourceTextureManager15PropertyName = "ResourceTextureManager15") + fixed (char* pBufferPropertyName = nameof(D2D1PixelShaderEffectProperty.ConstantBuffer)) + fixed (char* pResourceTextureManager0PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager0)) + fixed (char* pResourceTextureManager1PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager1)) + fixed (char* pResourceTextureManager2PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager2)) + fixed (char* pResourceTextureManager3PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager3)) + fixed (char* pResourceTextureManager4PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager4)) + fixed (char* pResourceTextureManager5PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager5)) + fixed (char* pResourceTextureManager6PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager6)) + fixed (char* pResourceTextureManager7PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager7)) + fixed (char* pResourceTextureManager8PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager8)) + fixed (char* pResourceTextureManager9PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager9)) + fixed (char* pResourceTextureManager10PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager10)) + fixed (char* pResourceTextureManager11PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager11)) + fixed (char* pResourceTextureManager12PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager12)) + fixed (char* pResourceTextureManager13PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager13)) + fixed (char* pResourceTextureManager14PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager14)) + fixed (char* pResourceTextureManager15PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager15)) + fixed (char* pTransformMapperPropertyName = nameof(D2D1PixelShaderEffectProperty.TransformMapper)) { // Prepare the effect binding functions - D2D1_PROPERTY_BINDING* d2D1PropertyBinding = stackalloc D2D1_PROPERTY_BINDING[17]; + D2D1_PROPERTY_BINDING* d2D1PropertyBinding = stackalloc D2D1_PROPERTY_BINDING[(int)D2D1PixelShaderEffectProperty.NumberOfProperties]; // Property names d2D1PropertyBinding[0].propertyName = (ushort*)pBufferPropertyName; @@ -211,6 +171,7 @@ public static unsafe class D2D1PixelShaderEffect d2D1PropertyBinding[14].propertyName = (ushort*)pResourceTextureManager13PropertyName; d2D1PropertyBinding[15].propertyName = (ushort*)pResourceTextureManager14PropertyName; d2D1PropertyBinding[16].propertyName = (ushort*)pResourceTextureManager15PropertyName; + d2D1PropertyBinding[17].propertyName = (ushort*)pTransformMapperPropertyName; // Property getters d2D1PropertyBinding[0].getFunction = PixelShaderEffect.GetConstantBuffer; @@ -230,6 +191,7 @@ public static unsafe class D2D1PixelShaderEffect d2D1PropertyBinding[14].getFunction = PixelShaderEffect.GetResourceTextureManager13; d2D1PropertyBinding[15].getFunction = PixelShaderEffect.GetResourceTextureManager14; d2D1PropertyBinding[16].getFunction = PixelShaderEffect.GetResourceTextureManager15; + d2D1PropertyBinding[17].getFunction = PixelShaderEffect.GetTransformMapper; // Property setters d2D1PropertyBinding[0].setFunction = PixelShaderEffect.SetConstantBuffer; @@ -249,59 +211,29 @@ public static unsafe class D2D1PixelShaderEffect d2D1PropertyBinding[14].setFunction = PixelShaderEffect.SetResourceTextureManager13; d2D1PropertyBinding[15].setFunction = PixelShaderEffect.SetResourceTextureManager14; d2D1PropertyBinding[16].setFunction = PixelShaderEffect.SetResourceTextureManager15; + d2D1PropertyBinding[17].setFunction = PixelShaderEffect.SetTransformMapper; - fixed (Guid* pGuid = &PixelShaderEffect.For.Id) + fixed (Guid* pGuid = &PixelShaderEffect.For.Instance.Id) { // Register the effect ((ID2D1Factory1*)d2D1Factory1)->RegisterEffectFromString( classId: pGuid, propertyXml: (ushort*)pXml, bindings: d2D1PropertyBinding, - bindingsCount: 17, - effectFactory: PixelShaderEffect.For.Factory).Assert(); + bindingsCount: D2D1PixelShaderEffectProperty.NumberOfProperties, + effectFactory: PixelShaderEffect.For.Instance.Factory).Assert(); } - effectId = PixelShaderEffect.For.Id; + effectId = PixelShaderEffect.For.Instance.Id; } writer.Dispose(); } - /// - /// Gets a binary blob containing serialized information that can be used to register an effect, by using ID2D1Factory1::RegisterEffectFromString. - /// - /// The type of D2D1 pixel shader to register. - /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. - /// A blob containing serialized information that can be used to register an effect. - /// Thrown if an effect is registered multiple times with different properties. - /// For more info and for details on the binary format, see . - public static ReadOnlyMemory GetRegistrationBlob(out Guid effectId) - where T : unmanaged, ID2D1PixelShader - { - return GetRegistrationBlob(null, out effectId); - } - - /// - /// Gets a binary blob containing serialized information that can be used to register an effect, by using ID2D1Factory1::RegisterEffectFromString. - /// - /// The type of D2D1 pixel shader to register. - /// The type of implementation to register. - /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. - /// A blob containing serialized information that can be used to register an effect. - /// Thrown if an effect is registered multiple times with different properties. - /// For more info and for details on the binary format, see . - public static ReadOnlyMemory GetRegistrationBlob(out Guid effectId) - where T : unmanaged, ID2D1PixelShader - where TMapper : class, ID2D1TransformMapper, new() - { - return GetRegistrationBlob(D2D1TransformMapper.FactoryOf.Instance, out effectId); - } - /// /// Gets a binary blob containing serialized information that can be used to register an effect, by using ID2D1Factory1::RegisterEffectFromString. /// /// The type of D2D1 pixel shader to get the registration blob for. - /// An optional factory of instances to use for the transform. /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. /// A blob containing serialized information that can be used to register an effect. /// Thrown if an effect is registered multiple times with different properties. @@ -337,19 +269,17 @@ public static unsafe class D2D1PixelShaderEffect /// For more info, see . /// /// - public static ReadOnlyMemory GetRegistrationBlob(ID2D1TransformMapperFactory? mapperFactory, out Guid effectId) + public static ReadOnlyMemory GetRegistrationBlob(out Guid effectId) where T : unmanaged, ID2D1PixelShader { - PixelShaderEffect.For.Initialize(mapperFactory); - ArrayPoolBufferWriter writer = new(ArrayPoolBinaryWriter.DefaultInitialBufferSize); // Blob id writer.WriteRaw(D2D1EffectRegistrationData.V1.BlobId); // Effect id and number of inputs - writer.WriteRaw(PixelShaderEffect.For.Id); - writer.WriteRaw(PixelShaderEffect.For.InputCount); + writer.WriteRaw(PixelShaderEffect.For.Instance.Id); + writer.WriteRaw(PixelShaderEffect.For.Instance.InputCount); // Build the XML text writer.WriteRaw(""" @@ -368,7 +298,7 @@ public static unsafe class D2D1PixelShaderEffect """u8); // Add the input nodes - for (int i = 0; i < PixelShaderEffect.For.InputCount; i++) + for (int i = 0; i < PixelShaderEffect.For.Instance.InputCount; i++) { writer.WriteRaw(" + + + """u8); @@ -439,7 +372,7 @@ public static unsafe class D2D1PixelShaderEffect writer.WriteRaw((byte)'\0'); // Bindings - writer.WriteRaw(17); + writer.WriteRaw(D2D1PixelShaderEffectProperty.NumberOfProperties); writer.WriteRaw("ConstantBuffer"u8); writer.WriteRaw((byte)'\0'); writer.WriteRaw((nint)PixelShaderEffect.GetConstantBuffer); @@ -508,16 +441,20 @@ public static unsafe class D2D1PixelShaderEffect writer.WriteRaw((byte)'\0'); writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager15); writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager15); + writer.WriteRaw("TransformMapper"u8); + writer.WriteRaw((byte)'\0'); + writer.WriteRaw((nint)PixelShaderEffect.GetTransformMapper); + writer.WriteRaw((nint)PixelShaderEffect.SetTransformMapper); // Effect factory - writer.WriteRaw((nint)PixelShaderEffect.For.Factory); + writer.WriteRaw((nint)PixelShaderEffect.For.Instance.Factory); byte[] registrationBlob = writer.WrittenSpan.ToArray(); writer.Dispose(); // Extract the effect id (the same that was encoded in the registration blob) - effectId = PixelShaderEffect.For.Id; + effectId = PixelShaderEffect.For.Instance.Id; return registrationBlob; } @@ -548,14 +485,12 @@ public static unsafe class D2D1PixelShaderEffect ThrowHelper.ThrowArgumentNullException(nameof(d2D1Effect), "The pointer to the target ID2D1Effect result cannot be null."); } - if (!PixelShaderEffect.For.TryGetId(out Guid id)) + fixed (Guid* pGuid = &PixelShaderEffect.For.Instance.Id) { - ThrowHelper.ThrowInvalidOperationException("The effect for the input shader type has not been initialized yet."); + ((ID2D1DeviceContext*)d2D1DeviceContext)->CreateEffect( + effectId: pGuid, + effect: (ID2D1Effect**)d2D1Effect).Assert(); } - - ((ID2D1DeviceContext*)d2D1DeviceContext)->CreateEffect( - effectId: &id, - effect: (ID2D1Effect**)d2D1Effect).Assert(); } /// @@ -610,7 +545,7 @@ public static unsafe class D2D1PixelShaderEffect /// Sets the resource texture manager from an input D2D1 effect, by calling ID2D1Effect::SetValue. /// /// A pointer to the ID2D1Effect instance to use. - /// The input instance.. + /// The input instance. /// The index of the resource texture to assign the resource texture manager to. /// Thrown if or are . /// For more info, see . @@ -636,4 +571,61 @@ public static unsafe class D2D1PixelShaderEffect data: (byte*)resourceTextureManager2.GetAddressOf(), dataSize: (uint)sizeof(void*)).Assert(); } + + /// + /// Sets the transform mapper for an input D2D1 effect, by calling ID2D1Effect::SetValue. + /// + /// A pointer to the ID2D1Effect instance to use. + /// The input ID2D1TransformMapper object (see ). + /// Thrown if or are . + /// For more info, see . + public static void SetTransformMapperForD2D1Effect(void* d2D1Effect, void* transformMapper) + { + if (d2D1Effect is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(d2D1Effect), "The input ID2D1Effect object cannot be null."); + } + + if (transformMapper is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(transformMapper), "The input ID2D1TransformMapper object cannot be null."); + } + + ((ID2D1Effect*)d2D1Effect)->SetValue( + index: D2D1PixelShaderEffectProperty.TransformMapper, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_IUNKNOWN, + data: (byte*)&transformMapper, + dataSize: (uint)sizeof(void*)).Assert(); + } + + /// + /// Sets the transform mapper for an input D2D1 effect, by calling ID2D1Effect::SetValue. + /// + /// A pointer to the ID2D1Effect instance to use. + /// The input ID2D1TransformMapper object. + /// Thrown if or are . + /// For more info, see . + public static void SetTransformMapperForD2D1Effect(void* d2D1Effect, D2D1TransformMapper transformMapper) + where T : unmanaged, ID2D1PixelShader + { + if (d2D1Effect is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(d2D1Effect), "The input ID2D1Effect object cannot be null."); + } + + if (transformMapper is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(transformMapper), "The input D2D1TransformMapper object cannot be null."); + } + + using ComPtr transformMapper2 = default; + + transformMapper.GetD2D1TransformMapper(transformMapper2.GetAddressOf()); + + ((ID2D1Effect*)d2D1Effect)->SetValue( + index: D2D1PixelShaderEffectProperty.TransformMapper, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_IUNKNOWN, + data: (byte*)transformMapper2.GetAddressOf(), + dataSize: (uint)sizeof(void*)).Assert(); + } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffectProperty.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffectProperty.cs index 892ec2f4..440b0951 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffectProperty.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffectProperty.cs @@ -112,4 +112,20 @@ public static class D2D1PixelShaderEffectProperty /// /// For more info, see . public const uint ResourceTextureManager15 = 16; + + /// + /// The index for the ID2D1TransformMapper property of a object. + /// + /// + /// The value of this property is of type D2D1_PROPERTY_TYPE_IUNKNOWN. + /// This value can be passed when calling ID2D1Effect::SetValue. + /// For more info, see . + /// + public const uint TransformMapper = 17; + + /// + /// The total number of properties. + /// + /// This should always be the value of the last property above, plus 1. + internal const uint NumberOfProperties = 18; } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureManager.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureManager.cs index 3c1234ce..6f9d2404 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureManager.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureManager.cs @@ -1,6 +1,7 @@ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using ComputeSharp.D2D1.Extensions; using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -77,8 +78,8 @@ namespace ComputeSharp.D2D1.Interop; /// interface ID2D1ResourceTextureManagerInternal : IUnknown /// { /// HRESULT Initialize( -/// [in] ID2D1EffectContext *effectContext, -/// [in, optional] const UINT32 *dimensions); +/// [in] const ID2D1EffectContext *effectContext, +/// [in, optional] const UINT32 *dimensions); /// /// HRESULT GetResourceTexture([out] ID2D1ResourceTexture **resourceTexture); /// }; @@ -105,7 +106,7 @@ public sealed unsafe class D2D1ResourceTextureManager : ICustomQueryInterface /// /// The object wrapped by the current instance. /// - private readonly D2D1ResourceTextureManagerImpl* d2D1ResourceManagerImpl; + private ComPtr d2D1ResourceManagerImpl; /// /// Creates a new instance with the specified parameters. @@ -305,7 +306,7 @@ public sealed unsafe class D2D1ResourceTextureManager : ICustomQueryInterface Marshal.ThrowExceptionForHR(E.E_INVALIDARG); } - fixed (D2D1ResourceTextureManagerImpl** d2D1ResourceManagerImpl = &this.d2D1ResourceManagerImpl) + fixed (D2D1ResourceTextureManagerImpl** d2D1ResourceManagerImpl = this.d2D1ResourceManagerImpl) { D2D1ResourceTextureManagerImpl.Factory(d2D1ResourceManagerImpl, requiresMultithread: true); } @@ -324,7 +325,7 @@ public sealed unsafe class D2D1ResourceTextureManager : ICustomQueryInterface d2D1ResourceTextureProperties.extendModes = (D2D1_EXTEND_MODE*)pExtendModes; int hresult = D2D1ResourceTextureManagerImpl.Initialize( - @this: this.d2D1ResourceManagerImpl, + @this: this.d2D1ResourceManagerImpl.Get(), resourceId: resourceId, resourceTextureProperties: &d2D1ResourceTextureProperties, data: pData, @@ -340,10 +341,7 @@ public sealed unsafe class D2D1ResourceTextureManager : ICustomQueryInterface /// ~D2D1ResourceTextureManager() { - if (this.d2D1ResourceManagerImpl is not null) - { - _ = this.d2D1ResourceManagerImpl->Release(); - } + this.d2D1ResourceManagerImpl.Dispose(); } /// @@ -376,7 +374,7 @@ public sealed unsafe class D2D1ResourceTextureManager : ICustomQueryInterface } int hresult = D2D1ResourceTextureManagerImpl.Update( - @this: this.d2D1ResourceManagerImpl, + @this: this.d2D1ResourceManagerImpl.Get(), minimumExtents: pMinimumExtents, maximimumExtents: pMaximumExtents, strides: pStrides, @@ -397,9 +395,7 @@ public sealed unsafe class D2D1ResourceTextureManager : ICustomQueryInterface [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void GetD2D1ResourceTextureManager(ID2D1ResourceTextureManager** resourceTextureManager) { - _ = this.d2D1ResourceManagerImpl->AddRef(); - - *resourceTextureManager = (ID2D1ResourceTextureManager*)this.d2D1ResourceManagerImpl; + this.d2D1ResourceManagerImpl.CopyTo(resourceTextureManager).Assert(); GC.KeepAlive(this); } @@ -410,7 +406,7 @@ public sealed unsafe class D2D1ResourceTextureManager : ICustomQueryInterface fixed (Guid* pIid = &iid) fixed (IntPtr* pPpv = &ppv) { - int hresult = this.d2D1ResourceManagerImpl->QueryInterface(pIid, (void**)pPpv); + int hresult = this.d2D1ResourceManagerImpl.CopyTo(pIid, (void**)pPpv); GC.KeepAlive(this); diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1TransformMapperFactory{T}.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1TransformMapperFactory{T}.cs index c53756ef..3e0d1ff2 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1TransformMapperFactory{T}.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1TransformMapperFactory{T}.cs @@ -12,81 +12,81 @@ public static class D2D1TransformMapperFactory where T : unmanaged, ID2D1PixelShader { /// - /// Creates an instance for an inflate transform. + /// Creates an instance for an inflate transform. /// /// The fixed inflate amount to use (applies to all edges of the input area). - /// The resulting instance for an inflate transform. - public static ID2D1TransformMapperFactory Inflate(int amount) + /// The resulting instance for an inflate transform. + public static D2D1TransformMapper Inflate(int amount) { - return new D2D1InflateTransformMapperFactory { ParametersAccessor = new D2D1InflateTransformMapperFactory.ConstantAmount { Amount = amount } }; + return new D2D1InflateTransformMapper.ConstantAmount { Amount = amount }; } /// - /// Creates an instance for an inflate transform. + /// Creates an instance for an inflate transform. /// /// The fixed left inflate amount to use. /// The fixed top inflate amount to use. /// The fixed right inflate amount to use. /// The fixed bottom inflate amount to use. - /// The resulting instance for an inflate transform. - public static ID2D1TransformMapperFactory Inflate(int left, int top, int right, int bottom) + /// The resulting instance for an inflate transform. + public static D2D1TransformMapper Inflate(int left, int top, int right, int bottom) { - return new D2D1InflateTransformMapperFactory { ParametersAccessor = new D2D1InflateTransformMapperFactory.ConstantLeftTopRightBottomAmount { Left = left, Top = top, Right = right, Bottom = bottom } }; + return new D2D1InflateTransformMapper.ConstantLeftTopRightBottomAmount { Left = left, Top = top, Right = right, Bottom = bottom }; } /// - /// Creates an instance for an inflate transform. + /// Creates an instance for an inflate transform. /// /// The input instance to retrieve the inflate amount to use (applies to all edges of the input area). - /// The resulting instance for an inflate transform. - public static ID2D1TransformMapperFactory Inflate(Accessor accessor) + /// The resulting instance for an inflate transform. + public static D2D1TransformMapper Inflate(Accessor accessor) { if (accessor is null) { ThrowHelper.ThrowArgumentNullException(nameof(accessor), "The input D2D1TransformMapperFactory.Accessor object cannot be null."); } - return new D2D1InflateTransformMapperFactory { ParametersAccessor = new D2D1InflateTransformMapperFactory.DynamicAmount { Accessor = accessor } }; + return new D2D1InflateTransformMapper.DynamicAmount { Accessor = accessor }; } /// - /// Creates an instance for an inflate transform. + /// Creates an instance for an inflate transform. /// /// The input instance to retrieve the inflate amount to use. - /// The resulting instance for an inflate transform. - public static ID2D1TransformMapperFactory Inflate(Accessor<(int Left, int Top, int Right, int Bottom)> accessor) + /// The resulting instance for an inflate transform. + public static D2D1TransformMapper Inflate(Accessor<(int Left, int Top, int Right, int Bottom)> accessor) { if (accessor is null) { ThrowHelper.ThrowArgumentNullException(nameof(accessor), "The input D2D1TransformMapperFactory.Accessor<(int Left, int Top, int Right, int Bottom)> object cannot be null."); } - return new D2D1InflateTransformMapperFactory { ParametersAccessor = new D2D1InflateTransformMapperFactory.DynamicLeftTopRightBottomAmount { Accessor = accessor } }; + return new D2D1InflateTransformMapper.DynamicLeftTopRightBottomAmount { Accessor = accessor }; } /// - /// Creates an instance for an affine transform. + /// Creates an instance for an affine transform. /// /// The fixed transformation matrix to use. - /// The resulting instance for an affine transform. - public static ID2D1TransformMapperFactory Transform(Matrix3x2 matrix) + /// The resulting instance for an affine transform. + public static D2D1TransformMapper Transform(Matrix3x2 matrix) { - return new D2D1AffineTransformMapperFactory.For { ParametersAccessor = new D2D1AffineTransformMapperFactory.For.ConstantMatrix { Amount = matrix } }; + return new D2D1AffineTransformMapper.ConstantMatrix { Amount = matrix }; } /// - /// Creates an instance for an affine transform. + /// Creates an instance for an affine transform. /// /// The input instance to retrieve the transformation matrix to use. - /// The resulting instance for an affine transform. - public static ID2D1TransformMapperFactory Transform(Accessor accessor) + /// The resulting instance for an affine transform. + public static D2D1TransformMapper Transform(Accessor accessor) { if (accessor is null) { ThrowHelper.ThrowArgumentNullException(nameof(accessor), "The input D2D1TransformMapperFactory.Accessor object cannot be null."); } - return new D2D1AffineTransformMapperFactory.For { ParametersAccessor = new D2D1AffineTransformMapperFactory.For.DynamicMatrix { Accessor = accessor } }; + return new D2D1AffineTransformMapper.DynamicMatrix { Accessor = accessor }; } /// diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1TransformMapper{T}.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1TransformMapper{T}.cs new file mode 100644 index 00000000..21db7412 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1TransformMapper{T}.cs @@ -0,0 +1,277 @@ +using System; +using System.Drawing; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.Interop.Effects; +using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; +using TerraFX.Interop.Windows; + +#pragma warning disable CA1033 + +namespace ComputeSharp.D2D1.Interop; + +/// +/// Provides an ID2D1TransformMapper implementation, which can be used to customize the draw transform logic in +/// an effect created with and also shared across multiple instances of a given effect. +/// +/// The type of shader the transform will interact with. +/// +/// +/// The built-in ID2D1EffectImpl +/// implementation provided by (which makes it possible to register and create +/// ID2D1Effect +/// instances that can be used to run D2D1 pixel shaders) uses draw transform objects to allow customizing the transform logic externally. +/// +/// +/// These managers are COM objects implementing the following interface: +/// +/// [uuid(02E6D48D-B892-4FBC-AA54-119203BAB802)] +/// interface ID2D1TransformMapper : IUnknown +/// { +/// HRESULT MapInputRectsToOutputRect( +/// [in] const ID2D1DrawInfoUpdateContext* updateContext, +/// [in] const RECT* inputRects, +/// [in] const RECT* inputOpaqueSubRects, +/// UINT32 inputRectCount, +/// [out] RECT* outputRect, +/// [out] RECT* outputOpaqueSubRect); +/// +/// HRESULT MapOutputRectToInputRects( +/// [in] const RECT* outputRect, +/// [out] RECT* inputRects, +/// UINT32 inputRectsCount); +/// +/// HRESULT MapInvalidRect( +/// UINT32 inputIndex, +/// RECT invalidInputRect, +/// [out] RECT* invalidOutputRect); +/// }; +/// +/// +/// +/// These can be used to implement custom draw transform logic, assign it to an effect and also share these transforms over multiple effects. +/// +/// +/// For details of how these work, MapInputRectsToOutputRect maps to +/// ID2D1Transform::MapInputRectsToOutputRect, +/// MapOutputRectToInputRects maps to ID2D1Transform::MapOutputRectToInputRects. +/// and MapInvalidRect maps to ID2D1Transform::MapInvalidRect. +/// +/// +/// The main difference between these APIs and the ones in ID2D1Transform is the fact that this interface is standalone (ie. it doesn't inherit from ID2D1TransformNode), +/// and that it allows transform mappers to also read and update additional data tied to an effect instance (such as the shader constant buffer). This is done through the +/// ID2D1DrawInfoUpdateContext interface, that is passed to MapInputRectsToOutputRect. This interface is defined as follows: +/// +/// [uuid(430C5B40-AE16-485F-90E6-4FA4915144B6)] +/// interface ID2D1DrawInfoUpdateContext : IUnknown +/// { +/// HRESULT GetConstantBufferSize([out] UINT32 *size); +/// +/// HRESULT GetConstantBuffer( +/// [out] BYTE *buffer, +/// UINT32 bufferCount); +/// +/// HRESULT SetConstantBuffer( +/// [in] const BYTE *buffer, +/// UINT32 bufferCount); +/// } +/// +/// +/// +/// That is, ID2D1DrawInfoUpdateContext allows a custom transform (an ID2D1TransformMapper instance) to interact with the underlying ID2D1DrawInfo object +/// that is owned by the effect being used, in a safe way. For instance, it allows a transform to read and update the constant buffer, which can be used to allow a transform to +/// pass the exact dispatch area size to an input shader, without the consumer having to manually query that information beforehand (which might not be available either). +/// +/// +/// This interface is implemented by ComputeSharp.D2D1, and it can be used through the APIs in , in several ways. +/// That is, consumers can either implement a type inheriting from to implement their own fully customized transform +/// mapping logic, or they can use the helper methods exposed by to easily retrieve ready to use transforms. +/// +/// +/// A CCW (COM callable wrapper, see ) is also available for all +/// of these APIs, implemented via the same type. That is, a given instance can expose its underlying CCW through the +/// interface, and this can then be passed to an existing D2D1 effect instance. +/// +/// +public abstract unsafe class D2D1TransformMapper : ICustomQueryInterface, ID2D1TransformMapperInterop + where T : unmanaged, ID2D1PixelShader +{ + /// + /// The object wrapped by the current instance. + /// + private ComPtr d2D1TransformMapperImpl; + + /// + /// Creates a new instance. + /// + public D2D1TransformMapper() + { + fixed (D2D1TransformMapperImpl** d2D1TransformMapperImpl = this.d2D1TransformMapperImpl) + { + D2D1TransformMapperImpl.Factory(this, d2D1TransformMapperImpl); + } + } + + /// + /// Releases the underlying ID2D1TransformMapper object. + /// + ~D2D1TransformMapper() + { + this.d2D1TransformMapperImpl.Dispose(); + } + + /// + /// + /// 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 value, which can be used to access and modify shader data. + /// 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 . + /// + /// + public abstract void MapInputsToOutput( + D2D1DrawInfoUpdateContext drawInfoUpdateContext, + 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 output rectangle from which the inputs must be mapped. + /// The corresponding set of inputs. The inputs will directly correspond to the transform inputs. + /// + /// + /// The transform implementation must regard this method as purely functional. It can base the mapped input and output rectangles on its + /// current state as specified by the encapsulating effect properties. However, it must not change its own state in response to this method + /// being invoked. The Direct2D renderer implementation reserves the right to call this method at any time and in any sequence. + /// + /// + /// For more info, see . + /// + /// + public abstract void MapOutputToInputs(in Rectangle output, Span inputs); + + /// + /// Sets the input rectangles for this rendering pass into the transform. + /// + /// The index of the input rectangle. + /// The invalid input rectangle. + /// The output rectangle to which the input rectangle must be mapped. + /// + /// + /// 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 . + /// + /// + /// For more info, see . + /// + /// + public abstract void MapInvalidOutput(int inputIndex, in Rectangle invalidInput, out Rectangle invalidOutput); + + /// + /// Gets the underlying object. + /// + /// The underlying object. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void GetD2D1TransformMapper(ID2D1TransformMapper** transformMapper) + { + bool lockTaken = false; + + this.d2D1TransformMapperImpl.Get()->SpinLock.Enter(ref lockTaken); + + // Whenever the CCW is requested from this object, we also make sure that the current instance is tracked + // in the GC handle stored in the CCW. This could've been reset in case there were no other references to + // the CCW (see comments in D2D1TransformMapperImpl about this), so here we're assigning a reference to the + // current object again to ensure the returned CCW object will keep the instance alive if needed. + try + { + this.d2D1TransformMapperImpl.Get()->EnsureTargetIsTracked(this); + this.d2D1TransformMapperImpl.Get()->CopyToWithNoLock(transformMapper); + } + finally + { + this.d2D1TransformMapperImpl.Get()->SpinLock.Exit(); + + GC.KeepAlive(this); + } + } + + /// + CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv) + { + fixed (Guid* pIid = &iid) + fixed (IntPtr* pPpv = &ppv) + { + int hresult; + bool lockTaken = false; + + this.d2D1TransformMapperImpl.Get()->SpinLock.Enter(ref lockTaken); + + try + { + this.d2D1TransformMapperImpl.Get()->EnsureTargetIsTracked(this); + + hresult = this.d2D1TransformMapperImpl.Get()->QueryInterfaceWithNoLock(pIid, (void**)pPpv); + } + finally + { + this.d2D1TransformMapperImpl.Get()->SpinLock.Exit(); + + GC.KeepAlive(this); + } + + return hresult switch + { + S.S_OK => CustomQueryInterfaceResult.Handled, + _ => CustomQueryInterfaceResult.Failed + }; + } + } + + /// + void ID2D1TransformMapperInterop.MapInputsToOutput( + ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext, + ReadOnlySpan inputs, + ReadOnlySpan opaqueInputs, + out Rectangle output, + out Rectangle opaqueOutput) + { + MapInputsToOutput( + new D2D1DrawInfoUpdateContext(d2D1DrawInfoUpdateContext), + inputs, + opaqueInputs, + out output, + out opaqueOutput); + } + + /// + void ID2D1TransformMapperInterop.MapOutputToInputs(in Rectangle output, Span inputs) + { + MapOutputToInputs(in output, inputs); + } + + /// + void ID2D1TransformMapperInterop.MapInvalidOutput(int inputIndex, in Rectangle invalidInput, out Rectangle invalidOutput) + { + MapInvalidOutput(inputIndex, in invalidInput, out invalidOutput); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/D2D1TransformMapper.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/D2D1TransformMapper.cs deleted file mode 100644 index f13dc1ac..00000000 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/D2D1TransformMapper.cs +++ /dev/null @@ -1,133 +0,0 @@ -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 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(in Rectangle output, Span inputs); - - /// - /// 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(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 D2D1TransformMapper? Get(ID2D1TransformMapper? transformMapper) - { - if (transformMapper is null) - { - return null; - } - - // If one of the built-in transform mapper factories from D2D1TransformMapperFactory was used, - // the returned ID2D1TransformMapper instance will already inherit from D2D1TransformMapper. - // If that's the case, that object can be returned directly, saving one allocation and avoiding - // an extra interface stub dispatch call every time one of the transform mapping APIs is called. - if (transformMapper is D2D1TransformMapper d2D1TransformMapper) - { - return d2D1TransformMapper; - } - - return new For(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(in Rectangle output, Span inputs) - { - this.transformMapper.MapOutputToInputs(in output, inputs); - } - - /// - public override void MapInvalidOutput(int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput) - { - this.transformMapper.MapInvalidOutput(inputIndex, invalidInput, out invalidOutput); - } - } - - /// - /// A generic implementation for a mapper with a parameterless constructor. - /// - /// The type of D2D1 pixel shader to register. - /// The type of implementation to register. - public sealed class FactoryOf : ID2D1TransformMapperFactory - where T : unmanaged, ID2D1PixelShader - where TMapper : class, ID2D1TransformMapper, new() - { - /// - /// Creates a new instance. - /// - private FactoryOf() - { - } - - /// - /// Gets the shared instance for a given transform mapper. - /// - public static FactoryOf Instance { get; } = new(); - - /// - public ID2D1TransformMapper Create() - { - return new TMapper(); - } - } -} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ID2D1TransformMapperInterop.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ID2D1TransformMapperInterop.cs new file mode 100644 index 00000000..23417b24 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ID2D1TransformMapperInterop.cs @@ -0,0 +1,30 @@ +using System; +using System.Drawing; +using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; + +namespace ComputeSharp.D2D1.Interop.Effects; + +/// +/// A base type to support non-generic uses. +/// +internal unsafe interface ID2D1TransformMapperInterop +{ + /// + /// The instance associated with the current effect. + /// 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. + void MapInputsToOutput( + ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext, + ReadOnlySpan inputs, + ReadOnlySpan opaqueInputs, + out Rectangle output, + out Rectangle opaqueOutput); + + /// + void MapOutputToInputs(in Rectangle output, Span inputs); + + /// + void MapInvalidOutput(int inputIndex, in Rectangle invalidInput, out Rectangle invalidOutput); +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs index 0befc486..237cb296 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs @@ -1,7 +1,6 @@ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using ComputeSharp.D2D1.Helpers; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; #if NET6_0_OR_GREATER @@ -10,8 +9,6 @@ using RuntimeHelpers = System.Runtime.CompilerServices.RuntimeHelpers; using RuntimeHelpers = ComputeSharp.D2D1.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; #endif -#pragma warning disable CA2002 - namespace ComputeSharp.D2D1.Interop.Effects; /// @@ -19,22 +16,25 @@ namespace ComputeSharp.D2D1.Interop.Effects; /// internal unsafe partial struct PixelShaderEffect { + /// + /// A wrapper for an effect factory. + /// + /// The resulting effect factory. + /// The HRESULT for the operation. + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int FactoryDelegate(IUnknown** effectImpl); + /// /// A generic pixel shader implementation. /// /// The type of shader. - public static class For + public sealed class For where T : unmanaged, ID2D1PixelShader { /// /// The wrapper for the shader factory. /// - private static readonly FactoryDelegate EffectFactory = CreateEffect; - - /// - /// Indicates whether or not initialization has completed. - /// - private static bool isInitialized; + private readonly FactoryDelegate effectFactory; /// /// The for the shader. @@ -44,229 +44,168 @@ internal unsafe partial struct PixelShaderEffect /// being used to pass its address to a native API, but the attribute is incompatible with collectible assemblies. /// Because of that, it can't be used, as this project is explicitly meant to support plugin-like scenarios. /// - private static Guid shaderId; + private readonly Guid shaderId; /// /// The size of the constant buffer for the shader. /// - private static int constantBufferSize; + private readonly int constantBufferSize; /// /// The number of inputs for the shader. /// - private static int inputCount; + private readonly int inputCount; /// /// The buffer with the types of inputs for the shader. /// - private static D2D1PixelShaderInputType* inputTypes; + private readonly D2D1PixelShaderInputType* inputTypes; /// /// The number of available input descriptions. /// - private static int inputDescriptionCount; + private readonly int inputDescriptionCount; /// /// The buffer with the available input descriptions for the shader. /// - private static D2D1InputDescription* inputDescriptions; + private readonly D2D1InputDescription* inputDescriptions; /// /// The pixel options for the shader. /// - private static D2D1PixelOptions pixelOptions; + private readonly D2D1PixelOptions pixelOptions; /// /// The shader bytecode. /// - private static byte* bytecode; + private readonly byte* bytecode; /// /// The size of . /// - private static int bytecodeSize; + private readonly int bytecodeSize; /// /// The buffer precision for the resulting output buffer. /// - private static D2D1BufferPrecision bufferPrecision; + private readonly D2D1BufferPrecision bufferPrecision; /// /// The channel depth for the resulting output buffer. /// - private static D2D1ChannelDepth channelDepth; + private readonly D2D1ChannelDepth channelDepth; /// /// The number of available resource texture descriptions. /// - private static int resourceTextureDescriptionCount; + private readonly int resourceTextureDescriptionCount; /// /// The buffer with the available resource texture descriptions for the shader. /// - private static D2D1ResourceTextureDescription* resourceTextureDescriptions; + private readonly D2D1ResourceTextureDescription* resourceTextureDescriptions; /// - /// The factory of instances to use for each created effect. + /// Creates a new instance with the specified parameters. /// - private static ID2D1TransformMapperFactory? d2D1DrawTransformMapperFactory; - - /// - /// Initializes the shared state. - /// - /// The factory of instances to use for each created effect. - /// Thrown if initialization is attempted with a mismatched transform factory. - public static void Initialize(ID2D1TransformMapperFactory? d2D1DrawTransformMapperFactory) + /// The wrapper for the shader factory. + /// The for the shader. + /// The size of the constant buffer for the shader. + /// The number of inputs for the shader. + /// The buffer with the types of inputs for the shader. + /// The number of available input descriptions. + /// The buffer with the available input descriptions for the shader. + /// The pixel options for the shader. + /// The shader bytecode. + /// The size of . + /// The buffer precision for the resulting output buffer. + /// The channel depth for the resulting output buffer. + /// The number of available resource texture descriptions. + /// The buffer with the available resource texture descriptions for the shader. + private For( + FactoryDelegate effectFactory, + Guid shaderId, + int constantBufferSize, + int inputCount, + D2D1PixelShaderInputType* inputTypes, + int inputDescriptionCount, + D2D1InputDescription* inputDescriptions, + D2D1PixelOptions pixelOptions, + byte* bytecode, + int bytecodeSize, + D2D1BufferPrecision bufferPrecision, + D2D1ChannelDepth channelDepth, + int resourceTextureDescriptionCount, + D2D1ResourceTextureDescription* resourceTextureDescriptions) { - // This conceptually acts as a static constructor, and this type is - // internal, so in this very specific case locking on the type is fine. - lock (typeof(For)) - { - if (isInitialized) - { - // If the factory is already initialized, ensure the draw transform mapper is the same - if (For.d2D1DrawTransformMapperFactory != d2D1DrawTransformMapperFactory) - { - ThrowHelper.ThrowInvalidOperationException( - "Cannot initialize an ID2D1Effect factory for the same shader type with two different transform mapper factories. " + - "Make sure to only ever register a pixel shader effect with either no transform, or the same transform mapper factory instance."); - } - } - else - { - // Load all shader properties - Guid shaderId = typeof(T).GUID; - int constantBufferSize = D2D1PixelShader.GetConstantBufferSize(); - D2D1BufferPrecision bufferPrecision = D2D1PixelShader.GetOutputBufferPrecision(); - D2D1ChannelDepth channelDepth = D2D1PixelShader.GetOutputBufferChannelDepth(); - D2D1PixelOptions pixelOptions = D2D1PixelShader.GetPixelOptions(); - - // Prepare the inputs info - int inputCount = D2D1PixelShader.GetInputCount(); - D2D1PixelShaderInputType* inputTypes = (D2D1PixelShaderInputType*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), sizeof(D2D1PixelShaderInputType) * inputCount); - - for (int i = 0; i < inputCount; i++) - { - inputTypes[i] = D2D1PixelShader.GetInputType(i); - } - - // Prepare the input descriptions - ReadOnlyMemory inputDescriptionsInfo = D2D1PixelShader.GetInputDescriptions(); - int inputDescriptionCount = inputDescriptionsInfo.Length; - D2D1InputDescription* inputDescriptions = (D2D1InputDescription*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), sizeof(D2D1InputDescription) * inputDescriptionCount); - - inputDescriptionsInfo.Span.CopyTo(new Span(inputDescriptions, inputDescriptionCount)); - - // Prepare the resource texture descriptions - ReadOnlyMemory resourceTextureDescriptionsInfo = D2D1PixelShader.GetResourceTextureDescriptions(); - int resourceTextureDescriptionCount = resourceTextureDescriptionsInfo.Length; - D2D1ResourceTextureDescription* resourceTextureDescriptions = (D2D1ResourceTextureDescription*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), sizeof(D2D1ResourceTextureDescription) * resourceTextureDescriptionCount); - - resourceTextureDescriptionsInfo.Span.CopyTo(new Span(resourceTextureDescriptions, resourceTextureDescriptionCount)); - - // Copy the bytecode to the target buffer - ReadOnlyMemory bytecodeInfo = D2D1PixelShader.LoadBytecode(); - int bytecodeSize = bytecodeInfo.Length; - byte* bytecode = (byte*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), bytecodeSize); - - bytecodeInfo.Span.CopyTo(new Span(bytecode, bytecodeSize)); - - // Set the shared state and mark the type as initialized - For.shaderId = shaderId; - For.constantBufferSize = constantBufferSize; - For.inputCount = inputCount; - For.inputTypes = inputTypes; - For.inputDescriptionCount = inputDescriptionCount; - For.inputDescriptions = inputDescriptions; - For.pixelOptions = pixelOptions; - For.bytecode = bytecode; - For.bytecodeSize = bytecodeSize; - For.bufferPrecision = bufferPrecision; - For.channelDepth = channelDepth; - For.resourceTextureDescriptionCount = resourceTextureDescriptionCount; - For.resourceTextureDescriptions = resourceTextureDescriptions; - For.d2D1DrawTransformMapperFactory = d2D1DrawTransformMapperFactory; - - isInitialized = true; - } - } + this.effectFactory = effectFactory; + this.shaderId = shaderId; + this.constantBufferSize = constantBufferSize; + this.inputCount = inputCount; + this.inputTypes = inputTypes; + this.inputDescriptionCount = inputDescriptionCount; + this.inputDescriptions = inputDescriptions; + this.pixelOptions = pixelOptions; + this.bytecode = bytecode; + this.bytecodeSize = bytecodeSize; + this.bufferPrecision = bufferPrecision; + this.channelDepth = channelDepth; + this.resourceTextureDescriptionCount = resourceTextureDescriptionCount; + this.resourceTextureDescriptions = resourceTextureDescriptions; } /// - /// Gets a reference to the id of the effect. + /// Gets the shader instance. /// - public static ref Guid Id - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => ref shaderId; - } + public static For Instance { get; } = CreateInstance(); /// - /// Gets the factory for the current effect. + /// Creates a new instance. /// -#if NET6_0_OR_GREATER - public static delegate* unmanaged[Stdcall] Factory -#else - public static void* Factory -#endif + /// The initialized instance. + private static For CreateInstance() { - [MethodImpl(MethodImplOptions.AggressiveInlining)] -#if NET6_0_OR_GREATER - get => (delegate* unmanaged[Stdcall])Marshal.GetFunctionPointerForDelegate(EffectFactory); -#else - get => (void*)Marshal.GetFunctionPointerForDelegate(EffectFactory); -#endif - } + // Load all shader properties + Guid shaderId = typeof(T).GUID; + int constantBufferSize = D2D1PixelShader.GetConstantBufferSize(); + D2D1BufferPrecision bufferPrecision = D2D1PixelShader.GetOutputBufferPrecision(); + D2D1ChannelDepth channelDepth = D2D1PixelShader.GetOutputBufferChannelDepth(); + D2D1PixelOptions pixelOptions = D2D1PixelShader.GetPixelOptions(); - /// - /// Gets the number of inputs for the effect. - /// - public static int InputCount => inputCount; + // Prepare the inputs info + int inputCount = D2D1PixelShader.GetInputCount(); + D2D1PixelShaderInputType* inputTypes = (D2D1PixelShaderInputType*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), sizeof(D2D1PixelShaderInputType) * inputCount); - /// - /// Tries to get the effect id, if it has been initialized. - /// - /// The resulting effect id. - /// Whether or not the effect had been initialized. - public static bool TryGetId(out Guid id) - { - lock (typeof(For)) + for (int i = 0; i < inputCount; i++) { - if (isInitialized) - { - id = Id; - - return true; - } + inputTypes[i] = D2D1PixelShader.GetInputType(i); } - id = default; + // Prepare the input descriptions + ReadOnlyMemory inputDescriptionsInfo = D2D1PixelShader.GetInputDescriptions(); + int inputDescriptionCount = inputDescriptionsInfo.Length; + D2D1InputDescription* inputDescriptions = (D2D1InputDescription*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), sizeof(D2D1InputDescription) * inputDescriptionCount); - return false; - } + inputDescriptionsInfo.Span.CopyTo(new Span(inputDescriptions, inputDescriptionCount)); - /// - private static int CreateEffect(IUnknown** effectImpl) - { - D2D1TransformMapper? d2D1TransformMapper; + // Prepare the resource texture descriptions + ReadOnlyMemory resourceTextureDescriptionsInfo = D2D1PixelShader.GetResourceTextureDescriptions(); + int resourceTextureDescriptionCount = resourceTextureDescriptionsInfo.Length; + D2D1ResourceTextureDescription* resourceTextureDescriptions = (D2D1ResourceTextureDescription*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), sizeof(D2D1ResourceTextureDescription) * resourceTextureDescriptionCount); - // If there is a custom draw transform factory, run it in a try block and handle exceptions. This - // is needed because the factory will be running user code from a method that's invoked by COM, - // and managed exceptions should never cross the ABI boundary. If it throws, just return the HRESULT. - try - { - ID2D1TransformMapper? d2D1DrawTransformMapper = d2D1DrawTransformMapperFactory?.Create(); + resourceTextureDescriptionsInfo.Span.CopyTo(new Span(resourceTextureDescriptions, resourceTextureDescriptionCount)); - d2D1TransformMapper = D2D1TransformMapper.For.Get(d2D1DrawTransformMapper); - } - catch (Exception e) - { - *effectImpl = null; + // Copy the bytecode to the target buffer + ReadOnlyMemory bytecodeInfo = D2D1PixelShader.LoadBytecode(); + int bytecodeSize = bytecodeInfo.Length; + byte* bytecode = (byte*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), bytecodeSize); - return e.HResult; - } + bytecodeInfo.Span.CopyTo(new Span(bytecode, bytecodeSize)); - return PixelShaderEffect.Factory( + // Initialize the shared instance with the computed state + return new( + CreateEffect, shaderId, constantBufferSize, inputCount, @@ -279,8 +218,59 @@ internal unsafe partial struct PixelShaderEffect bufferPrecision, channelDepth, resourceTextureDescriptionCount, - resourceTextureDescriptions, - d2D1TransformMapper, + resourceTextureDescriptions); + } + + /// + /// Gets a reference to the id of the effect. + /// + public ref readonly Guid Id + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref this.shaderId; + } + + /// + /// Gets the factory for the current effect. + /// +#if NET6_0_OR_GREATER + public delegate* unmanaged[Stdcall] Factory +#else + public void* Factory +#endif + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#if NET6_0_OR_GREATER + get => (delegate* unmanaged[Stdcall])Marshal.GetFunctionPointerForDelegate(this.effectFactory); +#else + get => (void*)Marshal.GetFunctionPointerForDelegate(this.effectFactory); +#endif + } + + /// + /// Gets the number of inputs for the effect. + /// + public int InputCount => this.inputCount; + + /// + private static int CreateEffect(IUnknown** effectImpl) + { + For instance = Instance; + + return PixelShaderEffect.Factory( + instance.shaderId, + instance.constantBufferSize, + instance.inputCount, + instance.inputTypes, + instance.inputDescriptionCount, + instance.inputDescriptions, + instance.pixelOptions, + instance.bytecode, + instance.bytecodeSize, + instance.bufferPrecision, + instance.channelDepth, + instance.resourceTextureDescriptionCount, + instance.resourceTextureDescriptions, effectImpl); } } diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs index 9075fbf6..a5d848eb 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs @@ -1,7 +1,7 @@ using System; -using System.Drawing; using System.Runtime.InteropServices; using ComputeSharp.D2D1.Extensions; +using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; #if !NET6_0_OR_GREATER @@ -127,29 +127,14 @@ partial struct PixelShaderEffect return E.E_INVALIDARG; } - if (@this->d2D1TransformMapperHandle.Target is D2D1TransformMapper d2D1TransformMapper) + if (@this->d2D1TransformMapper is not null) { - Rectangle output = outputRect->ToRectangle(); - Span inputs = stackalloc Rectangle[8].Slice(0, (int)inputRectsCount); + // Forward to the current ID2D1TransformMapper instance + HRESULT hresult = @this->d2D1TransformMapper->MapOutputRectToInputRects(outputRect, inputRects, inputRectsCount); - for (int i = 0; i < (int)inputRectsCount; i++) + if (!Windows.SUCCEEDED(hresult)) { - inputs[i] = inputRects[i].ToRectangle(); - } - - // Invoke MapOutputToInputs and handle exceptions so they don't cross the ABI boundary - try - { - d2D1TransformMapper.MapOutputToInputs(in output, inputs); - } - catch (Exception e) - { - return e.HResult; - } - - for (int i = 0; i < (int)inputRectsCount; i++) - { - inputRects[i] = inputs[i].ToRECT(); + return hresult; } } else @@ -189,34 +174,38 @@ partial struct PixelShaderEffect return E.E_INVALIDARG; } - if (@this->d2D1TransformMapperHandle.Target is D2D1TransformMapper d2D1TransformMapper) + if (@this->d2D1TransformMapper is not null) { - Span inputs = stackalloc Rectangle[8].Slice(0, (int)inputRectCount); - Span opaqueInputs = stackalloc Rectangle[8].Slice(0, (int)inputRectCount); + using ComPtr d2D1DrawInfoUpdateContext = default; - for (int i = 0; i < (int)inputRectCount; i++) + // Create an ID2D1DrawInfoUpdateContext instance + HRESULT hresult = D2D1DrawInfoUpdateContextImpl.Factory( + drawInfoUpdateContext: d2D1DrawInfoUpdateContext.GetAddressOf(), + constantBuffer: @this->constantBuffer, + constantBufferSize: @this->constantBufferSize, + d2D1DrawInfo: @this->d2D1DrawInfo); + + if (!Windows.SUCCEEDED(hresult)) { - inputs[i] = inputRects[i].ToRectangle(); - opaqueInputs[i] = inputOpaqueSubRects[i].ToRectangle(); + return hresult; } - ReadOnlySpan buffer = new(@this->constantBuffer, @this->constantBufferSize); + // Forward the call to the input ID2D1TransformMapper instance + hresult = @this->d2D1TransformMapper->MapInputRectsToOutputRect( + updateContext: (ID2D1DrawInfoUpdateContext*)d2D1DrawInfoUpdateContext.Get(), + inputRects: inputRects, + inputOpaqueSubRects: inputOpaqueSubRects, + inputRectCount: inputRectCount, + outputRect: outputRect, + outputOpaqueSubRect: outputOpaqueSubRect); - Rectangle output; - Rectangle opaqueOutput; + // Regardless of the operation result, always invalidate the context + _ = d2D1DrawInfoUpdateContext.Get()->Close(); - // Handle exceptions, as mentioned above - try + if (!Windows.SUCCEEDED(hresult)) { - d2D1TransformMapper.MapInputsToOutput(buffer, inputs, opaqueInputs, out output, out opaqueOutput); + return hresult; } - catch (Exception e) - { - return e.HResult; - } - - *outputRect = output.ToRECT(); - *outputOpaqueSubRect = opaqueOutput.ToRECT(); } else if (inputRectCount == 0) { @@ -278,22 +267,15 @@ partial struct PixelShaderEffect return E.E_INVALIDARG; } - if (@this->d2D1TransformMapperHandle.Target is D2D1TransformMapper d2D1TransformMapper) + if (@this->d2D1TransformMapper is not null) { - Rectangle invalidInput = invalidInputRect.ToRectangle(); - Rectangle invalidOutput; + // Forward to the current ID2D1TransformMapper instance + HRESULT hresult = @this->d2D1TransformMapper->MapInvalidRect(inputIndex, invalidInputRect, invalidOutputRect); - // Handle exceptions once again - try + if (!Windows.SUCCEEDED(hresult)) { - d2D1TransformMapper.MapInvalidOutput((int)inputIndex, invalidInput, out invalidOutput); + return hresult; } - catch (Exception e) - { - return e.HResult; - } - - *invalidOutputRect = invalidOutput.ToRECT(); } else { diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs index 44d86690..e18736a2 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs @@ -2,6 +2,7 @@ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; +using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; #if !NET6_0_OR_GREATER @@ -31,6 +32,16 @@ unsafe partial struct PixelShaderEffect /// A cached instance wrapping . /// private static readonly PropertySetFunctionDelegate SetConstantBufferWrapper = SetConstantBufferImpl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetTransformMapperWrapper = GetTransformMapperImpl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetTransformMapperWrapper = SetTransformMapperImpl; #endif /// @@ -67,6 +78,40 @@ unsafe partial struct PixelShaderEffect #endif } + /// + /// Gets the get accessor for the transform mapper. + /// +#if NET6_0_OR_GREATER + public static delegate* unmanaged[Stdcall] GetTransformMapper +#else + public static void* GetTransformMapper +#endif + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#if NET6_0_OR_GREATER + get => &GetTransformMapperImpl; +#else + get => (void*)Marshal.GetFunctionPointerForDelegate(GetTransformMapperWrapper); +#endif + } + + /// + /// Gets the set accessor for the transform mapper. + /// +#if NET6_0_OR_GREATER + public static delegate* unmanaged[Stdcall] SetTransformMapper +#else + public static void* SetTransformMapper +#endif + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#if NET6_0_OR_GREATER + get => &SetTransformMapperImpl; +#else + get => (void*)Marshal.GetFunctionPointerForDelegate(SetTransformMapperWrapper); +#endif + } + /// [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] private static int GetConstantBufferImpl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) @@ -119,28 +164,115 @@ unsafe partial struct PixelShaderEffect [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] private static int SetConstantBufferImpl(IUnknown* effect, byte* data, uint dataSize) { + PixelShaderEffect* @this = (PixelShaderEffect*)effect; + if (data is null) { return E.E_POINTER; } - PixelShaderEffect* @this = (PixelShaderEffect*)effect; - if (dataSize != (uint)@this->constantBufferSize) { return E.E_INVALIDARG; } + // Reuse the existing buffer if there is one, otherwise allocate a new one if (@this->constantBuffer is not null) { - NativeMemory.Free(@this->constantBuffer); + Buffer.MemoryCopy(data, @this->constantBuffer, dataSize, dataSize); + } + else + { + void* buffer = NativeMemory.Alloc(dataSize); + + Buffer.MemoryCopy(data, buffer, dataSize, dataSize); + + @this->constantBuffer = (byte*)buffer; } - void* buffer = NativeMemory.Alloc(dataSize); + return S.S_OK; + } - Buffer.MemoryCopy(data, buffer, dataSize, dataSize); + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetTransformMapperImpl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + PixelShaderEffect* @this = (PixelShaderEffect*)effect; - @this->constantBuffer = (byte*)buffer; + if (data is null) + { + return E.E_POINTER; + } + + if (dataSize < sizeof(void*)) + { + return E.E_INVALIDARG; + } + + if (@this->d2D1TransformMapper is null) + { + *(void**)data = null; + } + else + { + HRESULT hresult = ((IUnknown*)@this->d2D1TransformMapper)->QueryInterface(Windows.__uuidof(), (void**)data); + + if (!Windows.SUCCEEDED(hresult)) + { + return hresult; + } + } + + if (actualSize is not null) + { + *actualSize = (uint)sizeof(void*); + } + + return S.S_OK; + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetTransformMapperImpl(IUnknown* effect, byte* data, uint dataSize) + { + PixelShaderEffect* @this = (PixelShaderEffect*)effect; + + if (data is null) + { + return E.E_POINTER; + } + + void* value = *(void**)data; + + if (value is null) + { + return E.E_POINTER; + } + + if (dataSize != (uint)sizeof(void*)) + { + return E.E_INVALIDARG; + } + + using ComPtr unknown = (IUnknown*)value; + using ComPtr transformMapper = default; + + // Check that the input object implements ID2D1TransformMapper + int result = unknown.CopyTo(transformMapper.GetAddressOf()); + + if (result != S.S_OK) + { + return result; + } + + // If there's already an existing manager, release it + if (@this->d2D1TransformMapper is not null) + { + _ = ((IUnknown*)@this->d2D1TransformMapper)->Release(); + } + + // Store the transform mapper manager into the effect + @this->d2D1TransformMapper = transformMapper.Detach(); return S.S_OK; } @@ -172,7 +304,12 @@ unsafe partial struct PixelShaderEffect using ComPtr resourceTextureManager = this.resourceTextureManagerBuffer[resourceTextureIndex]; - _ = resourceTextureManager.CopyTo((ID2D1ResourceTextureManager**)data); + HRESULT hresult = resourceTextureManager.CopyTo((ID2D1ResourceTextureManager**)data); + + if (!Windows.SUCCEEDED(hresult)) + { + return hresult; + } if (actualSize is not null) { diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs index 136112bc..d38561c2 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs @@ -3,6 +3,7 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; +using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; #if NET6_0_OR_GREATER @@ -18,14 +19,6 @@ namespace ComputeSharp.D2D1.Interop.Effects; /// internal unsafe partial struct PixelShaderEffect { - /// - /// A wrapper for an effect factory. - /// - /// The resulting effect factory. - /// The HRESULT for the operation. - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int FactoryDelegate(IUnknown** effectImpl); - #if !NET6_0_OR_GREATER /// [UnmanagedFunctionPointer(CallingConvention.StdCall)] @@ -196,9 +189,9 @@ internal unsafe partial struct PixelShaderEffect private D2D1ResourceTextureDescription* resourceTextureDescriptions; /// - /// The handle for the instance in use, if any. + /// The instance to use, if any. /// - private GCHandle d2D1TransformMapperHandle; + private ID2D1TransformMapper* d2D1TransformMapper; /// /// The instance currently in use. @@ -231,7 +224,6 @@ internal unsafe partial struct PixelShaderEffect /// The channel depth for the resulting output buffer. /// The number of available resource texture descriptions. /// The buffer with the available resource texture descriptions for the shader. - /// The instance to use for the effect. /// The resulting effect instance. /// This always returns 0. private static int Factory( @@ -248,7 +240,6 @@ internal unsafe partial struct PixelShaderEffect D2D1ChannelDepth channelDepth, int resourceTextureDescriptionCount, D2D1ResourceTextureDescription* resourceTextureDescriptions, - D2D1TransformMapper? d2D1TransformMapper, IUnknown** effectImpl) { PixelShaderEffect* @this; @@ -283,7 +274,7 @@ internal unsafe partial struct PixelShaderEffect @this->channelDepth = channelDepth; @this->resourceTextureDescriptionCount = resourceTextureDescriptionCount; @this->resourceTextureDescriptions = resourceTextureDescriptions; - @this->d2D1TransformMapperHandle = GCHandle.Alloc(d2D1TransformMapper); + @this->d2D1TransformMapper = null; @this->d2D1DrawInfo = null; @this->d2D1EffectContext = null; @this->resourceTextureManagerBuffer = default; @@ -347,7 +338,10 @@ internal unsafe partial struct PixelShaderEffect NativeMemory.Free(this.constantBuffer); } - this.d2D1TransformMapperHandle.Free(); + if (this.d2D1TransformMapper is not null) + { + _ = ((IUnknown*)this.d2D1TransformMapper)->Release(); + } if (this.d2D1DrawInfo is not null) { diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManager.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManager.cs index 959f5ffe..58c2875b 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManager.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManager.cs @@ -118,7 +118,7 @@ unsafe partial struct D2D1ResourceTextureManagerImpl } /// - /// The implementation for ID2D1ResourceTextureManager. + /// The implementation for . /// private static class ID2D1ResourceTextureManagerMethods { diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManagerInternal.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManagerInternal.cs index 9f7cc023..c8e9ba9f 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManagerInternal.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManagerInternal.cs @@ -13,7 +13,7 @@ namespace ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; partial struct D2D1ResourceTextureManagerImpl { /// - /// The implementation for ID2D1ResourceTextureManagerInternal. + /// The implementation for . /// private static unsafe class ID2D1ResourceTextureManagerInternalMethods { diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs index 31095856..100bc5b1 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs @@ -13,10 +13,11 @@ using RuntimeHelpers = ComputeSharp.D2D1.NetStandard.System.Runtime.CompilerServ namespace ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; /// -/// An implementation of the ID2D1ResourceTextureManager and ID2D1ResourceTextureManagerInternal interfaces. +/// An implementation of the and interfaces. /// internal unsafe partial struct D2D1ResourceTextureManagerImpl { +#if !NET6_0_OR_GREATER /// [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int QueryInterfaceDelegate(D2D1ResourceTextureManagerImpl* @this, Guid* riid, void** ppvObject); @@ -28,21 +29,22 @@ internal unsafe partial struct D2D1ResourceTextureManagerImpl /// [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate uint ReleaseDelegate(D2D1ResourceTextureManagerImpl* @this); +#endif /// - /// The shared vtable pointer for instance, for ID2D1ResourceTextureManager. + /// The shared vtable pointer for instance, for . /// private static readonly void** VtblForID2D1ResourceTextureManager = InitVtblForID2D1ResourceTextureManagerAndID2D1ResourceTextureManagerInternal(); /// - /// The shared vtable pointer for instance, for ID2D1ResourceTextureManagerInternal. + /// The shared vtable pointer for instance, for . /// private static readonly void** VtblForID2D1ResourceTextureManagerInternal = &VtblForID2D1ResourceTextureManager[5]; /// - /// Initializes the combined vtable for ID2D1ResourceTextureManager and ID2D1ResourceTextureManagerInternal. + /// Initializes the combined vtable for and . /// - /// The combined vtable for ID2D1ResourceTextureManager and ID2D1ResourceTextureManagerInternal. + /// The combined vtable for and . private static void** InitVtblForID2D1ResourceTextureManagerAndID2D1ResourceTextureManagerInternal() { void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(D2D1ResourceTextureManagerImpl), sizeof(void*) * 10); @@ -81,17 +83,17 @@ internal unsafe partial struct D2D1ResourceTextureManagerImpl } /// - /// The vtable pointer for the current instance, for ID2D1ResourceTextureManager. + /// The vtable pointer for the current instance, for . /// private void** lpVtblForID2D1ResourceTextureManager; /// - /// The vtable pointer for the current instance, for ID2D1ResourceTextureManagerInternal. + /// The vtable pointer for the current instance, for . /// private void** lpVtblForID2D1ResourceTextureManagerInternal; /// - /// The current reference count for the object (from IUnknown). + /// The current reference count for the object (from ). /// private volatile int referenceCount; diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/ID2D1ResourceTextureManager.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/ID2D1ResourceTextureManager.cs index 651f511c..370d8f9a 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/ID2D1ResourceTextureManager.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/ID2D1ResourceTextureManager.cs @@ -15,7 +15,7 @@ namespace ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; internal unsafe struct ID2D1ResourceTextureManager { /// - /// Gets the for ID2D1ResourceTextureManager (3C4FC7E4-A419-46CA-B5F6-66EB4FF18D64). + /// Gets the for (3C4FC7E4-A419-46CA-B5F6-66EB4FF18D64). /// public static ref readonly Guid Guid { @@ -54,7 +54,7 @@ internal unsafe struct ID2D1ResourceTextureManager /// The size, in bytes, of the data. /// An for the operation. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public int Initialize( + public HRESULT Initialize( Guid* resourceId, D2D1_RESOURCE_TEXTURE_PROPERTIES* resourceTextureProperties, byte* data, @@ -81,7 +81,7 @@ internal unsafe struct ID2D1ResourceTextureManager /// The size of the data buffer to be used to update the resource texture. /// An for the operation. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public int Update( + public HRESULT Update( uint* minimumExtents, uint* maximimumExtents, uint* strides, diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/ID2D1ResourceTextureManagerInternal.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/ID2D1ResourceTextureManagerInternal.cs index d8b7c894..e9bf555c 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/ID2D1ResourceTextureManagerInternal.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/ID2D1ResourceTextureManagerInternal.cs @@ -15,7 +15,7 @@ namespace ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; internal unsafe struct ID2D1ResourceTextureManagerInternal { /// - /// Gets the for ID2D1ResourceTextureManagerInternal (5CBB1024-8EA1-4689-81BF-8AD190B5EF5D). + /// Gets the for (5CBB1024-8EA1-4689-81BF-8AD190B5EF5D). /// public static ref readonly Guid Guid { @@ -44,13 +44,13 @@ internal unsafe struct ID2D1ResourceTextureManagerInternal private readonly void** lpVtbl; /// - /// Sets the for the current ID2D1ResourceTextureManagerInternal instance. + /// Sets the for the current instance. /// /// The input for the manager. /// A pointer to an optional amount of dimensions for the target resource texture, for validation. /// An for the operation. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public int Initialize(ID2D1EffectContext* effectContext, uint* dimensions) + public HRESULT Initialize(ID2D1EffectContext* effectContext, uint* dimensions) { return ((delegate* unmanaged[Stdcall])this.lpVtbl[3])( (ID2D1ResourceTextureManagerInternal*)Unsafe.AsPointer(ref this), @@ -64,7 +64,7 @@ internal unsafe struct ID2D1ResourceTextureManagerInternal /// The resulting instance. /// An for the operation. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public int GetResourceTexture(ID2D1ResourceTexture** resourceTexture) + public HRESULT GetResourceTexture(ID2D1ResourceTexture** resourceTexture) { return ((delegate* unmanaged[Stdcall])this.lpVtbl[4])( (ID2D1ResourceTextureManagerInternal*)Unsafe.AsPointer(ref this), diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1DrawInfoUpdateContextImpl.ID2D1DrawInfoUpdateContex.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1DrawInfoUpdateContextImpl.ID2D1DrawInfoUpdateContex.cs new file mode 100644 index 00000000..b39239ca --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1DrawInfoUpdateContextImpl.ID2D1DrawInfoUpdateContex.cs @@ -0,0 +1,166 @@ +using System; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; +#if !NET6_0_OR_GREATER +using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; +#endif + +namespace ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; + +/// +partial struct D2D1DrawInfoUpdateContextImpl +{ + /// + /// The implementation for . + /// + private static unsafe class ID2D1DrawInfoUpdateContextMethods + { +#if !NET6_0_OR_GREATER + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int GetConstantBufferSizeDelegate(D2D1DrawInfoUpdateContextImpl* @this, uint* size); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int GetConstantBufferDelegate(D2D1DrawInfoUpdateContextImpl* @this, byte* buffer, uint bufferCount); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int SetConstantBufferDelegate(D2D1DrawInfoUpdateContextImpl* @this, byte* buffer, uint bufferCount); + + /// + /// A cached instance wrapping . + /// + public static readonly QueryInterfaceDelegate QueryInterfaceWrapper = QueryInterface; + + /// + /// A cached instance wrapping . + /// + public static readonly AddRefDelegate AddRefWrapper = AddRef; + + /// + /// A cached instance wrapping . + /// + public static readonly ReleaseDelegate ReleaseWrapper = Release; + + /// + /// A cached instance wrapping . + /// + public static readonly GetConstantBufferSizeDelegate GetConstantBufferSizeWrapper = GetConstantBufferSize; + + /// + /// A cached instance wrapping . + /// + public static readonly GetConstantBufferDelegate GetConstantBufferWrapper = GetConstantBuffer; + + /// + /// A cached instance wrapping . + /// + public static readonly SetConstantBufferDelegate SetConstantBufferWrapper = SetConstantBuffer; +#endif + + /// + [UnmanagedCallersOnly] + public static int QueryInterface(D2D1DrawInfoUpdateContextImpl* @this, Guid* riid, void** ppvObject) + { + return @this->QueryInterface(riid, ppvObject); + } + + /// + [UnmanagedCallersOnly] + public static uint AddRef(D2D1DrawInfoUpdateContextImpl* @this) + { + return @this->AddRef(); + } + + /// + [UnmanagedCallersOnly] + public static uint Release(D2D1DrawInfoUpdateContextImpl* @this) + { + return @this->Release(); + } + + /// + [UnmanagedCallersOnly] + public static int GetConstantBufferSize(D2D1DrawInfoUpdateContextImpl* @this, uint* size) + { + if (size is null) + { + return E.E_POINTER; + } + + if (@this->d2D1DrawInfo is null) + { + return RO.RO_E_CLOSED; + } + + *size = (uint)@this->constantBufferSize; + + return S.S_OK; + } + + /// + [UnmanagedCallersOnly] + public static int GetConstantBuffer(D2D1DrawInfoUpdateContextImpl* @this, byte* buffer, uint bufferCount) + { + if (buffer is null) + { + return E.E_POINTER; + } + + if (bufferCount < @this->constantBufferSize) + { + return E.E_NOT_SUFFICIENT_BUFFER; + } + + if (@this->constantBuffer is null) + { + return E.E_NOT_VALID_STATE; + } + + if (@this->d2D1DrawInfo is null) + { + return RO.RO_E_CLOSED; + } + + if (@this->constantBufferSize > 0) + { + Buffer.MemoryCopy(@this->constantBuffer, buffer, bufferCount, @this->constantBufferSize); + } + + return S.S_OK; + } + + /// + [UnmanagedCallersOnly] + public static int SetConstantBuffer(D2D1DrawInfoUpdateContextImpl* @this, byte* buffer, uint bufferCount) + { + if (buffer is null) + { + return E.E_POINTER; + } + + if (bufferCount != (uint)@this->constantBufferSize) + { + return E.E_INVALIDARG; + } + + if (@this->d2D1DrawInfo is null) + { + return RO.RO_E_CLOSED; + } + + // If the buffer is empty, just do nothing + if (bufferCount == 0) + { + return S.S_OK; + } + + // Copy the buffer to the backing store, so the effect can also access it later + Buffer.MemoryCopy(buffer, @this->constantBuffer, bufferCount, bufferCount); + + // Propagate it to the ID2D1DrawInfo object in use as well + return @this->d2D1DrawInfo->SetPixelShaderConstantBuffer(buffer, bufferCount); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1DrawInfoUpdateContextImpl.ID2D1DrawInfoUpdateContexInternal.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1DrawInfoUpdateContextImpl.ID2D1DrawInfoUpdateContexInternal.cs new file mode 100644 index 00000000..8b283f73 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1DrawInfoUpdateContextImpl.ID2D1DrawInfoUpdateContexInternal.cs @@ -0,0 +1,88 @@ +using System; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; +#if !NET6_0_OR_GREATER +using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; +#endif + +namespace ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; + +/// +unsafe partial struct D2D1DrawInfoUpdateContextImpl +{ + /// + public int Close() + { + this.d2D1DrawInfo = null; + + return S.S_OK; + } + + /// + /// The implementation for . + /// + private static class ID2D1DrawInfoUpdateContextInternalMethods + { +#if !NET6_0_OR_GREATER + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int CloseDelegate(D2D1DrawInfoUpdateContextImpl* @this); + + /// + /// A cached instance wrapping . + /// + public static readonly QueryInterfaceDelegate QueryInterfaceWrapper = QueryInterface; + + /// + /// A cached instance wrapping . + /// + public static readonly AddRefDelegate AddRefWrapper = AddRef; + + /// + /// A cached instance wrapping . + /// + public static readonly ReleaseDelegate ReleaseWrapper = Release; + + /// + /// A cached instance wrapping . + /// + public static readonly CloseDelegate CloseWrapper = Close; +#endif + + /// + [UnmanagedCallersOnly] + public static int QueryInterface(D2D1DrawInfoUpdateContextImpl* @this, Guid* riid, void** ppvObject) + { + @this = (D2D1DrawInfoUpdateContextImpl*)&((void**)@this)[-1]; + + return @this->QueryInterface(riid, ppvObject); + } + + /// + [UnmanagedCallersOnly] + public static uint AddRef(D2D1DrawInfoUpdateContextImpl* @this) + { + @this = (D2D1DrawInfoUpdateContextImpl*)&((void**)@this)[-1]; + + return @this->AddRef(); + } + + /// + [UnmanagedCallersOnly] + public static uint Release(D2D1DrawInfoUpdateContextImpl* @this) + { + @this = (D2D1DrawInfoUpdateContextImpl*)&((void**)@this)[-1]; + + return @this->Release(); + } + + /// + [UnmanagedCallersOnly] + public static int Close(D2D1DrawInfoUpdateContextImpl* @this) + { + @this = (D2D1DrawInfoUpdateContextImpl*)&((void**)@this)[-1]; + + return @this->Close(); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1DrawInfoUpdateContextImpl.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1DrawInfoUpdateContextImpl.cs new file mode 100644 index 00000000..b49bdfbc --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1DrawInfoUpdateContextImpl.cs @@ -0,0 +1,206 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +#if NET6_0_OR_GREATER +using RuntimeHelpers = System.Runtime.CompilerServices.RuntimeHelpers; +#else +using RuntimeHelpers = ComputeSharp.D2D1.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +#endif + +namespace ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; + +/// +/// An implementation of the and interfaces. +/// +internal unsafe partial struct D2D1DrawInfoUpdateContextImpl +{ +#if !NET6_0_OR_GREATER + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int QueryInterfaceDelegate(D2D1DrawInfoUpdateContextImpl* @this, Guid* riid, void** ppvObject); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate uint AddRefDelegate(D2D1DrawInfoUpdateContextImpl* @this); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate uint ReleaseDelegate(D2D1DrawInfoUpdateContextImpl* @this); +#endif + + /// + /// The shared vtable pointer for instance, for . + /// + private static readonly void** VtblForID2D1DrawInfoUpdateContext = InitVtblForID2D1DrawInfoUpdateContextAndID2D1DrawInfoUpdateContextInternal(); + + /// + /// The shared vtable pointer for instance, for . + /// + private static readonly void** VtblForID2D1DrawInfoUpdateContextInternal = &VtblForID2D1DrawInfoUpdateContext[5]; + + /// + /// Initializes the combined vtable for and . + /// + /// The combined vtable for and . + private static void** InitVtblForID2D1DrawInfoUpdateContextAndID2D1DrawInfoUpdateContextInternal() + { + void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(D2D1DrawInfoUpdateContextImpl), sizeof(void*) * 10); + + // ID2D1ResourceTextureManager +#if NET6_0_OR_GREATER + lpVtbl[0] = (delegate* unmanaged)&ID2D1DrawInfoUpdateContextMethods.QueryInterface; + lpVtbl[1] = (delegate* unmanaged)&ID2D1DrawInfoUpdateContextMethods.AddRef; + lpVtbl[2] = (delegate* unmanaged)&ID2D1DrawInfoUpdateContextMethods.Release; + lpVtbl[3] = (delegate* unmanaged)&ID2D1DrawInfoUpdateContextMethods.GetConstantBufferSize; + lpVtbl[4] = (delegate* unmanaged)&ID2D1DrawInfoUpdateContextMethods.GetConstantBuffer; + lpVtbl[5] = (delegate* unmanaged)&ID2D1DrawInfoUpdateContextMethods.SetConstantBuffer; +#else + lpVtbl[0] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextMethods.QueryInterfaceWrapper); + lpVtbl[1] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextMethods.AddRefWrapper); + lpVtbl[2] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextMethods.ReleaseWrapper); + lpVtbl[3] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextMethods.GetConstantBufferSizeWrapper); + lpVtbl[4] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextMethods.GetConstantBufferWrapper); + lpVtbl[5] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextMethods.SetConstantBufferWrapper); +#endif + + // ID2D1ResourceTextureManagerInternal +#if NET6_0_OR_GREATER + lpVtbl[6 + 0] = (delegate* unmanaged)&ID2D1DrawInfoUpdateContextInternalMethods.QueryInterface; + lpVtbl[6 + 1] = (delegate* unmanaged)&ID2D1DrawInfoUpdateContextInternalMethods.AddRef; + lpVtbl[6 + 2] = (delegate* unmanaged)&ID2D1DrawInfoUpdateContextInternalMethods.Release; + lpVtbl[6 + 3] = (delegate* unmanaged)&ID2D1DrawInfoUpdateContextInternalMethods.Close; +#else + lpVtbl[6 + 0] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextInternalMethods.QueryInterfaceWrapper); + lpVtbl[6 + 1] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextInternalMethods.AddRefWrapper); + lpVtbl[6 + 2] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextInternalMethods.ReleaseWrapper); + lpVtbl[6 + 3] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextInternalMethods.CloseWrapper); +#endif + + return lpVtbl; + } + + /// + /// The vtable pointer for the current instance, for . + /// + private void** lpVtblForID2D1DrawInfoUpdateContext; + + /// + /// The vtable pointer for the current instance, for . + /// + private void** lpVtblForID2D1DrawInfoUpdateContextInternal; + + /// + /// The current reference count for the object (from ). + /// + private volatile int referenceCount; + + /// + /// The constant buffer data, if set. + /// + private byte* constantBuffer; + + /// + /// The size of . + /// + private int constantBufferSize; + + /// + /// The instance currently in use. + /// + private ID2D1DrawInfo* d2D1DrawInfo; + + /// + /// The factory method for instances. + /// + /// The resulting draw info update context instance. + /// The constant buffer data, if set. + /// The size of . + /// The instance currently in use. + /// This always returns 0. + public static HRESULT Factory( + D2D1DrawInfoUpdateContextImpl** drawInfoUpdateContext, + byte* constantBuffer, + int constantBufferSize, + ID2D1DrawInfo* d2D1DrawInfo) + { + D2D1DrawInfoUpdateContextImpl* @this; + + try + { + @this = (D2D1DrawInfoUpdateContextImpl*)NativeMemory.Alloc((nuint)sizeof(D2D1DrawInfoUpdateContextImpl)); + } + catch (OutOfMemoryException) + { + *drawInfoUpdateContext = null; + + return E.E_OUTOFMEMORY; + } + + @this->lpVtblForID2D1DrawInfoUpdateContext = VtblForID2D1DrawInfoUpdateContext; + @this->lpVtblForID2D1DrawInfoUpdateContextInternal = VtblForID2D1DrawInfoUpdateContextInternal; + @this->referenceCount = 1; + @this->constantBuffer = constantBuffer; + @this->constantBufferSize = constantBufferSize; + @this->d2D1DrawInfo = d2D1DrawInfo; + + *drawInfoUpdateContext = @this; + + return S.S_OK; + } + + /// + public int QueryInterface(Guid* riid, void** ppvObject) + { + if (ppvObject is null) + { + return E.E_POINTER; + } + + // ID2D1DrawInfoUpdateContext + if (riid->Equals(Windows.__uuidof()) || + riid->Equals(ID2D1DrawInfoUpdateContext.Guid)) + { + _ = Interlocked.Increment(ref this.referenceCount); + + *ppvObject = Unsafe.AsPointer(ref this); + + return S.S_OK; + } + + // ID2D1DrawInfoUpdateContextInternal + if (riid->Equals(ID2D1DrawInfoUpdateContextInternal.Guid)) + { + _ = Interlocked.Increment(ref this.referenceCount); + + *ppvObject = (void**)Unsafe.AsPointer(ref this) + 1; + + return S.S_OK; + } + + *ppvObject = null; + + return E.E_NOINTERFACE; + } + + /// + public uint AddRef() + { + return (uint)Interlocked.Increment(ref this.referenceCount); + } + + /// + public uint Release() + { + uint referenceCount = (uint)Interlocked.Decrement(ref this.referenceCount); + + if (referenceCount == 0) + { + NativeMemory.Free(Unsafe.AsPointer(ref this)); + } + + return referenceCount; + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.ID2D1TransformMapper.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.ID2D1TransformMapper.cs new file mode 100644 index 00000000..1dedba7f --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.ID2D1TransformMapper.cs @@ -0,0 +1,143 @@ +using System; +using System.Drawing; +using System.Runtime.CompilerServices; +#if NET6_0_OR_GREATER +using System.Runtime.InteropServices; +#endif +using ComputeSharp.D2D1.Extensions; +using ComputeSharp.D2D1.Interop.Effects; +using TerraFX.Interop.Windows; +#if !NET6_0_OR_GREATER +using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; +#endif + +namespace ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; + +/// +unsafe partial struct D2D1TransformMapperImpl +{ + /// + [UnmanagedCallersOnly] + private static int QueryInterface(D2D1TransformMapperImpl* @this, Guid* riid, void** ppvObject) + { + return @this->QueryInterface(riid, ppvObject); + } + + /// + [UnmanagedCallersOnly] + private static uint AddRef(D2D1TransformMapperImpl* @this) + { + return @this->AddRef(); + } + + /// + [UnmanagedCallersOnly] + private static uint Release(D2D1TransformMapperImpl* @this) + { + return @this->Release(); + } + + /// + [UnmanagedCallersOnly] + private static int MapInputRectsToOutputRect( + D2D1TransformMapperImpl* @this, + ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext, + RECT* inputRects, + RECT* inputOpaqueSubRects, + uint inputRectCount, + RECT* outputRect, + RECT* outputOpaqueSubRect) + { + Span inputs = stackalloc Rectangle[8].Slice(0, (int)inputRectCount); + Span opaqueInputs = stackalloc Rectangle[8].Slice(0, (int)inputRectCount); + + for (int i = 0; i < (int)inputRectCount; i++) + { + inputs[i] = inputRects[i].ToRectangle(); + opaqueInputs[i] = inputOpaqueSubRects[i].ToRectangle(); + } + + Rectangle output; + Rectangle opaqueOutput; + + // Invoke MapInputsToOutput and handle exceptions so they don't cross the ABI boundary + try + { + Unsafe.As(@this->transformMapperHandle.Target!).MapInputsToOutput( + d2D1DrawInfoUpdateContext, + inputs, + opaqueInputs, + out output, + out opaqueOutput); + } + catch (Exception e) + { + return e.HResult; + } + + *outputRect = output.ToRECT(); + *outputOpaqueSubRect = opaqueOutput.ToRECT(); + + return S.S_OK; + } + + /// + [UnmanagedCallersOnly] + private static int MapOutputRectToInputRects( + D2D1TransformMapperImpl* @this, + RECT* outputRect, + RECT* inputRects, + uint inputRectsCount) + { + Rectangle output = outputRect->ToRectangle(); + Span inputs = stackalloc Rectangle[8].Slice(0, (int)inputRectsCount); + + for (int i = 0; i < (int)inputRectsCount; i++) + { + inputs[i] = inputRects[i].ToRectangle(); + } + + // Handle exceptions, as mentioned above + try + { + Unsafe.As(@this->transformMapperHandle.Target!).MapOutputToInputs(in output, inputs); + } + catch (Exception e) + { + return e.HResult; + } + + for (int i = 0; i < (int)inputRectsCount; i++) + { + inputRects[i] = inputs[i].ToRECT(); + } + + return S.S_OK; + } + + /// + [UnmanagedCallersOnly] + private static int MapInvalidRect( + D2D1TransformMapperImpl* @this, + uint inputIndex, + RECT invalidInputRect, + RECT* invalidOutputRect) + { + Rectangle invalidInput = invalidInputRect.ToRectangle(); + Rectangle invalidOutput; + + // Handle exceptions once again + try + { + Unsafe.As(@this->transformMapperHandle.Target!).MapInvalidOutput((int)inputIndex, invalidInput, out invalidOutput); + } + catch (Exception e) + { + return e.HResult; + } + + *invalidOutputRect = invalidOutput.ToRECT(); + + return S.S_OK; + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.cs new file mode 100644 index 00000000..0454c6e2 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.cs @@ -0,0 +1,296 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using ComputeSharp.D2D1.Interop.Effects; +using TerraFX.Interop.Windows; +#if NET6_0_OR_GREATER +using RuntimeHelpers = System.Runtime.CompilerServices.RuntimeHelpers; +#else +using RuntimeHelpers = ComputeSharp.D2D1.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +#endif + +namespace ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; + +/// +/// An implementation of the interface wrapping . +/// +internal unsafe partial struct D2D1TransformMapperImpl +{ +#if !NET6_0_OR_GREATER + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int QueryInterfaceDelegate(D2D1TransformMapperImpl* @this, Guid* riid, void** ppvObject); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate uint AddRefDelegate(D2D1TransformMapperImpl* @this); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate uint ReleaseDelegate(D2D1TransformMapperImpl* @this); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int MapInputRectsToOutputRectDelegate( + D2D1TransformMapperImpl* @this, + ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext, + RECT* inputRects, + RECT* inputOpaqueSubRects, + uint inputRectCount, + RECT* outputRect, + RECT* outputOpaqueSubRect); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int MapOutputRectToInputRectsDelegate( + D2D1TransformMapperImpl* @this, + RECT* outputRect, + RECT* inputRects, + uint inputRectsCount); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int MapInvalidRectDelegate( + D2D1TransformMapperImpl* @this, + uint inputIndex, + RECT invalidInputRect, + RECT* invalidOutputRect); + + /// + /// A cached instance wrapping . + /// + private static readonly QueryInterfaceDelegate QueryInterfaceWrapper = QueryInterface; + + /// + /// A cached instance wrapping . + /// + private static readonly AddRefDelegate AddRefWrapper = AddRef; + + /// + /// A cached instance wrapping . + /// + private static readonly ReleaseDelegate ReleaseWrapper = Release; + + /// + /// A cached instance wrapping . + /// + private static readonly MapInputRectsToOutputRectDelegate MapInputRectsToOutputRectWrapper = MapInputRectsToOutputRect; + + /// + /// A cached instance wrapping . + /// + private static readonly MapOutputRectToInputRectsDelegate MapOutputRectToInputRectsWrapper = MapOutputRectToInputRects; + + /// + /// A cached instance wrapping . + /// + private static readonly MapInvalidRectDelegate MapInvalidRectWrapper = MapInvalidRect; +#endif + + /// + /// The shared method table pointer for all instances. + /// + private static readonly void** Vtbl = InitVtbl(); + + /// + /// Builds the custom method table pointer for . + /// + /// The method table pointer for . + private static void** InitVtbl() + { + void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(D2D1TransformMapperImpl), sizeof(void*) * 6); + +#if NET6_0_OR_GREATER + lpVtbl[0] = (delegate* unmanaged)&QueryInterface; + lpVtbl[1] = (delegate* unmanaged)&AddRef; + lpVtbl[2] = (delegate* unmanaged)&Release; + lpVtbl[3] = (delegate* unmanaged)&MapInputRectsToOutputRect; + lpVtbl[4] = (delegate* unmanaged)&MapOutputRectToInputRects; + lpVtbl[5] = (delegate* unmanaged)&MapInvalidRect; +#else + lpVtbl[0] = (void*)Marshal.GetFunctionPointerForDelegate(QueryInterfaceWrapper); + lpVtbl[1] = (void*)Marshal.GetFunctionPointerForDelegate(AddRefWrapper); + lpVtbl[2] = (void*)Marshal.GetFunctionPointerForDelegate(ReleaseWrapper); + lpVtbl[3] = (void*)Marshal.GetFunctionPointerForDelegate(MapInputRectsToOutputRectWrapper); + lpVtbl[4] = (void*)Marshal.GetFunctionPointerForDelegate(MapOutputRectToInputRectsWrapper); + lpVtbl[5] = (void*)Marshal.GetFunctionPointerForDelegate(MapInvalidRectWrapper); +#endif + + return lpVtbl; + } + + /// + /// The vtable pointer for the current instance. + /// + private void** lpVtbl; + + /// + /// The current reference count for the object (from ). + /// + private volatile int referenceCount; + + /// + /// A to the wrapped instance. + /// + private GCHandle transformMapperHandle; + + /// + /// The instance to synchronize accesses to this instance. + /// + private SpinLock spinLock; + + /// + /// The factory method for instances. + /// + /// The input instance to wrap. + /// The resulting instance. + public static void Factory( + ID2D1TransformMapperInterop transformMapper, + D2D1TransformMapperImpl** d2D1TransformMapperProxy) + { + D2D1TransformMapperImpl* @this = (D2D1TransformMapperImpl*)NativeMemory.Alloc((nuint)sizeof(D2D1TransformMapperImpl)); + + @this->lpVtbl = Vtbl; + @this->referenceCount = 1; + @this->transformMapperHandle = GCHandle.Alloc(transformMapper); + @this->spinLock = new SpinLock(enableThreadOwnerTracking: false); + + *d2D1TransformMapperProxy = @this; + } + + /// + /// Gets a reference to the instance used to synchronize reference counts. + /// + [UnscopedRef] + public ref SpinLock SpinLock => ref this.spinLock; + + /// + /// Ensures the target of the current CCW is tracked and is keeping it alive. + /// + /// The associated object to track. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void EnsureTargetIsTracked(ID2D1TransformMapperInterop target) + { + this.transformMapperHandle.Target = target; + } + + /// + /// Copies the current object onto a target pointer. + /// + /// The target pointer. + /// The for the operation. + /// This method must only be called if the caller has taken a lock on already. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void CopyToWithNoLock(ID2D1TransformMapper** transformMapper) + { + this.referenceCount++; + + *transformMapper = (ID2D1TransformMapper*)Unsafe.AsPointer(ref this); + } + + /// + /// + /// This method is the same as but skips locks. + /// This method must only be called if the caller has taken a lock on already. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int QueryInterfaceWithNoLock(Guid* riid, void** ppvObject) + { + if (ppvObject is null) + { + return E.E_POINTER; + } + + if (riid->Equals(Windows.__uuidof()) || + riid->Equals(ID2D1TransformMapper.Guid)) + { + this.referenceCount++; + + *ppvObject = Unsafe.AsPointer(ref this); + + return S.S_OK; + } + + *ppvObject = null; + + return E.E_NOINTERFACE; + } + + /// + private int QueryInterface(Guid* riid, void** ppvObject) + { + bool lockTaken = false; + + this.spinLock.Enter(ref lockTaken); + + try + { + return QueryInterfaceWithNoLock(riid, ppvObject); + } + finally + { + this.spinLock.Exit(); + } + } + + /// + private uint AddRef() + { + bool lockTaken = false; + + this.spinLock.Enter(ref lockTaken); + + try + { + return (uint)++this.referenceCount; + } + finally + { + this.spinLock.Exit(); + } + } + + /// + private uint Release() + { + bool lockTaken = false; + + this.spinLock.Enter(ref lockTaken); + + uint referenceCount; + + try + { + referenceCount = (uint)--this.referenceCount; + + // There are two special cases to consider here: + // - If the reference count is 1, it means that the D2D1TransformMapper object is the only + // thing keeping this CCW alive. In that case, we can reset the GC handle pointing back to it, + // so that it can be collected if nobody else is referencing it. This breaks the reference cycle + // between the two object, which would have otherwise caused them to remain alive forever. + // - If the reference count is 0, the object is simply being destroyed. This is moved outside of + // this try/finally block, as otherwise accessing the lock from the finally block would write to + // out of bounds memory (as the field is in native memory that has just been freed). + if (referenceCount == 1) + { + this.transformMapperHandle.Target = null; + } + } + finally + { + this.spinLock.Exit(); + } + + // Destroy the object if this was the last reference left (see notes above as to why this is here) + if (referenceCount == 0) + { + this.transformMapperHandle.Free(); + + NativeMemory.Free(Unsafe.AsPointer(ref this)); + } + + return referenceCount; + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/ID2D1DrawInfoUpdateContext.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/ID2D1DrawInfoUpdateContext.cs new file mode 100644 index 00000000..528a4437 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/ID2D1DrawInfoUpdateContext.cs @@ -0,0 +1,87 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; + +/// +/// The updater for type to use with built-in effects. +/// +[Guid("430C5B40-AE16-485F-90E6-4FA4915144B6")] +internal unsafe struct ID2D1DrawInfoUpdateContext +{ + /// + /// Gets the for (430C5B40-AE16-485F-90E6-4FA4915144B6). + /// + public static ref readonly Guid Guid + { + get + { + ReadOnlySpan data = new byte[] { + 0x40, 0x5B, 0x0C, 0x43, + 0x16, 0xAE, + 0x5F, 0x48, + 0x90, 0xE6, + 0x4F, + 0xA4, + 0x91, + 0x51, + 0x44, + 0xB6 + }; + + return ref Unsafe.As(ref MemoryMarshal.GetReference(data)); + } + } + + /// + /// The vtable for the current instance. + /// + private readonly void** lpVtbl; + + /// + /// Retrieves the size of the constant buffer for the current effect. + /// + /// The resulting size of the constant buffer. + /// An for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public HRESULT GetConstantBufferSize(uint* size) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[3])( + (ID2D1DrawInfoUpdateContext*)Unsafe.AsPointer(ref this), + size); + } + + /// + /// Retrieves the constant buffer data for the current effect. + /// + /// A pointer to the buffer to fill with the constant buffer data. + /// The size of the buffer provided through . + /// An for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public HRESULT GetConstantBuffer(byte* buffer, uint bufferCount) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[4])( + (ID2D1DrawInfoUpdateContext*)Unsafe.AsPointer(ref this), + buffer, + bufferCount); + } + + /// + /// Sets the constant buffer data for the current effect. + /// + /// A pointer to the constant buffer data to use to update the effect. + /// The size of the buffer provided through . + /// An for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public HRESULT SetConstantBuffer(byte* buffer, uint bufferCount) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[5])( + (ID2D1DrawInfoUpdateContext*)Unsafe.AsPointer(ref this), + buffer, + bufferCount); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/ID2D1DrawInfoUpdateContextInternal.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/ID2D1DrawInfoUpdateContextInternal.cs new file mode 100644 index 00000000..9ac8206d --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/ID2D1DrawInfoUpdateContextInternal.cs @@ -0,0 +1,54 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; + +/// +/// An internal version of that supports being closed, to manage lifetime scopes. +/// +[Guid("CF2F5BB0-3F5E-4D6E-8FF1-D9A7EB6C0250")] +internal unsafe struct ID2D1DrawInfoUpdateContextInternal +{ + /// + /// Gets the for (CF2F5BB0-3F5E-4D6E-8FF1-D9A7EB6C0250). + /// + public static ref readonly Guid Guid + { + get + { + ReadOnlySpan data = new byte[] { + 0xB0, 0x5B, 0x2F, 0xCF, + 0x5E, 0x3F, + 0x6E, 0x4D, + 0x8F, 0xF1, + 0xD9, + 0xA7, + 0xEB, + 0x6C, + 0x02, + 0x50 + }; + + return ref Unsafe.As(ref MemoryMarshal.GetReference(data)); + } + } + + /// + /// The vtable for the current instance. + /// + private readonly void** lpVtbl; + + /// + /// Closes the current instance. + /// + /// An for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public HRESULT Close() + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[3])((ID2D1DrawInfoUpdateContext*)Unsafe.AsPointer(ref this)); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/ID2D1TransformMapper.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/ID2D1TransformMapper.cs new file mode 100644 index 00000000..82f8327c --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/ID2D1TransformMapper.cs @@ -0,0 +1,113 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; + +/// +/// The transform mapper manager type to use with built-in effects. +/// +[Guid("02E6D48D-B892-4FBC-AA54-119203BAB802")] +internal unsafe struct ID2D1TransformMapper +{ + /// + /// Gets the for (02E6D48D-B892-4FBC-AA54-119203BAB802). + /// + public static ref readonly Guid Guid + { + get + { + ReadOnlySpan data = new byte[] { + 0x8D, 0xD4, 0xE6, 0x02, + 0x92, 0xB8, + 0xBC, 0x4F, + 0xAA, 0x54, + 0x11, + 0x92, + 0x03, + 0xBA, + 0xB8, + 0x02 + }; + + return ref Unsafe.As(ref MemoryMarshal.GetReference(data)); + } + } + + /// + /// The vtable for the current instance. + /// + private readonly void** lpVtbl; + + /// + /// Performs the inverse mapping to . + /// + /// The input instance. + /// An array of input rectangles to be mapped to the output rectangle. + /// An array of input rectangles to be mapped to the opaque output rectangle. + /// The number of inputs specified. + /// The output rectangle that maps to the corresponding input rectangle. + /// The output rectangle that maps to the corresponding opaque input rectangle. + /// An for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public HRESULT MapInputRectsToOutputRect( + ID2D1DrawInfoUpdateContext* updateContext, + RECT* inputRects, + RECT* inputOpaqueSubRects, + uint inputRectCount, + RECT* outputRect, + RECT* outputOpaqueSubRect) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[3])( + (ID2D1TransformMapper*)Unsafe.AsPointer(ref this), + updateContext, + inputRects, + inputOpaqueSubRects, + inputRectCount, + outputRect, + outputOpaqueSubRect); + } + + /// + /// 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 output rectangle from which the inputs must be mapped. + /// The corresponding set of inputs. The inputs will directly correspond to the transform inputs. + /// The number of inputs specified. + /// An for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public HRESULT MapOutputRectToInputRects( + RECT* outputRect, + RECT* inputRects, + uint inputRectsCount) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[4])( + (ID2D1TransformMapper*)Unsafe.AsPointer(ref this), + outputRect, + inputRects, + inputRectsCount); + } + + /// + /// Sets the input rectangles for this rendering pass into the transform. + /// + /// The index of the input rectangle. + /// The invalid input rectangle. + /// The output rectangle to which the input rectangle must be mapped. + /// An for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public HRESULT MapInvalidRect( + uint inputIndex, + RECT invalidInputRect, + RECT* invalidOutputRect) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[5])( + (ID2D1TransformMapper*)Unsafe.AsPointer(ref this), + inputIndex, + invalidInputRect, + invalidOutputRect); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Factories/Abstract/D2D1TransformMapperFactory{T, TParameters, TTransformMapper}.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Factories/Abstract/D2D1TransformMapperFactory{T, TParameters, TTransformMapper}.cs deleted file mode 100644 index 5350b0b0..00000000 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Factories/Abstract/D2D1TransformMapperFactory{T, TParameters, TTransformMapper}.cs +++ /dev/null @@ -1,24 +0,0 @@ -namespace ComputeSharp.D2D1.Shaders.Interop.Factories.Abstract; - -/// -/// A base type for a transform mapper factory to be used in a D2D1 pixel shader effect. -/// -/// The type of D2D1 pixel shader associated to the transform mapper. -/// The type of parameters that the transform mapper will use. -/// The type of concrete transform mapper to produce from this factory. -internal abstract class D2D1TransformMapperFactory : ID2D1TransformMapperFactory - where T : unmanaged, ID2D1PixelShader - where TParameters : unmanaged - where TTransformMapper : D2D1TransformMapper, new() -{ - /// - ID2D1TransformMapper ID2D1TransformMapperFactory.Create() - { - return new TTransformMapper { ParametersAccessor = ParametersAccessor }; - } - - /// - /// The instance to use to retrieve parameters for the transform mapper. - /// - public required D2D1TransformMapperParametersAccessor ParametersAccessor { get; init; } -} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Factories/Abstract/D2D1TransformMapperParametersAccessor{T, TParameters}.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Factories/Abstract/D2D1TransformMapperParametersAccessor{T, TParameters}.cs deleted file mode 100644 index 51f454ec..00000000 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Factories/Abstract/D2D1TransformMapperParametersAccessor{T, TParameters}.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace ComputeSharp.D2D1.Shaders.Interop.Factories.Abstract; - -/// -/// A base type for an accessor of parameters to be used in D2D1 transform mapping implementations. -/// -/// The type of D2D1 pixel shader associated to the transform mapper. -/// The type of parameters that the transform mapper will use. -internal abstract class D2D1TransformMapperParametersAccessor -{ - /// - /// Gets the parameters to be used by the transform mapper. - /// - /// The input D2D1 pixel shader being executed on the current effect (this can be used to retrieve shader properties). - /// The resulting parameters to be used by the transform mapper. - public abstract TParameters Get(in T shader); -} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Factories/Abstract/D2D1TransformMapper{T, TParameters}.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Factories/Abstract/D2D1TransformMapper{T, TParameters}.cs index 09a62ed5..5f602c97 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Factories/Abstract/D2D1TransformMapper{T, TParameters}.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Factories/Abstract/D2D1TransformMapper{T, TParameters}.cs @@ -1,11 +1,9 @@ using System; using System.Drawing; using System.Runtime.CompilerServices; -using ComputeSharp.D2D1.Interop.Effects; +using ComputeSharp.D2D1.Interop; using ComputeSharp.D2D1.Shaders.Interop.Helpers; -#pragma warning disable CS0618 - namespace ComputeSharp.D2D1.Shaders.Interop.Factories.Abstract; /// @@ -13,7 +11,7 @@ namespace ComputeSharp.D2D1.Shaders.Interop.Factories.Abstract; /// /// The type of D2D1 pixel shader associated to the transform mapper. /// The type of parameters that the transform mapper will use. -internal abstract class D2D1TransformMapper : D2D1TransformMapper, ID2D1TransformMapper +internal abstract class D2D1TransformMapper : D2D1TransformMapper where T : unmanaged, ID2D1PixelShader where TParameters : unmanaged { @@ -22,57 +20,15 @@ internal abstract class D2D1TransformMapper : D2D1TransformMappe /// private TParameters parameters; - /// - public D2D1TransformMapperParametersAccessor? ParametersAccessor { get; init; } - - /// - /// Transforms an input rectangle to an output rectangle. - /// - /// The parameters to be used to inform the transformation. - /// The input rectangle to transform to output. - protected abstract void TransformInputToOutput(in TParameters parameters, ref Rectangle64 rectangle); - - /// - /// Transforms an output rectangle to an input rectangle. - /// - /// The parameters to be used to inform the transformation. - /// The output rectangle to transform to input. - protected abstract void TransformOutputToInput(in TParameters parameters, ref Rectangle64 rectangle); - /// - public override void MapInputsToOutput(ReadOnlySpan buffer, ReadOnlySpan inputs, ReadOnlySpan opaqueInputs, out Rectangle output, out Rectangle opaqueOutput) + public override void MapInputsToOutput( + D2D1DrawInfoUpdateContext drawInfoUpdateContext, + ReadOnlySpan inputs, + ReadOnlySpan opaqueInputs, + out Rectangle output, + out Rectangle opaqueOutput) { - Unsafe.SkipInit(out T shader); - - shader.InitializeFromDispatchData(buffer); - - MapInputsToOutput(in shader, inputs, opaqueInputs, out output, out opaqueOutput); - } - - /// - public override void MapOutputToInputs(in Rectangle output, Span inputs) - { - Rectangle64 output64 = Rectangle64.FromRectangle(output); - - TransformOutputToInput(in this.parameters, ref output64); - - inputs.Fill(output64.ToRectangleWithD2D1LogicallyInfiniteClamping()); - } - - /// - public override void MapInvalidOutput(int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput) - { - Rectangle64 output64 = Rectangle64.FromRectangle(invalidInput); - - TransformInputToOutput(in this.parameters, ref output64); - - invalidOutput = output64.ToRectangleWithD2D1LogicallyInfiniteClamping(); - } - - /// - public void MapInputsToOutput(in T shader, ReadOnlySpan inputs, ReadOnlySpan opaqueInputs, out Rectangle output, out Rectangle opaqueOutput) - { - this.parameters = ParametersAccessor!.Get(in shader); + this.parameters = GetParameters(drawInfoUpdateContext); if (inputs.IsEmpty) { @@ -96,4 +52,44 @@ internal abstract class D2D1TransformMapper : D2D1TransformMappe opaqueOutput = Rectangle.Empty; } } + + /// + public override void MapOutputToInputs(in Rectangle output, Span inputs) + { + Rectangle64 output64 = Rectangle64.FromRectangle(output); + + TransformOutputToInput(in this.parameters, ref output64); + + inputs.Fill(output64.ToRectangleWithD2D1LogicallyInfiniteClamping()); + } + + /// + public override void MapInvalidOutput(int inputIndex, in Rectangle invalidInput, out Rectangle invalidOutput) + { + Rectangle64 output64 = Rectangle64.FromRectangle(invalidInput); + + TransformInputToOutput(in this.parameters, ref output64); + + invalidOutput = output64.ToRectangleWithD2D1LogicallyInfiniteClamping(); + } + + /// + /// Gets the values for the current transform mapper. + /// + /// The input value, which can be used to access and modify shader data. + protected abstract TParameters GetParameters(D2D1DrawInfoUpdateContext drawInfoUpdateContext); + + /// + /// Transforms an input rectangle to an output rectangle. + /// + /// The parameters to be used to inform the transformation. + /// The input rectangle to transform to output. + protected abstract void TransformInputToOutput(in TParameters parameters, ref Rectangle64 rectangle); + + /// + /// Transforms an output rectangle to an input rectangle. + /// + /// The parameters to be used to inform the transformation. + /// The output rectangle to transform to input. + protected abstract void TransformOutputToInput(in TParameters parameters, ref Rectangle64 rectangle); } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Factories/D2D1AffineTransformMapperFactory.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Factories/D2D1AffineTransformMapper{T}.cs similarity index 56% rename from src/ComputeSharp.D2D1/Shaders/Interop/Factories/D2D1AffineTransformMapperFactory.cs rename to src/ComputeSharp.D2D1/Shaders/Interop/Factories/D2D1AffineTransformMapper{T}.cs index 3e76e5b7..c7663a96 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Factories/D2D1AffineTransformMapperFactory.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Factories/D2D1AffineTransformMapper{T}.cs @@ -8,19 +8,19 @@ using ComputeSharp.D2D1.Shaders.Interop.Helpers; namespace ComputeSharp.D2D1.Shaders.Interop.Factories; /// -/// A container for shader-specific affine transform mapper factory. +/// Shared helpers for . /// /// /// This non-generic type is used so that and are not recompiled for each generic type instantiation. /// -internal sealed class D2D1AffineTransformMapperFactory +file static class D2D1AffineTransformMapper { /// /// Transforms a target rectangle using a given transform matrix. /// /// The transform matrix to use. /// The rectangle to transform. - private static void Transform(in Matrix3x2 matrix, ref Rectangle64 rectangle) + public static void Transform(in Matrix3x2 matrix, ref Rectangle64 rectangle) { // Get the rectangle corners Point64 topLeft = new(rectangle.Left, rectangle.Top); @@ -60,7 +60,7 @@ internal sealed class D2D1AffineTransformMapperFactory /// The value to subtract. /// The result of the subtraction, clamped to . [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static long SubtractAndClampToMaxIfOverflow(long x, long y) + public static long SubtractAndClampToMaxIfOverflow(long x, long y) { long z = unchecked(x - y); @@ -73,74 +73,68 @@ internal sealed class D2D1AffineTransformMapperFactory return z; } +} + +/// +/// A custom implementation for an affine transform. +/// +/// The type of D2D1 pixel shader associated to the transform mapper. +internal abstract class D2D1AffineTransformMapper : D2D1TransformMapper + where T : unmanaged, ID2D1PixelShader +{ + /// + protected sealed override void TransformInputToOutput(in Matrix3x2 parameters, ref Rectangle64 rectangle) + { + D2D1AffineTransformMapper.Transform(in parameters, ref rectangle); + } + + /// + protected sealed override void TransformOutputToInput(in Matrix3x2 parameters, ref Rectangle64 rectangle) + { + if (!Matrix3x2.Invert(parameters, out Matrix3x2 matrix)) + { + static void Throw() + { + throw new ArgumentException("The input transform matrix can't be inverted, so it can't be used for a transform mapper."); + } + + Throw(); + } + + D2D1AffineTransformMapper.Transform(in matrix, ref rectangle); + } /// - /// A custom implementation for an affine transform. + /// A implementation for a constant affine transform matrix. /// - /// The type of D2D1 pixel shader associated to the transform mapper. - public sealed class For : D2D1TransformMapperFactory.TransformMapper> - where T : unmanaged, ID2D1PixelShader + public sealed class ConstantMatrix : D2D1AffineTransformMapper { /// - /// A implementation for a constant affine transform matrix. + /// Gets the fixed affine transform matrix. /// - public sealed class ConstantMatrix : D2D1TransformMapperParametersAccessor - { - /// - /// Gets the fixed affine transform matrix. - /// - public Matrix3x2 Amount { get; init; } + public required Matrix3x2 Amount { get; init; } - /// - public override Matrix3x2 Get(in T shader) - { - return Amount; - } + /// + protected override Matrix3x2 GetParameters(D2D1DrawInfoUpdateContext drawInfoUpdateContext) + { + return Amount; } + } + /// + /// A implementation for a dynamic affine transform matrix. + /// + public sealed class DynamicMatrix : D2D1AffineTransformMapper + { /// - /// A implementation for a dynamic affine transform matrix. + /// Gets the instance to get the dynamic affine transform matrix. /// - public sealed class DynamicMatrix : D2D1TransformMapperParametersAccessor + public required D2D1TransformMapperFactory.Accessor Accessor { get; init; } + + /// + protected override Matrix3x2 GetParameters(D2D1DrawInfoUpdateContext drawInfoUpdateContext) { - /// - /// Gets the instance to get the dynamic affine transform matrix. - /// - public required D2D1TransformMapperFactory.Accessor Accessor { get; init; } - - /// - public override Matrix3x2 Get(in T shader) - { - return Accessor(in shader); - } - } - - /// - /// A custom implementation for an affine transform. - /// - public sealed class TransformMapper : D2D1TransformMapper - { - /// - protected override void TransformInputToOutput(in Matrix3x2 parameters, ref Rectangle64 rectangle) - { - Transform(in parameters, ref rectangle); - } - - /// - protected override void TransformOutputToInput(in Matrix3x2 parameters, ref Rectangle64 rectangle) - { - if (!Matrix3x2.Invert(parameters, out Matrix3x2 matrix)) - { - static void Throw() - { - throw new ArgumentException("The input transform matrix can't be inverted, so it can't be used for a transform mapper."); - } - - Throw(); - } - - Transform(in matrix, ref rectangle); - } + return Accessor(drawInfoUpdateContext.GetConstantBuffer()); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Factories/D2D1InflateTransformMapperFactory.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Factories/D2D1InflateTransformMapperFactory.cs deleted file mode 100644 index 873d911f..00000000 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Factories/D2D1InflateTransformMapperFactory.cs +++ /dev/null @@ -1,116 +0,0 @@ -using ComputeSharp.D2D1.Interop; -using ComputeSharp.D2D1.Shaders.Interop.Factories.Abstract; -using ComputeSharp.D2D1.Shaders.Interop.Helpers; - -namespace ComputeSharp.D2D1.Shaders.Interop.Factories; - -/// -/// A custom implementation for an inflate transform. -/// -/// The type of D2D1 pixel shader associated to the transform mapper. -internal sealed class D2D1InflateTransformMapperFactory : D2D1TransformMapperFactory.TransformMapper> - where T : unmanaged, ID2D1PixelShader -{ - /// - /// A implementation for a constant inflate amount. - /// - public sealed class ConstantAmount : D2D1TransformMapperParametersAccessor - { - /// - /// Gets the fixed inflate amount. - /// - public int Amount { get; init; } - - /// - public override (int, int, int, int) Get(in T shader) - { - return (Amount, Amount, Amount, Amount); - } - } - - /// - /// A implementation for a constant inflate LTRB amount. - /// - public sealed class ConstantLeftTopRightBottomAmount : D2D1TransformMapperParametersAccessor - { - /// - /// The constant left inflate amount. - /// - public int Left { get; init; } - - /// - /// The constant top inflate amount. - /// - public int Top { get; init; } - - /// - /// The constant right inflate amount. - /// - public int Right { get; init; } - - /// - /// The constant bottom inflate amount. - /// - public int Bottom { get; init; } - - /// - public override (int, int, int, int) Get(in T shader) - { - return (Left, Top, Right, Bottom); - } - } - - /// - /// A implementation for a dynamic inflate amount. - /// - public sealed class DynamicAmount : D2D1TransformMapperParametersAccessor - { - /// - /// Gets the instance to get the dynamic inflate amount. - /// - public required D2D1TransformMapperFactory.Accessor Accessor { get; init; } - - /// - public override (int, int, int, int) Get(in T shader) - { - int amount = Accessor!(in shader); - - return (amount, amount, amount, amount); - } - } - - /// - /// A implementation for a dynamic inflate LTRB amount. - /// - public sealed class DynamicLeftTopRightBottomAmount : D2D1TransformMapperParametersAccessor - { - /// - /// Gets the instance to get the dynamic inflate LTRB amount. - /// - public required D2D1TransformMapperFactory.Accessor<(int, int, int, int)> Accessor { get; init; } - - /// - public override (int, int, int, int) Get(in T shader) - { - return Accessor!(in shader); - } - } - - /// - /// A custom implementation for an inflate transform. - /// - public sealed class TransformMapper : D2D1TransformMapper - { - /// - protected override void TransformInputToOutput(in (int Left, int Top, int Right, int Bottom) parameters, ref Rectangle64 rectangle) - { - rectangle.Inflate(parameters.Left, parameters.Top, parameters.Right, parameters.Bottom); - } - - /// - protected override void TransformOutputToInput(in (int Left, int Top, int Right, int Bottom) parameters, ref Rectangle64 rectangle) - { - rectangle.Inflate(parameters.Left, parameters.Top, parameters.Right, parameters.Bottom); - } - } -} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Factories/D2D1InflateTransformMapper{T}.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Factories/D2D1InflateTransformMapper{T}.cs new file mode 100644 index 00000000..c01e4591 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Factories/D2D1InflateTransformMapper{T}.cs @@ -0,0 +1,110 @@ +using ComputeSharp.D2D1.Interop; +using ComputeSharp.D2D1.Shaders.Interop.Factories.Abstract; +using ComputeSharp.D2D1.Shaders.Interop.Helpers; + +namespace ComputeSharp.D2D1.Shaders.Interop.Factories; + +/// +/// A custom implementation for an inflate transform. +/// +/// The type of D2D1 pixel shader associated to the transform mapper. +internal abstract class D2D1InflateTransformMapper : D2D1TransformMapper + where T : unmanaged, ID2D1PixelShader +{ + /// + protected sealed override void TransformInputToOutput(in (int Left, int Top, int Right, int Bottom) parameters, ref Rectangle64 rectangle) + { + rectangle.Inflate(parameters.Left, parameters.Top, parameters.Right, parameters.Bottom); + } + + /// + protected sealed override void TransformOutputToInput(in (int Left, int Top, int Right, int Bottom) parameters, ref Rectangle64 rectangle) + { + rectangle.Inflate(parameters.Left, parameters.Top, parameters.Right, parameters.Bottom); + } + + /// + /// A implementation for a constant inflate amount. + /// + public sealed class ConstantAmount : D2D1InflateTransformMapper + { + /// + /// Gets the fixed inflate amount. + /// + public required int Amount { get; init; } + + /// + protected override (int Left, int Top, int Right, int Bottom) GetParameters(D2D1DrawInfoUpdateContext drawInfoUpdateContext) + { + return (Amount, Amount, Amount, Amount); + } + } + + /// + /// A implementation for a constant inflate LTRB amount. + /// + public sealed class ConstantLeftTopRightBottomAmount : D2D1InflateTransformMapper + { + /// + /// The constant left inflate amount. + /// + public required int Left { get; init; } + + /// + /// The constant top inflate amount. + /// + public required int Top { get; init; } + + /// + /// The constant right inflate amount. + /// + public required int Right { get; init; } + + /// + /// The constant bottom inflate amount. + /// + public required int Bottom { get; init; } + + /// + protected override (int Left, int Top, int Right, int Bottom) GetParameters(D2D1DrawInfoUpdateContext drawInfoUpdateContext) + { + return (Left, Top, Right, Bottom); + } + } + + /// + /// A implementation for a dynamic inflate amount. + /// + public sealed class DynamicAmount : D2D1InflateTransformMapper + { + /// + /// Gets the instance to get the dynamic inflate amount. + /// + public required D2D1TransformMapperFactory.Accessor Accessor { get; init; } + + /// + protected override (int Left, int Top, int Right, int Bottom) GetParameters(D2D1DrawInfoUpdateContext drawInfoUpdateContext) + { + int amount = Accessor(drawInfoUpdateContext.GetConstantBuffer()); + + return (amount, amount, amount, amount); + } + } + + /// + /// A implementation for a dynamic inflate LTRB amount. + /// + public sealed class DynamicLeftTopRightBottomAmount : D2D1InflateTransformMapper + { + /// + /// Gets the instance to get the dynamic inflate LTRB amount. + /// + public required D2D1TransformMapperFactory.Accessor<(int, int, int, int)> Accessor { get; init; } + + /// + protected override (int Left, int Top, int Right, int Bottom) GetParameters(D2D1DrawInfoUpdateContext drawInfoUpdateContext) + { + return Accessor(drawInfoUpdateContext.GetConstantBuffer()); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1DrawInfoDispatchDataLoader.cs b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1DrawInfoDispatchDataLoader.cs index 0f302f4b..88bf71d0 100644 --- a/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1DrawInfoDispatchDataLoader.cs +++ b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1DrawInfoDispatchDataLoader.cs @@ -2,6 +2,7 @@ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.Extensions; using TerraFX.Interop.DirectX; #pragma warning disable CS0618 @@ -31,8 +32,8 @@ internal readonly unsafe struct D2D1DrawInfoDispatchDataLoader : ID2D1DispatchDa /// void ID2D1DispatchDataLoader.LoadConstantBuffer(ReadOnlySpan data) { - _ = this.d2D1DrawInfo->SetPixelShaderConstantBuffer( + this.d2D1DrawInfo->SetPixelShaderConstantBuffer( buffer: (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data)), - bufferCount: (uint)data.Length); + bufferCount: (uint)data.Length).Assert(); } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1DrawInfoUpdateContextDispatchDataLoader.cs b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1DrawInfoUpdateContextDispatchDataLoader.cs new file mode 100644 index 00000000..74a3690d --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Loaders/D2D1DrawInfoUpdateContextDispatchDataLoader.cs @@ -0,0 +1,39 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.Extensions; +using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.Shaders.Loaders; + +/// +/// A data loader for D2D1 pixel shaders to be passed onto an object. +/// +internal readonly unsafe struct D2D1DrawInfoUpdateContextDispatchDataLoader : ID2D1DispatchDataLoader +{ + /// + /// The object in use. + /// + private readonly ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext; + + /// + /// Creates a new instance. + /// + /// The object to use. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal D2D1DrawInfoUpdateContextDispatchDataLoader(ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext) + { + this.d2D1DrawInfoUpdateContext = d2D1DrawInfoUpdateContext; + } + + /// + void ID2D1DispatchDataLoader.LoadConstantBuffer(ReadOnlySpan data) + { + this.d2D1DrawInfoUpdateContext->SetConstantBuffer( + buffer: (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data)), + bufferCount: (uint)data.Length).Assert(); + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems index d9f59f77..c62669ca 100644 --- a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems +++ b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems @@ -63,6 +63,7 @@ + \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/RO.cs b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/RO.cs new file mode 100644 index 00000000..1e972113 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/RO.cs @@ -0,0 +1,12 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from shared/winerror.h in the Windows SDK for Windows 10.0.22621.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.Windows; + +internal static partial class RO +{ + [NativeTypeName("#define RO_E_CLOSED _HRESULT_TYPEDEF_(0x80000013L)")] + public const int RO_E_CLOSED = unchecked((int)(0x80000013)); +} \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Tests/Assets/RadialFadeOut.png b/tests/ComputeSharp.D2D1.Tests/Assets/RadialFadeOut.png new file mode 100644 index 00000000..f84a286b Binary files /dev/null and b/tests/ComputeSharp.D2D1.Tests/Assets/RadialFadeOut.png differ diff --git a/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj b/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj index 56dd7bf9..5e1e0d94 100644 --- a/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj +++ b/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj @@ -95,6 +95,9 @@ PreserveNewest + + PreserveNewest + diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1EffectRegistrationDataTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1EffectRegistrationDataTests.cs index 31c16d92..712626f3 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1EffectRegistrationDataTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1EffectRegistrationDataTests.cs @@ -17,7 +17,7 @@ public partial class D2D1EffectRegistrationDataTests Assert.AreEqual(effectId, data.ClassId); Assert.AreEqual(2, data.NumberOfInputs); Assert.IsTrue(data.EffectFactory is not null); - Assert.AreEqual(17, data.PropertyBindings.Length); + Assert.AreEqual(18, data.PropertyBindings.Length); Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ConstantBuffer), data.PropertyBindings.Span[0].PropertyName); Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager0), data.PropertyBindings.Span[1].PropertyName); Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager1), data.PropertyBindings.Span[2].PropertyName); @@ -35,6 +35,7 @@ public partial class D2D1EffectRegistrationDataTests Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager13), data.PropertyBindings.Span[14].PropertyName); Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager14), data.PropertyBindings.Span[15].PropertyName); Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager15), data.PropertyBindings.Span[16].PropertyName); + Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.TransformMapper), data.PropertyBindings.Span[17].PropertyName); foreach (ref readonly D2D1PropertyBinding propertyBinding in data.PropertyBindings.Span) { @@ -104,6 +105,9 @@ public partial class D2D1EffectRegistrationDataTests + + + """, data.PropertyXml); } diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs index 49e06915..f6782eba 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs @@ -1,6 +1,5 @@ using System; using System.ComponentModel; -using System.Drawing; using ComputeSharp.D2D1.Interop; using ComputeSharp.D2D1.Tests.Effects; using ComputeSharp.D2D1.Tests.Helpers; @@ -23,42 +22,11 @@ public partial class D2D1PixelShaderEffectTests D2D1PixelShaderEffect.RegisterForD2D1Factory1(null, out _); } - [TestMethod] - [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)] - public unsafe void RegisterForD2D1Factory1_WithTransformMapper_NullD2D1Factory1() - { - D2D1PixelShaderEffect.RegisterForD2D1Factory1(null, out _); - } - - public sealed partial class DummyTransformMapper : ID2D1TransformMapper - { - public void MapInputsToOutput(in Shader shader, ReadOnlySpan inputs, ReadOnlySpan opaqueInputs, out Rectangle output, out Rectangle opaqueOutput) - { - output = default; - opaqueOutput = default; - } - - public void MapInvalidOutput(int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput) - { - invalidOutput = default; - } - - public void MapOutputToInputs(in Rectangle output, Span inputs) - { - } - - [D2DInputCount(0)] - public partial struct Shader : ID2D1PixelShader - { - public float4 Execute() => default; - } - } - [TestMethod] [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)] public unsafe void RegisterForD2D1Factory1_WithTransformMapperFactory_NullD2D1Factory1() { - D2D1PixelShaderEffect.RegisterForD2D1Factory1(null, null, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(null, out _); } [TestMethod] @@ -117,6 +85,20 @@ public partial class D2D1PixelShaderEffectTests D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect((void*)1, (D2D1ResourceTextureManager)null!, 0); } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)] + public unsafe void SetTransformMapperForD2D1Effect_RCW_NullD2D1Effect() + { + D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(null, (void*)1); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)] + public unsafe void SetTransformMapperForD2D1Effect_RCW_NullD2D1ResourceTextureManager() + { + D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect((void*)1, (D2D1TransformMapper)null!); + } + [TestMethod] [ExpectedException(typeof(Win32Exception))] public unsafe void NullConstantBuffer_DrawImageFails() @@ -125,7 +107,7 @@ public partial class D2D1PixelShaderEffectTests using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); using ComPtr d2D1Effect = default; @@ -156,7 +138,7 @@ public partial class D2D1PixelShaderEffectTests using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); using ComPtr d2D1Effect = default; diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1ResourceTextureManagerTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1ResourceTextureManagerTests.cs index 9f304859..61dd5d58 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1ResourceTextureManagerTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1ResourceTextureManagerTests.cs @@ -108,7 +108,7 @@ public partial class D2D1ResourceTextureManagerTests using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); using ComPtr resourceTextureManager = default; @@ -152,7 +152,7 @@ public partial class D2D1ResourceTextureManagerTests using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); D2D1ResourceTextureManager resourceTextureManager = new( extents: stackalloc uint[] { 128, 128 }, @@ -192,7 +192,7 @@ public partial class D2D1ResourceTextureManagerTests using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); using ComPtr d2D1Effect = default; @@ -251,7 +251,7 @@ public partial class D2D1ResourceTextureManagerTests using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); using ComPtr d2D1Effect = default; @@ -315,7 +315,7 @@ public partial class D2D1ResourceTextureManagerTests using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); using ComPtr d2D1Effect = default; @@ -373,7 +373,7 @@ public partial class D2D1ResourceTextureManagerTests using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!; string wallpaper0Path = Path.Combine(assemblyPath, "Assets", "Wallpaper0.png"); @@ -480,7 +480,7 @@ public partial class D2D1ResourceTextureManagerTests using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); using ComPtr d2D1Effect = default; @@ -567,7 +567,7 @@ public partial class D2D1ResourceTextureManagerTests using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); using ComPtr d2D1Effect = default; @@ -655,7 +655,7 @@ public partial class D2D1ResourceTextureManagerTests using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); using ComPtr d2D1Effect = default; @@ -758,7 +758,7 @@ public partial class D2D1ResourceTextureManagerTests using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); using ComPtr d2D1Effect = default; @@ -854,7 +854,7 @@ public partial class D2D1ResourceTextureManagerTests using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); using ComPtr d2D1Effect = default; diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1TransformMapperTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1TransformMapperTests.cs new file mode 100644 index 00000000..d72014fe --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/D2D1TransformMapperTests.cs @@ -0,0 +1,227 @@ +using System; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.Interop; +using ComputeSharp.D2D1.Tests.Helpers; +using ComputeSharp.D2D1.Tests.Shaders; +using ComputeSharp.Tests.Helpers; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Win32; +using Win32.Graphics.Direct2D; + +#pragma warning disable CS0649, IDE0044, IDE0065 + +namespace ComputeSharp.D2D1.Tests; + +using D2D1_MAPPED_RECT = MappedRect; +using Rectangle = System.Drawing.Rectangle; + +[TestClass] +[TestCategory("D2D1TransformMapper")] +public partial class D2D1TransformMapperTests +{ + [TestMethod] + public unsafe void VerifyInterfaces() + { + D2D1TransformMapper transformMapper = D2D1TransformMapperFactory.Inflate(4); + + using ComPtr unknown = default; + using ComPtr transformMapper2 = default; + + Guid uuidOfIUnknown = typeof(IUnknown).GUID; + Guid uuidOfTransformMapper = new("02E6D48D-B892-4FBC-AA54-119203BAB802"); + + // The object implements IUnknown and the transform mapper interface + Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)transformMapper).GetInterface(ref uuidOfIUnknown, out *(IntPtr*)unknown.GetAddressOf())); + Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)transformMapper).GetInterface(ref uuidOfTransformMapper, out *(IntPtr*)transformMapper2.GetAddressOf())); + + Assert.IsTrue(unknown.Get() is not null); + Assert.IsTrue(transformMapper2.Get() is not null); + + using ComPtr garbage = default; + + Guid uuidOfGarbage = Guid.NewGuid(); + + // Any other random QueryInterface should fail + Assert.AreEqual(CustomQueryInterfaceResult.Failed, ((ICustomQueryInterface)transformMapper).GetInterface(ref uuidOfGarbage, out *(IntPtr*)garbage.GetAddressOf())); + + Assert.IsTrue(garbage.Get() is null); + } + + [TestMethod] + public unsafe void VerifyReferenceCounting() + { + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); + + D2D1TransformMapper transformMapper = D2D1TransformMapperFactory.Inflate(4); + + using ComPtr transformMapper2 = default; + + Guid uuidOfTransformMapper = new("02E6D48D-B892-4FBC-AA54-119203BAB802"); + + Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)transformMapper).GetInterface(ref uuidOfTransformMapper, out *(IntPtr*)transformMapper2.GetAddressOf())); + + _ = transformMapper2.Get()->AddRef(); + + // Right after creation, the transform mapper has only 2 ref count (one is the managed object, one is this ComPtr) + Assert.AreEqual(2u, transformMapper2.Get()->Release()); + + using (ComPtr d2D1Effect = default) + { + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); + + D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(d2D1Effect.Get(), transformMapper); + + _ = transformMapper2.Get()->AddRef(); + + // After setting a transform mapper to an effect, the count raises to 3 + Assert.AreEqual(3u, transformMapper2.Get()->Release()); + + D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(d2D1Effect.Get(), transformMapper); + + _ = transformMapper2.Get()->AddRef(); + + // Adding the same transform mapper again doesn't increment ref count + Assert.AreEqual(3u, transformMapper2.Get()->Release()); + } + + _ = transformMapper2.Get()->AddRef(); + + // If the effect is released, that extra manager reference is also released + Assert.AreEqual(2u, transformMapper2.Get()->Release()); + } + + [D2DInputCount(0)] + private partial struct DummyShader : ID2D1PixelShader + { + public float4 Execute() + { + return default; + } + } + + [TestMethod] + public unsafe void UpdateConstantBufferFromTransformMapper() + { + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); + + using ComPtr d2D1Effect = default; + + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); + + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new ShaderWithDispatchArea(111, 222), d2D1Effect.Get()); + + DispatchAreaTransformMapper transformMapper = new() { ExpectedWidth = 111, ExpectedHeight = 222 }; + + D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(d2D1Effect.Get(), transformMapper); + + string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!; + string sourcePath = Path.Combine(assemblyPath, "Assets", "Landscape.png"); + string expectedPath = Path.Combine(assemblyPath, "Assets", "RadialFadeOut.png"); + + ReadOnlyMemory pixels = ImageHelper.LoadBitmapFromFile(sourcePath, out uint width, out uint height); + + using ComPtr d2D1BitmapSource = D2D1Helper.CreateD2D1BitmapAndSetAsSource(d2D1DeviceContext.Get(), pixels, width, height, d2D1Effect.Get()); + using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), width, height); + + D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get()); + + using ComPtr d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect); + + string destinationPath = Path.Combine(assemblyPath, "temp", $"{nameof(UpdateConstantBufferFromTransformMapper)}.png"); + + _ = Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!); + + ImageHelper.SaveBitmapToFile(destinationPath, width, height, d2D1MappedRect.pitch, d2D1MappedRect.bits); + + TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f); + } + + private sealed class DispatchAreaTransformMapper : D2D1TransformMapper + { + public int ExpectedWidth; + public int ExpectedHeight; + + public override void MapInputsToOutput( + D2D1DrawInfoUpdateContext drawInfoUpdateContext, + ReadOnlySpan inputs, + ReadOnlySpan opaqueInputs, + out Rectangle output, + out Rectangle opaqueOutput) + { + ShaderWithDispatchArea shader = drawInfoUpdateContext.GetConstantBuffer(); + + Assert.AreEqual(shader.Width, this.ExpectedWidth); + Assert.AreEqual(shader.Height, this.ExpectedHeight); + + shader.Width = inputs[0].Width; + shader.Height = inputs[0].Height; + + drawInfoUpdateContext.SetConstantBuffer(in shader); + + output = inputs[0]; + opaqueOutput = Rectangle.Empty; + } + + public override void MapInvalidOutput(int inputIndex, in Rectangle invalidInput, out Rectangle invalidOutput) + { + invalidOutput = invalidInput; + } + + public override void MapOutputToInputs(in Rectangle output, Span inputs) + { + inputs.Fill(output); + } + } + + [D2DInputCount(1)] + [D2DInputSimple(0)] + [D2DRequiresScenePosition] + [AutoConstructor] + private partial struct ShaderWithDispatchArea : ID2D1PixelShader + { + public int Width; + public int Height; + + public float4 Execute() + { + // Get the current integer coordinate and input color + int2 xy = (int2)D2D.GetScenePosition().XY; + float4 color = D2D.GetInput(0); + + // Calculate the center and size of the largest circle centered in the image + float2 center = new((uint)this.Width / 2, (uint)this.Height / 2); + int diameter = Hlsl.Min(this.Width, this.Height); + int radius = (int)((uint)diameter / 2); + + // Calculate the distance from the center, to adjust the fade out + float distance = Hlsl.Distance(xy, center); + float falloff = radius / 2u; + float alpha = 0; + + // If the pixel is close enough, keep it fully visible + if (distance <= falloff) + { + alpha = 1; + } + else if (distance <= radius) + { + // Otherwise, linearly fade it out until the outer radius is reached + float delta = radius - distance; + + alpha = delta / falloff; + } + + return new(color.RGB, alpha); + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs index c68de934..c3b1d893 100644 --- a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs +++ b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs @@ -317,8 +317,8 @@ public sealed partial class BokehBlurEffect d2D1DeviceContext.Get()->SetRenderingControls(&d2D1RenderingControls); // Register all necessary effects - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), VerticalConvolution.Transform, out _); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), HorizontalConvolutionAndAccumulatePartials.Transform, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); @@ -344,6 +344,10 @@ public sealed partial class BokehBlurEffect D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)verticalConvolutionEffectsForReals[i].GetAddressOf()); D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)verticalConvolutionEffectsForImaginaries[i].GetAddressOf()); D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)horizontalConvolutionEffects[i].GetAddressOf()); + + D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(verticalConvolutionEffectsForReals[i].Get(), VerticalConvolution.Transform); + D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(verticalConvolutionEffectsForImaginaries[i].Get(), VerticalConvolution.Transform); + D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(horizontalConvolutionEffects[i].Get(), HorizontalConvolutionAndAccumulatePartials.Transform); } // Create the border effect to clamp the input image @@ -494,9 +498,9 @@ public sealed partial class BokehBlurEffect private sealed partial class VerticalConvolution { /// - /// The for the shader. + /// The for the shader. /// - public static ID2D1TransformMapperFactory Transform { get; } = D2D1TransformMapperFactory.Inflate(static (in Shader shader) => (0, shader.kernelLength, 0, shader.kernelLength)); + public static D2D1TransformMapper Transform { get; } = D2D1TransformMapperFactory.Inflate(static (in Shader shader) => (0, shader.kernelLength, 0, shader.kernelLength)); /// /// Kernel for the vertical convolution pass for real or imaginary components. @@ -541,9 +545,9 @@ public sealed partial class BokehBlurEffect private sealed partial class HorizontalConvolutionAndAccumulatePartials { /// - /// The for the shader. + /// The for the shader. /// - public static ID2D1TransformMapperFactory Transform { get; } = D2D1TransformMapperFactory.Inflate(static (in Shader shader) => (shader.kernelLength, 0, shader.kernelLength, 0)); + public static D2D1TransformMapper Transform { get; } = D2D1TransformMapperFactory.Inflate(static (in Shader shader) => (shader.kernelLength, 0, shader.kernelLength, 0)); /// /// Kernel for the horizontal convolution pass. diff --git a/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1TestRunner.cs b/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1TestRunner.cs index 35ce6288..df176f89 100644 --- a/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1TestRunner.cs +++ b/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1TestRunner.cs @@ -22,7 +22,7 @@ internal static class D2D1TestRunner /// Executes a pixel shader and compares the expected results. /// /// The type of pixel shader to run. - /// A custom factory for the effect. + /// A custom instance for the effect. /// The name of the source image. /// The name of the expected result image. /// The name of the destination image to save results to. @@ -30,7 +30,7 @@ internal static class D2D1TestRunner /// The allowed difference threshold for the normalized delta. public static void RunAndCompareShader( in T shader, - ID2D1TransformMapperFactory? transformMapperFactory, + D2D1TransformMapper? transformMapper, string originalFileName, string expectedFileName, [CallerMemberName] string destinationFileName = "", @@ -49,7 +49,7 @@ internal static class D2D1TestRunner // Run the shader ExecutePixelShaderAndSaveToFile( in shader, - transformMapperFactory, + transformMapper, originalPath, destinationPath); @@ -104,12 +104,12 @@ internal static class D2D1TestRunner /// /// The shader type to execute. /// The shader to run. - /// A custom factory for the effect. + /// A custom instance for the effect. /// The source path for the image to run the shader on. /// The destination path for the result. private static unsafe void ExecutePixelShaderAndSaveToFile( in T shader, - ID2D1TransformMapperFactory? transformMapperFactory, + D2D1TransformMapper? transformMapper, string sourcePath, string destinationPath) where T : unmanaged, ID2D1PixelShader @@ -118,7 +118,7 @@ internal static class D2D1TestRunner using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), transformMapperFactory, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); using ComPtr d2D1Effect = default; @@ -126,6 +126,11 @@ internal static class D2D1TestRunner D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in shader, d2D1Effect.Get()); + if (transformMapper is not null) + { + D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(d2D1Effect.Get(), transformMapper); + } + ReadOnlyMemory pixels = ImageHelper.LoadBitmapFromFile(sourcePath, out uint width, out uint height); using ComPtr d2D1BitmapSource = D2D1Helper.CreateD2D1BitmapAndSetAsSource(d2D1DeviceContext.Get(), pixels, width, height, d2D1Effect.Get()); @@ -146,12 +151,12 @@ internal static class D2D1TestRunner /// The shader to run. /// The resulting width. /// The resulting height. - /// A custom factory for the effect. + /// A custom instance for the effect. /// The destination path for the result. /// The additional resource textures to use to run the shader. private static unsafe void ExecutePixelShaderAndSaveToFile( in T shader, - ID2D1TransformMapperFactory? transformMapperFactory, + D2D1TransformMapper? transformMapper, int width, int height, string destinationPath, @@ -162,7 +167,7 @@ internal static class D2D1TestRunner using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), transformMapperFactory, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); using ComPtr d2D1Effect = default; @@ -170,6 +175,11 @@ internal static class D2D1TestRunner D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in shader, d2D1Effect.Get()); + if (transformMapper is not null) + { + D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(d2D1Effect.Get(), transformMapper); + } + foreach ((int index, D2D1ResourceTextureManager resourceTextureManager) in resourceTextures) { D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager, index);