From 7a7e8d2b25c7994a9e0c18b2fd5706062aa81f83 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 13 Oct 2022 23:26:48 +0200 Subject: [PATCH 01/59] Add new ComputeSharp.D2D1.Uwp project --- ComputeSharp.sln | 10 +++++ .../ComputeSharp.Core.csproj | 1 + .../ComputeSharp.D2D1.Uwp.csproj | 41 +++++++++++++++++++ .../Directory.Build.props | 3 ++ .../Properties/AssemblyInfo.cs | 3 ++ 5 files changed, 58 insertions(+) create mode 100644 src/ComputeSharp.D2D1.Uwp/ComputeSharp.D2D1.Uwp.csproj create mode 100644 src/ComputeSharp.D2D1.Uwp/Directory.Build.props create mode 100644 src/ComputeSharp.D2D1.Uwp/Properties/AssemblyInfo.cs diff --git a/ComputeSharp.sln b/ComputeSharp.sln index e3314f79..651f9a1a 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -132,6 +132,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{B86A48A7-18B src\Directory.Build.targets = src\Directory.Build.targets EndProjectSection EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.D2D1.Uwp", "src\ComputeSharp.D2D1.Uwp\ComputeSharp.D2D1.Uwp.csproj", "{E60A3B1E-FC5D-41AC-ACF0-C2D75B6590D2}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 @@ -372,6 +374,14 @@ Global {C12D7ACE-98ED-4813-8118-6667C34F484F}.Release|ARM64.Build.0 = Release|ARM64 {C12D7ACE-98ED-4813-8118-6667C34F484F}.Release|x64.ActiveCfg = Release|x64 {C12D7ACE-98ED-4813-8118-6667C34F484F}.Release|x64.Build.0 = Release|x64 + {E60A3B1E-FC5D-41AC-ACF0-C2D75B6590D2}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {E60A3B1E-FC5D-41AC-ACF0-C2D75B6590D2}.Debug|ARM64.Build.0 = Debug|ARM64 + {E60A3B1E-FC5D-41AC-ACF0-C2D75B6590D2}.Debug|x64.ActiveCfg = Debug|x64 + {E60A3B1E-FC5D-41AC-ACF0-C2D75B6590D2}.Debug|x64.Build.0 = Debug|x64 + {E60A3B1E-FC5D-41AC-ACF0-C2D75B6590D2}.Release|ARM64.ActiveCfg = Release|ARM64 + {E60A3B1E-FC5D-41AC-ACF0-C2D75B6590D2}.Release|ARM64.Build.0 = Release|ARM64 + {E60A3B1E-FC5D-41AC-ACF0-C2D75B6590D2}.Release|x64.ActiveCfg = Release|x64 + {E60A3B1E-FC5D-41AC-ACF0-C2D75B6590D2}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/ComputeSharp.Core/ComputeSharp.Core.csproj b/src/ComputeSharp.Core/ComputeSharp.Core.csproj index 5b41e119..34bcb729 100644 --- a/src/ComputeSharp.Core/ComputeSharp.Core.csproj +++ b/src/ComputeSharp.Core/ComputeSharp.Core.csproj @@ -13,6 +13,7 @@ + diff --git a/src/ComputeSharp.D2D1.Uwp/ComputeSharp.D2D1.Uwp.csproj b/src/ComputeSharp.D2D1.Uwp/ComputeSharp.D2D1.Uwp.csproj new file mode 100644 index 00000000..625ed7db --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/ComputeSharp.D2D1.Uwp.csproj @@ -0,0 +1,41 @@ + + + uap10.0.17763 + 10.0 + 19041 + 17763 + $(TargetPlatformBaseVersion).$(TargetPlatformRevision).0 + $(TargetPlatformBaseVersion).$(TargetPlatformMinRevision).0 + Portable + true + true + true + true + true + $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb + ComputeSharp.D2D1.Uwp + x64;ARM64 + win10-x64;win-arm64 + $(NoWarn);NETSDK1023 + + + + ComputeSharp.D2D1.Uwp + ComputeSharp.D2D1.Uwp + A UWP library with APIs to leverage D2D1 functionality with D2D1 pixel shaders powered by ComputeSharp.D2D1 + $(PackageTags) uwp winui + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/Directory.Build.props b/src/ComputeSharp.D2D1.Uwp/Directory.Build.props new file mode 100644 index 00000000..7fbbecef --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/Directory.Build.props @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/Properties/AssemblyInfo.cs b/src/ComputeSharp.D2D1.Uwp/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..5777bd26 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/Properties/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.InteropServices; + +[assembly: ComVisible(false)] \ No newline at end of file From 58fadcab9b5edbe498e064e08624cbe7f332a9ea Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 13 Oct 2022 23:35:12 +0200 Subject: [PATCH 02/59] Add ICanvasImageInternal interface from Win2D --- .../GetImageFlags.cs | 45 +++++++++++++++++ .../ICanvasImageInternal.cs | 50 +++++++++++++++++++ .../ComputeSharp.D2D1.csproj | 4 ++ 3 files changed, 99 insertions(+) create mode 100644 src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/GetImageFlags.cs create mode 100644 src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInternal.cs diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/GetImageFlags.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/GetImageFlags.cs new file mode 100644 index 00000000..af94310b --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/GetImageFlags.cs @@ -0,0 +1,45 @@ +using System; + +namespace ABI.Microsoft.Graphics.Canvas; + +/// +/// Options for fine-tuning the behavior of ICanvasImageInternal::GetD2DImage. +/// +[Flags] +internal enum GetImageFlags +{ + /// + /// No options specified. + /// + None = 0, + + /// + /// Ignore the targetDpi parameter, read DPI from deviceContext instead. + /// + ReadDpiFromDeviceContext = 1, + + /// + /// Ignore the targetDpi parameter, always insert DPI compensation. + /// + AlwaysInsertDpiCompensation = 2, + + /// + /// Ignore the targetDpi parameter, never insert DPI compensation. + /// + NeverInsertDpiCompensation = 4, + + /// + /// Do the bare minimum to get back an ID2D1Image, no validation or recursive realization. + /// + MinimalRealization = 8, + + /// + /// Allow partially configured effect graphs where some inputs are . + /// + AllowNullEffectInputs = 16, + + /// + /// If an input is invalid, unrealize the effect and return rather than throwing. + /// + UnrealizeOnFailure = 32 +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInternal.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInternal.cs new file mode 100644 index 00000000..d9d5db96 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInternal.cs @@ -0,0 +1,50 @@ +using System.Runtime.InteropServices; +using System; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using TerraFX.Interop; + +namespace ABI.Microsoft.Graphics.Canvas; + +/// +/// Internal Win2D interface for all images and effects that can be drawn. +/// +[ComImport] +[Guid("2F434224-053C-4978-87C4-CFAAFA2F4FAC")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal unsafe interface ICanvasImageInternal +{ + /// + /// Gets an from an instance. + /// + /// A pointer to the return buffer to write the result into (needed for ABI matching). + /// The input canvas device (as pointer to internal interface). + /// + /// The device context in use. This value is is optional (but recommended), except when the + /// flag is specified. This is because + /// not all callers of have easy access to a context. It is always + /// possible to get a resource creation context from the device, but the context is only + /// actually necessary if a new effect realization needs to be created, so it is more efficient + /// to have the implementation do this lookup only if/when it turns out to be needed. + /// + /// The flags to use to get the image. + /// + /// The DPI of the target device context. This is used to determine when a D2D1DpiCompensation + /// effect needs to be inserted. Behavior of this parameter can be overridden by the flag values + /// , + /// or + /// + /// + /// The DPI of a source bitmap, or zero if the image does not have a fixed DPI. A D2D1DpiCompensation effect + /// will be inserted if and are different (flags permitting). + /// + /// A pointer to the resulting image (this value is the same as ). + [PreserveSig] + ID2D1Image** GetD2DImage( + ID2D1Image** retBuf, + [NativeTypeName("ICanvasDevice*")] IUnknown* device, + ID2D1DeviceContext* deviceContext, + GetImageFlags flags, + float targetDpi, + float* realizeDpi); +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/ComputeSharp.D2D1.csproj b/src/ComputeSharp.D2D1/ComputeSharp.D2D1.csproj index d80e2324..7a528d56 100644 --- a/src/ComputeSharp.D2D1/ComputeSharp.D2D1.csproj +++ b/src/ComputeSharp.D2D1/ComputeSharp.D2D1.csproj @@ -6,6 +6,10 @@ windows6.1 + + + + From 9069e2ac31ab7656b08024dc131714a28e035c8d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 13 Oct 2022 23:38:03 +0200 Subject: [PATCH 03/59] Add ICanvasResourceWrapperNative interface from Win2D --- .../ICanvasResourceWrapperNative.cs | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceWrapperNative.cs diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceWrapperNative.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceWrapperNative.cs new file mode 100644 index 00000000..7d877958 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceWrapperNative.cs @@ -0,0 +1,57 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace ABI.Microsoft.Graphics.Canvas; + +/// +/// An interop wrapper type for Win2D objects (see ). +/// +[Guid("5F10688D-EA55-4D55-A3B0-4DDB55C0C20A")] +[NativeTypeName("class ICanvasResourceWrapperNative : IUnknown")] +[NativeInheritance("IUnknown")] +internal unsafe struct ICanvasResourceWrapperNative +{ + public void** lpVtbl; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(0)] + public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[0])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(1)] + [return: NativeTypeName("ULONG")] + public uint AddRef() + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[1])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this)); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(2)] + [return: NativeTypeName("ULONG")] + public uint Release() + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[2])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this)); + } + + /// + /// Interface provided by various Win2D objects that is able to retrieve the wrapped resource. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(3)] + [return: NativeTypeName("HRESULT")] + public HRESULT GetNativeResource([NativeTypeName("ICanvasDevice*")] void* device, float dpi, [NativeTypeName("REFIID")] Guid* iid, void** resource) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[3])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this), device, dpi, iid, resource); + } +} \ No newline at end of file From 7391f674f24eba49502fe61793603cc4e98d13f3 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 14 Oct 2022 00:45:19 +0200 Subject: [PATCH 04/59] Add initial PixelShaderEffect implementation --- .../PixelShaderEffect{T}.cs | 93 +++++++++++++++++++ .../DirectX/um/d2d1_1/ID2D1DeviceContext.cs | 7 ++ 2 files changed, 100 insertions(+) create mode 100644 src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs new file mode 100644 index 00000000..6e727c0b --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs @@ -0,0 +1,93 @@ +using ABI.Microsoft.Graphics.Canvas; +using Microsoft.Graphics.Canvas; +using System.Numerics; +using System; +using Windows.Foundation; +using TerraFX.Interop.Windows; +using TerraFX.Interop.DirectX; +using ComputeSharp.D2D1.Interop; +using ComputeSharp.D2D1.Extensions; + +namespace ComputeSharp.D2D1.Uwp; + +/// +/// A custom implementation powered by a supplied shader type. +/// +/// The type of shader to use to render frames. +public sealed class PixelShaderEffect : ICanvasImage, ICanvasImageInternal + where T : unmanaged, ID2D1PixelShader +{ + /// + /// The current value in use. + /// + public T Value; + + private ComPtr effect; + + /// + public void Dispose() + { + } + + /// + Rect ICanvasImage.GetBounds(ICanvasResourceCreator resourceCreator) + { + throw new NotImplementedException(); + } + + /// + Rect ICanvasImage.GetBounds(ICanvasResourceCreator resourceCreator, Matrix3x2 transform) + { + throw new NotImplementedException(); + } + + /// + unsafe ID2D1Image** ICanvasImageInternal.GetD2DImage( + ID2D1Image** retBuf, + IUnknown* device, + ID2D1DeviceContext* deviceContext, + GetImageFlags flags, + float targetDpi, + float* realizeDpi) + { + if (realizeDpi is not null) + { + *realizeDpi = targetDpi; + } + + using ComPtr d2D1Image = default; + + if (this.effect.Get() is null) + { + using ComPtr d2D1Factory = default; + + deviceContext->GetFactory(d2D1Factory.GetAddressOf()); + + using ComPtr d2D1Factory1 = default; + + d2D1Factory.CopyTo(d2D1Factory1.GetAddressOf()).Assert(); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory1.Get(), out _); + + using ComPtr d2D1Effect = default; + + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(deviceContext, (void**)d2D1Effect.GetAddressOf()); + + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, d2D1Effect.Get()); + + this.effect = new(d2D1Effect.Get()); + + d2D1Effect.CopyTo(d2D1Image.GetAddressOf()).Assert(); + } + else + { + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.effect.Get()); + + this.effect.CopyTo(d2D1Image.GetAddressOf()).Assert(); + } + + *retBuf = d2D1Image.Detach(); + + return retBuf; + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1DeviceContext.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1DeviceContext.cs index 2e70f810..f2c97599 100644 --- a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1DeviceContext.cs +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1DeviceContext.cs @@ -19,6 +19,13 @@ internal unsafe partial struct ID2D1DeviceContext { public void** lpVtbl; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(3)] + public void GetFactory(ID2D1Factory** factory) + { + ((delegate* unmanaged[Stdcall])(lpVtbl[3]))((ID2D1DeviceContext*)Unsafe.AsPointer(ref this), factory); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(63)] public HRESULT CreateEffect([NativeTypeName("const IID &")] Guid* effectId, ID2D1Effect** effect) From 8580dceeef434f1ab22f7858ee25986d55a01d77 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 17 Oct 2022 13:02:12 +0200 Subject: [PATCH 05/59] Add IDirect3DDxgiInterfaceAccess and ID2D1Device1 --- .../DirectX/um/d2d1_2/ID2D1Device1.cs | 52 +++++++++++++++++++ .../TerraFX.Interop.Windows.D2D1.projitems | 2 + .../IDirect3DDxgiInterfaceAccess.cs | 52 +++++++++++++++++++ 3 files changed, 106 insertions(+) create mode 100644 src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_2/ID2D1Device1.cs create mode 100644 src/TerraFX.Interop.Windows.D2D1/WinRT/um/windows.graphics.directx.direct3d11.interop/IDirect3DDxgiInterfaceAccess.cs diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_2/ID2D1Device1.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_2/ID2D1Device1.cs new file mode 100644 index 00000000..193e8b8c --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_2/ID2D1Device1.cs @@ -0,0 +1,52 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1_2.h in the Windows SDK for Windows 10.0.22621.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +namespace TerraFX.Interop.DirectX; + +[Guid("D21768E1-23A4-4823-A14B-7C3EBA85D658")] +[NativeTypeName("struct ID2D1Device1 : ID2D1Device")] +[NativeInheritance("ID2D1Device")] +internal unsafe partial struct ID2D1Device1 +{ + public void** lpVtbl; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(0)] + public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[0]))((ID2D1Device1*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(1)] + [return: NativeTypeName("ULONG")] + public uint AddRef() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[1]))((ID2D1Device1*)Unsafe.AsPointer(ref this)); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(2)] + [return: NativeTypeName("ULONG")] + public uint Release() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[2]))((ID2D1Device1*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(3)] + public void GetFactory(ID2D1Factory** factory) + { + ((delegate* unmanaged[Stdcall])(lpVtbl[3]))((ID2D1Device1*)Unsafe.AsPointer(ref this), factory); + } +} \ 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 c62669ca..dbd3fde5 100644 --- a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems +++ b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems @@ -37,6 +37,7 @@ + @@ -51,6 +52,7 @@ + diff --git a/src/TerraFX.Interop.Windows.D2D1/WinRT/um/windows.graphics.directx.direct3d11.interop/IDirect3DDxgiInterfaceAccess.cs b/src/TerraFX.Interop.Windows.D2D1/WinRT/um/windows.graphics.directx.direct3d11.interop/IDirect3DDxgiInterfaceAccess.cs new file mode 100644 index 00000000..25ceb2d6 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/WinRT/um/windows.graphics.directx.direct3d11.interop/IDirect3DDxgiInterfaceAccess.cs @@ -0,0 +1,52 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/windows.graphics.directx.direct3d11.interop.h in the Windows SDK for Windows 10.0.22621.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +namespace TerraFX.Interop.WinRT; + +[Guid("A9B3D012-3DF2-4EE3-B8D1-8695F457D3C1")] +[NativeTypeName("struct IDirect3DDxgiInterfaceAccess : IUnknown")] +[NativeInheritance("IUnknown")] +internal unsafe partial struct IDirect3DDxgiInterfaceAccess +{ + public void** lpVtbl; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(0)] + public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[0]))((IDirect3DDxgiInterfaceAccess*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(1)] + [return: NativeTypeName("ULONG")] + public uint AddRef() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[1]))((IDirect3DDxgiInterfaceAccess*)Unsafe.AsPointer(ref this)); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(2)] + [return: NativeTypeName("ULONG")] + public uint Release() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[2]))((IDirect3DDxgiInterfaceAccess*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(3)] + public HRESULT GetInterface([NativeTypeName("const IID &")] Guid* iid, void** p) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[3]))((IDirect3DDxgiInterfaceAccess*)Unsafe.AsPointer(ref this), iid, p); + } +} \ No newline at end of file From 6143ceebd5633f665e482eb8bd190841051c778e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 17 Oct 2022 13:04:47 +0200 Subject: [PATCH 06/59] Add ComPtrExtensions.IsSameInstance extension --- .../Extensions/ComPtrExtensions.cs | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/ComputeSharp.D2D1.Uwp/Extensions/ComPtrExtensions.cs diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/ComPtrExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/ComPtrExtensions.cs new file mode 100644 index 00000000..8e51d066 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/ComPtrExtensions.cs @@ -0,0 +1,41 @@ +using ComputeSharp.D2D1.Extensions; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D2D1.Uwp.Extensions; + +/// +/// Helper methods for working with the type. +/// +internal static class ComPtrExtensions +{ + /// + /// Checks whether two values have the same underlying COM object. + /// + /// The type of the first value to check. + /// The type of the second value to check. + /// The first object to compare. + /// The second object to compare. + /// Whether and point to the same COM object. + public static unsafe bool IsSameInstance(this in ComPtr left, in ComPtr right) + where T : unmanaged + where U : unmanaged + { + if (left.Get() == right.Get()) + { + return true; + } + + if (left.Get() is null || right.Get() is null) + { + return false; + } + + using ComPtr leftUnknown = default; + using ComPtr rightUnknown = default; + + left.CopyTo(leftUnknown.GetAddressOf()).Assert(); + right.CopyTo(rightUnknown.GetAddressOf()).Assert(); + + return leftUnknown.Get() == rightUnknown.Get(); + } +} \ No newline at end of file From 2362b32df0fa8054613779080506055a23d071ca Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 18 Oct 2022 00:30:44 +0200 Subject: [PATCH 07/59] Switch Win2D bindings to ICanvasImageInterop --- ...lags.cs => CanvasImageGetD2DImageFlags.cs} | 11 +--- ...mageInternal.cs => ICanvasImageInterop.cs} | 38 ++++++----- .../PixelShaderEffect{T}.cs | 63 +++++++++++-------- 3 files changed, 63 insertions(+), 49 deletions(-) rename src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/{GetImageFlags.cs => CanvasImageGetD2DImageFlags.cs} (75%) rename src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/{ICanvasImageInternal.cs => ICanvasImageInterop.cs} (53%) diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/GetImageFlags.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/CanvasImageGetD2DImageFlags.cs similarity index 75% rename from src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/GetImageFlags.cs rename to src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/CanvasImageGetD2DImageFlags.cs index af94310b..613d6221 100644 --- a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/GetImageFlags.cs +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/CanvasImageGetD2DImageFlags.cs @@ -3,10 +3,10 @@ using System; namespace ABI.Microsoft.Graphics.Canvas; /// -/// Options for fine-tuning the behavior of ICanvasImageInternal::GetD2DImage. +/// Options for fine-tuning the behavior of . /// [Flags] -internal enum GetImageFlags +internal enum CanvasImageGetD2DImageFlags { /// /// No options specified. @@ -36,10 +36,5 @@ internal enum GetImageFlags /// /// Allow partially configured effect graphs where some inputs are . /// - AllowNullEffectInputs = 16, - - /// - /// If an input is invalid, unrealize the effect and return rather than throwing. - /// - UnrealizeOnFailure = 32 + AllowNullEffectInputs = 16 } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInternal.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs similarity index 53% rename from src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInternal.cs rename to src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs index d9d5db96..cdc4e71c 100644 --- a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInternal.cs +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs @@ -7,21 +7,29 @@ using TerraFX.Interop; namespace ABI.Microsoft.Graphics.Canvas; /// -/// Internal Win2D interface for all images and effects that can be drawn. +/// An interop Win2D interface for all images and effects that can be drawn. /// [ComImport] -[Guid("2F434224-053C-4978-87C4-CFAAFA2F4FAC")] +[Guid("E042D1F7-F9AD-4479-A713-67627EA31863")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] -internal unsafe interface ICanvasImageInternal +internal unsafe interface ICanvasImageInterop { /// - /// Gets an from an instance. + /// Gets the device that the effect is currently realized on, if any. /// - /// A pointer to the return buffer to write the result into (needed for ABI matching). - /// The input canvas device (as pointer to internal interface). + /// The resulting device, if available ((as a marshalled )). + /// The for the operation. + [PreserveSig] + [return: NativeTypeName("HRESULT")] + int GetDevice([NativeTypeName("ICanvasDevice**")] IUnknown** device); + + /// + /// Gets an from an instance. + /// + /// The input canvas device (as a marshalled ). /// /// The device context in use. This value is is optional (but recommended), except when the - /// flag is specified. This is because + /// flag is specified. This is because /// not all callers of have easy access to a context. It is always /// possible to get a resource creation context from the device, but the context is only /// actually necessary if a new effect realization needs to be created, so it is more efficient @@ -31,20 +39,22 @@ internal unsafe interface ICanvasImageInternal /// /// The DPI of the target device context. This is used to determine when a D2D1DpiCompensation /// effect needs to be inserted. Behavior of this parameter can be overridden by the flag values - /// , - /// or + /// , + /// or /// /// /// The DPI of a source bitmap, or zero if the image does not have a fixed DPI. A D2D1DpiCompensation effect /// will be inserted if and are different (flags permitting). /// - /// A pointer to the resulting image (this value is the same as ). + /// The resulting for the effect. + /// The for the operation. [PreserveSig] - ID2D1Image** GetD2DImage( - ID2D1Image** retBuf, + [return: NativeTypeName("HRESULT")] + int GetD2DImage( [NativeTypeName("ICanvasDevice*")] IUnknown* device, ID2D1DeviceContext* deviceContext, - GetImageFlags flags, + CanvasImageGetD2DImageFlags flags, float targetDpi, - float* realizeDpi); + float* realizeDpi, + ID2D1Image** ppImage); } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs index 6e727c0b..f6f7613e 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs @@ -14,7 +14,7 @@ namespace ComputeSharp.D2D1.Uwp; /// A custom implementation powered by a supplied shader type. /// /// The type of shader to use to render frames. -public sealed class PixelShaderEffect : ICanvasImage, ICanvasImageInternal +public sealed class PixelShaderEffect : ICanvasImage, ICanvasImageInterop where T : unmanaged, ID2D1PixelShader { /// @@ -42,52 +42,61 @@ public sealed class PixelShaderEffect : ICanvasImage, ICanvasImageInternal } /// - unsafe ID2D1Image** ICanvasImageInternal.GetD2DImage( - ID2D1Image** retBuf, + unsafe int ICanvasImageInterop.GetDevice(IUnknown** device) + { + return S.S_OK; + } + + /// + unsafe int ICanvasImageInterop.GetD2DImage( IUnknown* device, ID2D1DeviceContext* deviceContext, - GetImageFlags flags, + CanvasImageGetD2DImageFlags flags, float targetDpi, - float* realizeDpi) + float* realizeDpi, + ID2D1Image** ppImage) { if (realizeDpi is not null) { - *realizeDpi = targetDpi; + *realizeDpi = 0; } - using ComPtr d2D1Image = default; - - if (this.effect.Get() is null) + try { - using ComPtr d2D1Factory = default; + if (this.effect.Get() is null) + { + using ComPtr d2D1Factory = default; - deviceContext->GetFactory(d2D1Factory.GetAddressOf()); + deviceContext->GetFactory(d2D1Factory.GetAddressOf()); - using ComPtr d2D1Factory1 = default; + using ComPtr d2D1Factory1 = default; - d2D1Factory.CopyTo(d2D1Factory1.GetAddressOf()).Assert(); + d2D1Factory.CopyTo(d2D1Factory1.GetAddressOf()).Assert(); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory1.Get(), out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory1.Get(), out _); - using ComPtr d2D1Effect = default; + using ComPtr d2D1Effect = default; - D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(deviceContext, (void**)d2D1Effect.GetAddressOf()); + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(deviceContext, (void**)d2D1Effect.GetAddressOf()); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, d2D1Effect.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, d2D1Effect.Get()); - this.effect = new(d2D1Effect.Get()); + this.effect = new(d2D1Effect.Get()); - d2D1Effect.CopyTo(d2D1Image.GetAddressOf()).Assert(); + d2D1Effect.CopyTo(ppImage).Assert(); + } + else + { + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.effect.Get()); + + this.effect.CopyTo(ppImage).Assert(); + } + + return S.S_OK; } - else + catch (Exception e) { - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.effect.Get()); - - this.effect.CopyTo(d2D1Image.GetAddressOf()).Assert(); + return e.HResult; } - - *retBuf = d2D1Image.Detach(); - - return retBuf; } } \ No newline at end of file From 2d61226a005d4acab9e351268f0586bf4633a91c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 23 Oct 2022 20:44:11 +0200 Subject: [PATCH 08/59] Add reference tracking support to PixelShaderEffect --- .../ComputeSharp.D2D1.Uwp.csproj | 5 ++ .../PixelShaderEffect{T}.ReferenceTracking.cs | 52 +++++++++++++++++++ .../Graphics/Interop/ReferenceTracker.cs | 4 +- 3 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs diff --git a/src/ComputeSharp.D2D1.Uwp/ComputeSharp.D2D1.Uwp.csproj b/src/ComputeSharp.D2D1.Uwp/ComputeSharp.D2D1.Uwp.csproj index 625ed7db..6f4838da 100644 --- a/src/ComputeSharp.D2D1.Uwp/ComputeSharp.D2D1.Uwp.csproj +++ b/src/ComputeSharp.D2D1.Uwp/ComputeSharp.D2D1.Uwp.csproj @@ -26,6 +26,11 @@ $(PackageTags) uwp winui + + + + + diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs new file mode 100644 index 00000000..2babeb23 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs @@ -0,0 +1,52 @@ +using System; +using ComputeSharp.Interop; +using System.Runtime.CompilerServices; + +namespace ComputeSharp.D2D1.Uwp; + +/// +partial class PixelShaderEffect +{ + /// + /// Creates a new instance. + /// + public PixelShaderEffect() + { + this.referenceTracker = new(); + } + + /// + /// Releases unmanaged resources and performs other cleanup operations. + /// + ~PixelShaderEffect() + { + this.referenceTracker.Dispose(); + } + + /// + public void Dispose() + { + this.referenceTracker.Dispose(); + + GC.SuppressFinalize(this); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ref ReferenceTracker GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + ref ReferenceTracker IReferenceTrackedObject.GetReferenceTracker() + { + return ref this.referenceTracker; + } + + /// + void IReferenceTrackedObject.DangerousOnDispose() + { + // TODO + } +} \ No newline at end of file diff --git a/src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs b/src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs index df54a9d5..ae4c0587 100644 --- a/src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs +++ b/src/ComputeSharp/Graphics/Interop/ReferenceTracker.cs @@ -215,7 +215,7 @@ internal struct ReferenceTracker : IDisposable } /// - /// A reference tracking lease to extend the lifetime of a given instance while in a given scope. + /// A reference tracking lease to extend the lifetime of a given instance while in a given scope. /// /// /// This type must always be used in a statement and disposed properly. Not doing @@ -224,7 +224,7 @@ internal struct ReferenceTracker : IDisposable public struct Lease : IDisposable { /// - /// The instance being wrapped, if any. + /// The instance being wrapped, if any. /// private IReferenceTrackedObject? trackedObject; From 7a5142698841f1309632add834da14b2b53aa8b7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 23 Oct 2022 22:59:20 +0200 Subject: [PATCH 09/59] Add base ICanvasDevice interface from Win2D --- .../ICanvasDevice.cs | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasDevice.cs diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasDevice.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasDevice.cs new file mode 100644 index 00000000..32fc10b5 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasDevice.cs @@ -0,0 +1,46 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace ABI.Microsoft.Graphics.Canvas; + +/// +/// The native WinRT interface for objects. +/// +[Guid("A27F0B5D-EC2C-4D4F-948F-0AA1E95E33E6")] +[NativeTypeName("class ICanvasDevice : IInspectable")] +[NativeInheritance("IInspectable")] +internal unsafe struct ICanvasDevice +{ + public void** lpVtbl; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(0)] + public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[0])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(1)] + [return: NativeTypeName("ULONG")] + public uint AddRef() + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[1])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this)); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(2)] + [return: NativeTypeName("ULONG")] + public uint Release() + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[2])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this)); + } +} \ No newline at end of file From 139ad8ed628fb8ff1d700b620b7ec9e6106042fa Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 23 Oct 2022 23:00:13 +0200 Subject: [PATCH 10/59] Initial implementation port of ICanvasImageInterop from Win2D --- .../ICanvasImageInterop.cs | 4 +- .../Extensions/ICanvasDeviceExtensions.cs | 38 +++ .../Extensions/ID3D12DeviceExtensions.cs | 60 +++++ .../PixelShaderEffect{T}.ReferenceTracking.cs | 4 +- .../PixelShaderEffect{T}.cs | 250 +++++++++++++++--- .../DirectX/um/d2d1_1/ID2D1CommandList.cs | 17 ++ .../DirectX/um/d2d1_1/ID2D1DeviceContext.cs | 14 + .../TerraFX.Interop.Windows.D2D1.projitems | 1 + .../Windows/shared/winerror/D2DERR.cs | 3 + 9 files changed, 347 insertions(+), 44 deletions(-) create mode 100644 src/ComputeSharp.D2D1.Uwp/Extensions/ICanvasDeviceExtensions.cs create mode 100644 src/ComputeSharp.D2D1.Uwp/Extensions/ID3D12DeviceExtensions.cs create mode 100644 src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1CommandList.cs diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs index cdc4e71c..b62ce00f 100644 --- a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs @@ -21,7 +21,7 @@ internal unsafe interface ICanvasImageInterop /// The for the operation. [PreserveSig] [return: NativeTypeName("HRESULT")] - int GetDevice([NativeTypeName("ICanvasDevice**")] IUnknown** device); + int GetDevice(ICanvasDevice** device); /// /// Gets an from an instance. @@ -51,7 +51,7 @@ internal unsafe interface ICanvasImageInterop [PreserveSig] [return: NativeTypeName("HRESULT")] int GetD2DImage( - [NativeTypeName("ICanvasDevice*")] IUnknown* device, + ICanvasDevice* device, ID2D1DeviceContext* deviceContext, CanvasImageGetD2DImageFlags flags, float targetDpi, diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/ICanvasDeviceExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/ICanvasDeviceExtensions.cs new file mode 100644 index 00000000..9cdc9de8 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/ICanvasDeviceExtensions.cs @@ -0,0 +1,38 @@ +using ABI.Microsoft.Graphics.Canvas; +using ComputeSharp.D2D1.Extensions; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using Win32 = TerraFX.Interop.Windows.Windows; + +namespace ComputeSharp.D2D1.Uwp.Extensions; + +/// +/// A with extensions for the type. +/// +internal static unsafe class ICanvasDeviceExtensions +{ + /// + /// Gets the underlying object from an object. + /// + /// The input object. + /// The underlying object for . + /// The for the operation. + public static HRESULT GetD2DDevice(this ref ICanvasDevice canvasDevice, ID2D1Device1** d2D1Device1) + { + using ComPtr canvasDeviceResourceWrapperNative = default; + + // Get the ICanvasResourceWrapperNative wrapper around the input device + canvasDevice.QueryInterface( + riid: Win32.__uuidof(), + ppvObject: (void**)canvasDeviceResourceWrapperNative.GetAddressOf()).Assert(); + + // Get the underlying ID2D1Device1 instance in use + HRESULT hresult = canvasDeviceResourceWrapperNative.Get()->GetNativeResource( + device: null, + dpi: 0, + iid: Win32.__uuidof(), + resource: (void**)d2D1Device1); + + return hresult; + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/ID3D12DeviceExtensions.cs new file mode 100644 index 00000000..5e6b46fb --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/ID3D12DeviceExtensions.cs @@ -0,0 +1,60 @@ +using ComputeSharp.D2D1.Extensions; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D2D1.Uwp.Extensions; + +/// +/// A with extensions for the type. +/// +internal static unsafe class ID2D1DeviceContextExtensions +{ + /// + /// Checks whether a given has an as render target. + /// + /// The input instance to check. + /// Whether the target of is an . + public static bool HasCommandListTarget(this ref ID2D1DeviceContext deviceContext) + { + using ComPtr d2D1Image = default; + + // First get the target and check that it is not null + deviceContext.GetTarget(d2D1Image.GetAddressOf()); + + if (d2D1Image.Get() is null) + { + return false; + } + + using ComPtr d2D1CommandList = default; + + // If there is a target, check if it is an ID2D1CommandList + HRESULT hresult = d2D1Image.CopyTo(d2D1CommandList.GetAddressOf()); + + // Special case E_NOINTERFACE: this should return false and it's not an error + if (hresult == E.E_NOINTERFACE) + { + return false; + } + + // Throw for any other failure + hresult.Assert(); + + return true; + } + + /// + /// Reads the DPI value from a target object. + /// + /// The input instance. + /// The DPIs from . + public static float GetDpi(this ref ID2D1DeviceContext deviceContext) + { + float dpiX; + float dpiY; + + deviceContext.GetDpi(&dpiX, &dpiY); + + return dpiX; + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs index 2babeb23..49ca9198 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs @@ -47,6 +47,8 @@ partial class PixelShaderEffect /// void IReferenceTrackedObject.DangerousOnDispose() { - // TODO + this.canvasDevice.Dispose(); + this.d2D1RealizationDevice.Dispose(); + this.d2D1Effect.Dispose(); } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs index f6f7613e..d8b95f47 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs @@ -1,12 +1,16 @@ -using ABI.Microsoft.Graphics.Canvas; -using Microsoft.Graphics.Canvas; -using System.Numerics; using System; -using Windows.Foundation; -using TerraFX.Interop.Windows; -using TerraFX.Interop.DirectX; -using ComputeSharp.D2D1.Interop; +using System.Numerics; +using System.Threading; +using ABI.Microsoft.Graphics.Canvas; using ComputeSharp.D2D1.Extensions; +using ComputeSharp.D2D1.Interop; +using ComputeSharp.D2D1.Uwp.Extensions; +using ComputeSharp.Interop; +using Microsoft.Graphics.Canvas; +using Windows.Foundation; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using Win32 = TerraFX.Interop.Windows.Windows; namespace ComputeSharp.D2D1.Uwp; @@ -14,89 +18,253 @@ namespace ComputeSharp.D2D1.Uwp; /// A custom implementation powered by a supplied shader type. /// /// The type of shader to use to render frames. -public sealed class PixelShaderEffect : ICanvasImage, ICanvasImageInterop +public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICanvasImage, ICanvasImageInterop where T : unmanaged, ID2D1PixelShader { + /// + /// The value for the current instance. + /// + private ReferenceTracker referenceTracker; + + /// + /// Lock object used to synchronize calls to APIs. + /// + private readonly object lockObject = new(); + + /// + /// Flag to track whether a given call is recursively invoked by , to avoid graph cycles. + /// + private volatile int isInsideGetD2DImage; + + /// + /// The current device the effect is realized on, if one is available (this is the underlying COM object for ). + /// + private ComPtr canvasDevice; + + /// + /// The underlying D2D1 device the effect is realized on, if one is available (this is the D2D device backing ). + /// + private ComPtr d2D1RealizationDevice; + + /// + /// The current realized , if one is available. + /// + private ComPtr d2D1Effect; + /// /// The current value in use. /// public T Value; - private ComPtr effect; - - /// - public void Dispose() - { - } - /// Rect ICanvasImage.GetBounds(ICanvasResourceCreator resourceCreator) { - throw new NotImplementedException(); + throw new NotSupportedException(); } /// Rect ICanvasImage.GetBounds(ICanvasResourceCreator resourceCreator, Matrix3x2 transform) { - throw new NotImplementedException(); + throw new NotSupportedException(); } /// - unsafe int ICanvasImageInterop.GetDevice(IUnknown** device) + unsafe int ICanvasImageInterop.GetDevice(ICanvasDevice** device) { - return S.S_OK; + using ReferenceTracker.Lease _0 = GetReferenceTracker().TryGetLease(out bool leaseTaken); + + // Check for disposal + if (!leaseTaken) + { + return RO.RO_E_CLOSED; + } + + // Ensure we can take a lock without blocking. We can't access the realization device with no + // lock, as that could lead to memory leaks or corruption if GetD2DImage was to manipulate that + // field concurrently. We also cannot lock directly, because that would deadlock if someone was + // to (incorrectly) try to use the same effect from two different threads. To protect against + // that, we try to lock, and just return E_NOT_VALID_STATE if another thread holds the lock. If + // this call had GetD2DImage in the stack, that would work fine because locks are recursive. + if (!Monitor.TryEnter(this.lockObject)) + { + return E.E_NOT_VALID_STATE; + } + + try + { + // Copy the device over to the target + return this.canvasDevice.CopyTo(device); + } + finally + { + Monitor.Exit(this.lockObject); + } } /// unsafe int ICanvasImageInterop.GetD2DImage( - IUnknown* device, + ICanvasDevice* device, ID2D1DeviceContext* deviceContext, CanvasImageGetD2DImageFlags flags, float targetDpi, float* realizeDpi, ID2D1Image** ppImage) { - if (realizeDpi is not null) + using ReferenceTracker.Lease _0 = GetReferenceTracker().TryGetLease(out bool leaseTaken); + + // Check for disposal + if (!leaseTaken) { - *realizeDpi = 0; + return RO.RO_E_CLOSED; + } + + // Check for graph cycles + if (Interlocked.CompareExchange(ref this.isInsideGetD2DImage, 1, 0) == 1) + { + return D2DERR.D2DERR_CYCLIC_GRAPH; } try { - if (this.effect.Get() is null) + // Lock after checking for graph cycles (other public APIs also lock on this object) + lock (this.lockObject) { - using ComPtr d2D1Factory = default; + // Process the ReadDpiFromDeviceContext flag (same logic as CanvasEffect::GetD2DImage) + if ((flags & CanvasImageGetD2DImageFlags.ReadDpiFromDeviceContext) != CanvasImageGetD2DImageFlags.None) + { + // If ReadDpiFromDeviceContext is used, the context cannot be null + if (deviceContext is null) + { + return E.E_POINTER; + } - deviceContext->GetFactory(d2D1Factory.GetAddressOf()); + if (deviceContext->HasCommandListTarget()) + { + // Command lists are DPI dependent, so DPI compensation effects are always needed + flags |= CanvasImageGetD2DImageFlags.AlwaysInsertDpiCompensation; + } + else + { + // If the effect is not being drawn onto a command list, the DPIs can be read from the device context + targetDpi = deviceContext->GetDpi(); + } - using ComPtr d2D1Factory1 = default; + // ReadDpiFromDeviceContext has been processed, so it can be removed now + flags &= ~CanvasImageGetD2DImageFlags.ReadDpiFromDeviceContext; + } - d2D1Factory.CopyTo(d2D1Factory1.GetAddressOf()).Assert(); + using ComPtr d2D1Device1 = default; - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory1.Get(), out _); + // Get the underlying ID2D1Device1 instance in use + device->GetD2DDevice(d2D1Device1.GetAddressOf()).Assert(); - using ComPtr d2D1Effect = default; + // Check that the input D2D device is the same instance as the current realization device, if any. + // If not and the effect has already been realized, unrealize it and store the new device to use. + if (!d2D1Device1.IsSameInstance(in this.d2D1RealizationDevice)) + { + Unrealize(); - D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(deviceContext, (void**)d2D1Effect.GetAddressOf()); + // Store the input realization device and canvas device for future uses + d2D1Device1.CopyTo(ref this.d2D1RealizationDevice).Assert(); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, d2D1Effect.Get()); + fixed (ICanvasDevice** canvasDevice = this.canvasDevice) + { + device->QueryInterface(Win32.__uuidof(), (void**)canvasDevice).Assert(); + } + } - this.effect = new(d2D1Effect.Get()); + // Create the effect, if it doesn't exist already + if (this.d2D1Effect.Get() is null) + { + Realize(flags, targetDpi, deviceContext); + } + else if (!flags.HasFlag(CanvasImageGetD2DImageFlags.MinimalRealization)) + { + // Recurse through the effect graph and ensure all nodes are initialized + RefreshInputs(flags, targetDpi, deviceContext); + } - d2D1Effect.CopyTo(ppImage).Assert(); + // The realized DPIs are always 0 for pixel shader effects + if (realizeDpi is not null) + { + *realizeDpi = 0; + } + + this.d2D1Effect.CopyTo(ppImage).Assert(); + + return S.S_OK; } - else - { - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.effect.Get()); - - this.effect.CopyTo(ppImage).Assert(); - } - - return S.S_OK; } catch (Exception e) { + *ppImage = null; + return e.HResult; } + finally + { + // Ensure that reset this flag so that this method can be called again + this.isInsideGetD2DImage = 0; + } + } + + /// + /// Unrealizes the currently realized object. + /// + private unsafe void Unrealize() + { + // If there is no ID2D1Effect object, there is nothing left to do + if (this.d2D1Effect.Get() is null) + { + return; + } + + // TODO + } + + /// + /// Realizes the underlying for this object. + /// + /// The current flags in use. + /// The target DPI in use. + /// The instance in use. + private unsafe void Realize(CanvasImageGetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) + { + using ComPtr d2D1Factory = default; + + // Get the underlying ID2D1Factory from the input context, so we can register and create the effect + deviceContext->GetFactory(d2D1Factory.GetAddressOf()); + + using ComPtr d2D1Factory1 = default; + + // D2D1PixelShaderEffect APIs specifically need an ID2D1Factory1 (as ID2D1Factory1::RegisterEffectFromString is used) + d2D1Factory.CopyTo(d2D1Factory1.GetAddressOf()).Assert(); + + // Register the effect with the factory (TODO: only do this if needed) + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory1.Get(), out _); + + fixed (ID2D1Effect** d2D1Effect = this.d2D1Effect) + { + // Create an instance of the effect in use and store it in the current object + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(deviceContext, (void**)d2D1Effect); + } + + // TODO: port base CanvasEffect::Realize logic + + // Also set the current constants for the effect + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.d2D1Effect.Get()); + } + + /// + /// Updates the draw state for the currently realized effect. + /// + /// The current flags in use. + /// The target DPI in use. + /// The instance in use. + private unsafe void RefreshInputs(CanvasImageGetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) + { + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.d2D1Effect.Get()); + + // TODO } } \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1CommandList.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1CommandList.cs new file mode 100644 index 00000000..184b8c3f --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1CommandList.cs @@ -0,0 +1,17 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1_1.h in the Windows SDK for Windows 10.0.22621.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.InteropServices; + +namespace TerraFX.Interop.DirectX; + +[Guid("B4F34A19-2383-4D76-94F6-EC343657C3DC")] +[NativeTypeName("struct ID2D1CommandList : ID2D1Image")] +[NativeInheritance("ID2D1Image")] +internal unsafe partial struct ID2D1CommandList +{ + public void** lpVtbl; +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1DeviceContext.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1DeviceContext.cs index f2c97599..620225ba 100644 --- a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1DeviceContext.cs +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1DeviceContext.cs @@ -26,10 +26,24 @@ internal unsafe partial struct ID2D1DeviceContext ((delegate* unmanaged[Stdcall])(lpVtbl[3]))((ID2D1DeviceContext*)Unsafe.AsPointer(ref this), factory); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(52)] + public void GetDpi(float* dpiX, float* dpiY) + { + ((delegate* unmanaged[Stdcall])(lpVtbl[52]))((ID2D1DeviceContext*)Unsafe.AsPointer(ref this), dpiX, dpiY); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(63)] public HRESULT CreateEffect([NativeTypeName("const IID &")] Guid* effectId, ID2D1Effect** effect) { return ((delegate* unmanaged[Stdcall])(lpVtbl[63]))((ID2D1DeviceContext*)Unsafe.AsPointer(ref this), effectId, effect); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(75)] + public void GetTarget(ID2D1Image** image) + { + ((delegate* unmanaged[Stdcall])(lpVtbl[75]))((ID2D1DeviceContext*)Unsafe.AsPointer(ref this), image); + } } \ 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 dbd3fde5..537c5701 100644 --- a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems +++ b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems @@ -33,6 +33,7 @@ + diff --git a/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/D2DERR.cs b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/D2DERR.cs index 5a3c371b..d11c5f59 100644 --- a/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/D2DERR.cs +++ b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/D2DERR.cs @@ -9,4 +9,7 @@ internal static partial class D2DERR { [NativeTypeName("#define D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES _HRESULT_TYPEDEF_(0x88990026L)")] public const int D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES = unchecked((int)(0x88990026)); + + [NativeTypeName("#define D2DERR_CYCLIC_GRAPH _HRESULT_TYPEDEF_(0x88990020L)")] + public const int D2DERR_CYCLIC_GRAPH = unchecked((int)(0x88990020)); } \ No newline at end of file From e7273d23c66788defc7eceb37fe7e7be56731c96 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 24 Oct 2022 00:26:52 +0200 Subject: [PATCH 11/59] Add CacheOutput and BufferPrecision properties --- .../PixelShaderEffect{T}.cs | 182 +++++++++++++++++- .../DirectX/um/d2d1_1/D2D1_PROPERTY.cs | 21 ++ .../DirectX/um/d2d1_1/D2D1_PROPERTY_TYPE.cs | 2 + .../DirectX/um/d2d1_1/ID2D1Effect.cs | 7 + .../TerraFX.Interop.Windows.D2D1.projitems | 1 + 5 files changed, 212 insertions(+), 1 deletion(-) create mode 100644 src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_PROPERTY.cs diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs index d8b95f47..42cb34b2 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs @@ -51,11 +51,142 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan /// private ComPtr d2D1Effect; + /// + /// The backing field for . + /// + private int cacheOutput; + + /// + /// The backing field for . + /// + private D2D1_BUFFER_PRECISION d2D1BufferPrecision; + /// /// The current value in use. /// public T Value; + /// + /// Gets or sets a value indicating whether to enable caching the output from drawing this effect. + /// + public unsafe bool CacheOutput + { + get + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + // If the effect is realized, get the latest value from it + if (this.d2D1Effect.Get() is not null) + { + int cacheOutput; + + this.d2D1Effect.Get()->GetValue( + index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_CACHED, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BOOL, + data: (byte*)&cacheOutput, + dataSize: sizeof(int)).Assert(); + + this.cacheOutput = cacheOutput; + } + + return this.cacheOutput != 0; + } + } + set + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + this.cacheOutput = value ? 1 : 0; + + // If the effect is realized, set the property on the underlying ID2D1Effect object too + if (this.d2D1Effect.Get() is not null) + { + int cacheOutput = this.cacheOutput; + + this.d2D1Effect.Get()->SetValue( + index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_CACHED, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BOOL, + data: (byte*)&cacheOutput, + dataSize: sizeof(int)).Assert(); + } + } + } + } + + /// + /// Gets or sets the precision to use for intermediate buffers when drawing this effect. + /// + /// If , the default precision for effects will be used. + public unsafe CanvasBufferPrecision? BufferPrecision + { + get + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + // If the effect is realized, get the latest value from it + if (this.d2D1Effect.Get() is not null) + { + D2D1_BUFFER_PRECISION d2D1BufferPrecision; + + this.d2D1Effect.Get()->GetValue( + index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_PRECISION, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_UNKNOWN, + data: (byte*)&d2D1BufferPrecision, + dataSize: sizeof(D2D1_BUFFER_PRECISION)).Assert(); + + this.d2D1BufferPrecision = d2D1BufferPrecision; + } + + // Map from D2D1_BUFFER_PRECISION to CanvasBufferPrecision, and return null for D2D1_BUFFER_PRECISION_UNKNOWN + return this.d2D1BufferPrecision switch + { + D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM => CanvasBufferPrecision.Precision8UIntNormalized, + D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM_SRGB => CanvasBufferPrecision.Precision8UIntNormalizedSrgb, + D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_16BPC_UNORM => CanvasBufferPrecision.Precision16UIntNormalized, + D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_16BPC_FLOAT => CanvasBufferPrecision.Precision16Float, + D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_32BPC_FLOAT => CanvasBufferPrecision.Precision32Float, + _ => null + }; + } + } + set + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + // Map back from CanvasBufferPrecision? to D2D1_BUFFER_PRECISION (null results in D2D1_BUFFER_PRECISION_UNKNOWN) + this.d2D1BufferPrecision = value switch + { + CanvasBufferPrecision.Precision8UIntNormalized => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM, + CanvasBufferPrecision.Precision8UIntNormalizedSrgb => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM_SRGB, + CanvasBufferPrecision.Precision16UIntNormalized => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_16BPC_UNORM, + CanvasBufferPrecision.Precision16Float => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_16BPC_FLOAT, + CanvasBufferPrecision.Precision32Float => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_32BPC_FLOAT, + _ => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_UNKNOWN + }; + + // If the effect is realized, set the property on the underlying ID2D1Effect object too + if (this.d2D1Effect.Get() is not null) + { + D2D1_BUFFER_PRECISION d2D1BufferPrecision = this.d2D1BufferPrecision; + + this.d2D1Effect.Get()->SetValue( + index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_PRECISION, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_UNKNOWN, + data: (byte*)&d2D1BufferPrecision, + dataSize: sizeof(D2D1_BUFFER_PRECISION)).Assert(); + } + } + } + } + /// Rect ICanvasImage.GetBounds(ICanvasResourceCreator resourceCreator) { @@ -219,7 +350,32 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan return; } - // TODO + // Cache the last update value of the cache property + int cacheOutput; + + this.d2D1Effect.Get()->GetValue( + index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_CACHED, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BOOL, + data: (byte*)&cacheOutput, + dataSize: sizeof(int)).Assert(); + + this.cacheOutput = cacheOutput; + + // Do the same for the buffer precision + D2D1_BUFFER_PRECISION d2D1BufferPrecision; + + this.d2D1Effect.Get()->GetValue( + index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_PRECISION, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_UNKNOWN, + data: (byte*)&d2D1BufferPrecision, + dataSize: sizeof(D2D1_BUFFER_PRECISION)).Assert(); + + this.d2D1BufferPrecision = d2D1BufferPrecision; + + // TODO: read back D2D sources from the effect + + // Finally release the effect as well + this.d2D1Effect.Dispose(); } /// @@ -249,6 +405,30 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(deviceContext, (void**)d2D1Effect); } + // If cache input has been set, forward that to the new effect + if (this.cacheOutput != 0) + { + int cacheOutput = this.cacheOutput; + + this.d2D1Effect.Get()->GetValue( + index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_CACHED, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BOOL, + data: (byte*)&cacheOutput, + dataSize: sizeof(int)).Assert(); + } + + // If the buffer precision isn't unknown, forward that as well + if (this.d2D1BufferPrecision != D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_UNKNOWN) + { + D2D1_BUFFER_PRECISION d2D1BufferPrecision = this.d2D1BufferPrecision; + + this.d2D1Effect.Get()->SetValue( + index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_PRECISION, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_UNKNOWN, + data: (byte*)&d2D1BufferPrecision, + dataSize: sizeof(D2D1_BUFFER_PRECISION)).Assert(); + } + // TODO: port base CanvasEffect::Realize logic // Also set the current constants for the effect diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_PROPERTY.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_PROPERTY.cs new file mode 100644 index 00000000..03315307 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_PROPERTY.cs @@ -0,0 +1,21 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1_1.h in the Windows SDK for Windows 10.0.22621.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.DirectX; + +internal enum D2D1_PROPERTY : uint +{ + D2D1_PROPERTY_CLSID = 0x80000000, + D2D1_PROPERTY_DISPLAYNAME = 0x80000001, + D2D1_PROPERTY_AUTHOR = 0x80000002, + D2D1_PROPERTY_CATEGORY = 0x80000003, + D2D1_PROPERTY_DESCRIPTION = 0x80000004, + D2D1_PROPERTY_INPUTS = 0x80000005, + D2D1_PROPERTY_CACHED = 0x80000006, + D2D1_PROPERTY_PRECISION = 0x80000007, + D2D1_PROPERTY_MIN_INPUTS = 0x80000008, + D2D1_PROPERTY_MAX_INPUTS = 0x80000009, + D2D1_PROPERTY_FORCE_DWORD = 0xffffffff +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_PROPERTY_TYPE.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_PROPERTY_TYPE.cs index 0ec753c4..afab61b9 100644 --- a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_PROPERTY_TYPE.cs +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_PROPERTY_TYPE.cs @@ -7,6 +7,8 @@ namespace TerraFX.Interop.DirectX; internal enum D2D1_PROPERTY_TYPE : uint { + D2D1_PROPERTY_TYPE_UNKNOWN = 0, + D2D1_PROPERTY_TYPE_BOOL = 2, D2D1_PROPERTY_TYPE_BLOB = 9, D2D1_PROPERTY_TYPE_IUNKNOWN = 10 } \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Effect.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Effect.cs index 3050f3c1..1d5dcb4a 100644 --- a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Effect.cs +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Effect.cs @@ -25,4 +25,11 @@ internal unsafe partial struct ID2D1Effect { return ((delegate* unmanaged[Stdcall])(lpVtbl[9]))((ID2D1Effect*)Unsafe.AsPointer(ref this), index, type, data, dataSize); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(11)] + public HRESULT GetValue([NativeTypeName("UINT32")] uint index, D2D1_PROPERTY_TYPE type, byte* data, [NativeTypeName("UINT32")] uint dataSize) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[11]))((ID2D1Effect*)Unsafe.AsPointer(ref this), index, type, data, dataSize); + } } \ 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 537c5701..977bcb66 100644 --- a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems +++ b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems @@ -32,6 +32,7 @@ + From 34cbd2d83f5496c9579f3187be270a806e7e2023 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 24 Oct 2022 00:38:47 +0200 Subject: [PATCH 12/59] Move ID2D1Effect property getters to extensions --- .../Extensions/ID2D1EffectExtensions.cs | 76 +++++++++++++++++ .../PixelShaderEffect{T}.cs | 84 +++---------------- 2 files changed, 89 insertions(+), 71 deletions(-) create mode 100644 src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs new file mode 100644 index 00000000..ffd7a850 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs @@ -0,0 +1,76 @@ +using ComputeSharp.D2D1.Extensions; +using TerraFX.Interop.DirectX; + +namespace ComputeSharp.D2D1.Uwp.Extensions; + +/// +/// A with extensions for the type. +/// +internal static unsafe class ID2D1EffectExtensions +{ + /// + /// Gets the property for a given object. + /// + /// The input instance. + /// The value for . + public static bool GetCachedProperty(this ref ID2D1Effect d2D1Effect) + { + int cacheOutput; + + d2D1Effect.GetValue( + index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_CACHED, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BOOL, + data: (byte*)&cacheOutput, + dataSize: sizeof(int)).Assert(); + + return cacheOutput != 0; + } + + /// + /// Sets the property for a given object. + /// + /// The input instance. + /// The property value to set. + public static void SetCachedProperty(this ref ID2D1Effect d2D1Effect, bool value) + { + int cacheOutput = value ? 1 : 0; + + d2D1Effect.SetValue( + index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_CACHED, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BOOL, + data: (byte*)&cacheOutput, + dataSize: sizeof(int)).Assert(); + } + + /// + /// Gets the property for a given object. + /// + /// The input instance. + /// The value for . + public static D2D1_BUFFER_PRECISION GetPrecisionProperty(this ref ID2D1Effect d2D1Effect) + { + D2D1_BUFFER_PRECISION d2D1BufferPrecision; + + d2D1Effect.GetValue( + index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_PRECISION, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_UNKNOWN, + data: (byte*)&d2D1BufferPrecision, + dataSize: sizeof(D2D1_BUFFER_PRECISION)).Assert(); + + return d2D1BufferPrecision; + } + + /// + /// Sets the property for a given object. + /// + /// The input instance. + /// The property value to set. + public static void SetPrecisionProperty(this ref ID2D1Effect d2D1Effect, D2D1_BUFFER_PRECISION value) + { + d2D1Effect.SetValue( + index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_PRECISION, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_UNKNOWN, + data: (byte*)&value, + dataSize: sizeof(D2D1_BUFFER_PRECISION)).Assert(); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs index 42cb34b2..a8b8fc47 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs @@ -54,7 +54,7 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan /// /// The backing field for . /// - private int cacheOutput; + private bool cacheOutput; /// /// The backing field for . @@ -80,18 +80,10 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan // If the effect is realized, get the latest value from it if (this.d2D1Effect.Get() is not null) { - int cacheOutput; - - this.d2D1Effect.Get()->GetValue( - index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_CACHED, - type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BOOL, - data: (byte*)&cacheOutput, - dataSize: sizeof(int)).Assert(); - - this.cacheOutput = cacheOutput; + this.cacheOutput = this.d2D1Effect.Get()->GetCachedProperty(); } - return this.cacheOutput != 0; + return this.cacheOutput; } } set @@ -100,18 +92,12 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan lock (this.lockObject) { - this.cacheOutput = value ? 1 : 0; + this.cacheOutput = value; // If the effect is realized, set the property on the underlying ID2D1Effect object too if (this.d2D1Effect.Get() is not null) { - int cacheOutput = this.cacheOutput; - - this.d2D1Effect.Get()->SetValue( - index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_CACHED, - type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BOOL, - data: (byte*)&cacheOutput, - dataSize: sizeof(int)).Assert(); + this.d2D1Effect.Get()->SetCachedProperty(value); } } } @@ -132,15 +118,7 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan // If the effect is realized, get the latest value from it if (this.d2D1Effect.Get() is not null) { - D2D1_BUFFER_PRECISION d2D1BufferPrecision; - - this.d2D1Effect.Get()->GetValue( - index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_PRECISION, - type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_UNKNOWN, - data: (byte*)&d2D1BufferPrecision, - dataSize: sizeof(D2D1_BUFFER_PRECISION)).Assert(); - - this.d2D1BufferPrecision = d2D1BufferPrecision; + this.d2D1BufferPrecision = this.d2D1Effect.Get()->GetPrecisionProperty(); } // Map from D2D1_BUFFER_PRECISION to CanvasBufferPrecision, and return null for D2D1_BUFFER_PRECISION_UNKNOWN @@ -175,13 +153,7 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan // If the effect is realized, set the property on the underlying ID2D1Effect object too if (this.d2D1Effect.Get() is not null) { - D2D1_BUFFER_PRECISION d2D1BufferPrecision = this.d2D1BufferPrecision; - - this.d2D1Effect.Get()->SetValue( - index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_PRECISION, - type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_UNKNOWN, - data: (byte*)&d2D1BufferPrecision, - dataSize: sizeof(D2D1_BUFFER_PRECISION)).Assert(); + this.d2D1Effect.Get()->SetPrecisionProperty(this.d2D1BufferPrecision); } } } @@ -350,27 +322,9 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan return; } - // Cache the last update value of the cache property - int cacheOutput; - - this.d2D1Effect.Get()->GetValue( - index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_CACHED, - type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BOOL, - data: (byte*)&cacheOutput, - dataSize: sizeof(int)).Assert(); - - this.cacheOutput = cacheOutput; - - // Do the same for the buffer precision - D2D1_BUFFER_PRECISION d2D1BufferPrecision; - - this.d2D1Effect.Get()->GetValue( - index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_PRECISION, - type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_UNKNOWN, - data: (byte*)&d2D1BufferPrecision, - dataSize: sizeof(D2D1_BUFFER_PRECISION)).Assert(); - - this.d2D1BufferPrecision = d2D1BufferPrecision; + // Cache the last update value of the cache and precision properties + this.cacheOutput = this.d2D1Effect.Get()->GetCachedProperty(); + this.d2D1BufferPrecision = this.d2D1Effect.Get()->GetPrecisionProperty(); // TODO: read back D2D sources from the effect @@ -406,27 +360,15 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan } // If cache input has been set, forward that to the new effect - if (this.cacheOutput != 0) + if (this.cacheOutput) { - int cacheOutput = this.cacheOutput; - - this.d2D1Effect.Get()->GetValue( - index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_CACHED, - type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BOOL, - data: (byte*)&cacheOutput, - dataSize: sizeof(int)).Assert(); + this.d2D1Effect.Get()->SetCachedProperty(true); } // If the buffer precision isn't unknown, forward that as well if (this.d2D1BufferPrecision != D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_UNKNOWN) { - D2D1_BUFFER_PRECISION d2D1BufferPrecision = this.d2D1BufferPrecision; - - this.d2D1Effect.Get()->SetValue( - index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_PRECISION, - type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_UNKNOWN, - data: (byte*)&d2D1BufferPrecision, - dataSize: sizeof(D2D1_BUFFER_PRECISION)).Assert(); + this.d2D1Effect.Get()->SetPrecisionProperty(this.d2D1BufferPrecision); } // TODO: port base CanvasEffect::Realize logic From bb6d9a99ec0e3516079261115924243664b8fc59 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 24 Oct 2022 01:28:13 +0200 Subject: [PATCH 13/59] Skip effect registrations when not needed --- .../PixelShaderEffect{T}.cs | 51 +++++++++++++++++-- .../Windows/shared/winerror/D2DERR.cs | 3 ++ 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs index a8b8fc47..3a3d2cdc 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs @@ -4,6 +4,7 @@ using System.Threading; using ABI.Microsoft.Graphics.Canvas; using ComputeSharp.D2D1.Extensions; using ComputeSharp.D2D1.Interop; +using ComputeSharp.D2D1.Interop.Effects; using ComputeSharp.D2D1.Uwp.Extensions; using ComputeSharp.Interop; using Microsoft.Graphics.Canvas; @@ -66,6 +67,20 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan /// public T Value; + /// + /// Configures the to use for effects of type . + /// + /// The factory of instances to use for each created effect. + /// Thrown if initialization is attempted with a mismatched transform factory. + /// + /// Initialization can only be done once, and is shared across all effects of type . + /// Initializing an effect is not necessary before using it: if no transform has been set, the default one will be used. + /// + public static void ConfigureD2D1TransformMapperFactory(ID2D1TransformMapperFactory? d2D1DrawTransformMapperFactory) + { + PixelShaderEffect.For.Initialize(d2D1DrawTransformMapperFactory); + } + /// /// Gets or sets a value indicating whether to enable caching the output from drawing this effect. /// @@ -350,13 +365,41 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan // D2D1PixelShaderEffect APIs specifically need an ID2D1Factory1 (as ID2D1Factory1::RegisterEffectFromString is used) d2D1Factory.CopyTo(d2D1Factory1.GetAddressOf()).Assert(); - // Register the effect with the factory (TODO: only do this if needed) - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory1.Get(), out _); + bool isPossiblyRegistered = true; + + // If the effect hasn't been initialized explicitly, initialize it now + if (!PixelShaderEffect.For.TryGetId(out Guid effectId)) + { + PixelShaderEffect.For.Initialize(null); + + effectId = PixelShaderEffect.For.Id; + isPossiblyRegistered = false; + } fixed (ID2D1Effect** d2D1Effect = this.d2D1Effect) { - // Create an instance of the effect in use and store it in the current object - D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(deviceContext, (void**)d2D1Effect); + HRESULT hresult = D2DERR.D2DERR_EFFECT_IS_NOT_REGISTERED; + + // Try to create an instance of the effect in use and store it in the current object + if (isPossiblyRegistered) + { + hresult = deviceContext->CreateEffect(effectId: &effectId, effect: d2D1Effect); + } + + // Check if creation failed due to the effect not being registered. In that case, register + // it and then try again. This is much faster than check whether the effect is registered + // manually every time, by enumerating all registered effects for the target device context. + if (hresult == D2DERR.D2DERR_EFFECT_IS_NOT_REGISTERED) + { + // Register the effect with the factory (pass the same D2D1 draw transform mapper factory that was used before) + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory1.Get(), PixelShaderEffect.For.D2D1DrawTransformMapperFactory, out _); + + // Try to create the effect again + hresult = deviceContext->CreateEffect(effectId: &effectId, effect: d2D1Effect); + } + + // Rethrow any other errors + hresult.Assert(); } // If cache input has been set, forward that to the new effect diff --git a/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/D2DERR.cs b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/D2DERR.cs index d11c5f59..542a9408 100644 --- a/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/D2DERR.cs +++ b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/D2DERR.cs @@ -12,4 +12,7 @@ internal static partial class D2DERR [NativeTypeName("#define D2DERR_CYCLIC_GRAPH _HRESULT_TYPEDEF_(0x88990020L)")] public const int D2DERR_CYCLIC_GRAPH = unchecked((int)(0x88990020)); + + [NativeTypeName("#define D2DERR_EFFECT_IS_NOT_REGISTERED _HRESULT_TYPEDEF_(0x88990028L)")] + public const int D2DERR_EFFECT_IS_NOT_REGISTERED = unchecked((int)(0x88990028)); } \ No newline at end of file From 1c2ff9a2ef222c747958c4c252cf5bcd8fc5b6b1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 24 Oct 2022 01:37:04 +0200 Subject: [PATCH 14/59] Move ICanvasImageInterop implementation into partial file --- ...ixelShaderEffect{T}.ICanvasImageInterop.cs | 266 ++++++++++++++++++ .../PixelShaderEffect{T}.cs | 251 ----------------- 2 files changed, 266 insertions(+), 251 deletions(-) create mode 100644 src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs new file mode 100644 index 00000000..f7235629 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -0,0 +1,266 @@ +using System; +using System.Threading; +using ABI.Microsoft.Graphics.Canvas; +using ComputeSharp.D2D1.Extensions; +using ComputeSharp.D2D1.Interop; +using ComputeSharp.D2D1.Interop.Effects; +using ComputeSharp.D2D1.Uwp.Extensions; +using ComputeSharp.Interop; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using Win32 = TerraFX.Interop.Windows.Windows; + +namespace ComputeSharp.D2D1.Uwp; + +/// +unsafe partial class PixelShaderEffect +{ + /// + int ICanvasImageInterop.GetDevice(ICanvasDevice** device) + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().TryGetLease(out bool leaseTaken); + + // Check for disposal + if (!leaseTaken) + { + return RO.RO_E_CLOSED; + } + + // Ensure we can take a lock without blocking. We can't access the realization device with no + // lock, as that could lead to memory leaks or corruption if GetD2DImage was to manipulate that + // field concurrently. We also cannot lock directly, because that would deadlock if someone was + // to (incorrectly) try to use the same effect from two different threads. To protect against + // that, we try to lock, and just return E_NOT_VALID_STATE if another thread holds the lock. If + // this call had GetD2DImage in the stack, that would work fine because locks are recursive. + if (!Monitor.TryEnter(this.lockObject)) + { + return E.E_NOT_VALID_STATE; + } + + try + { + // Copy the device over to the target + return this.canvasDevice.CopyTo(device); + } + finally + { + Monitor.Exit(this.lockObject); + } + } + + /// + int ICanvasImageInterop.GetD2DImage( + ICanvasDevice* device, + ID2D1DeviceContext* deviceContext, + CanvasImageGetD2DImageFlags flags, + float targetDpi, + float* realizeDpi, + ID2D1Image** ppImage) + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().TryGetLease(out bool leaseTaken); + + // Check for disposal + if (!leaseTaken) + { + return RO.RO_E_CLOSED; + } + + // Check for graph cycles + if (Interlocked.CompareExchange(ref this.isInsideGetD2DImage, 1, 0) == 1) + { + return D2DERR.D2DERR_CYCLIC_GRAPH; + } + + try + { + // Lock after checking for graph cycles (other public APIs also lock on this object) + lock (this.lockObject) + { + // Process the ReadDpiFromDeviceContext flag (same logic as CanvasEffect::GetD2DImage) + if ((flags & CanvasImageGetD2DImageFlags.ReadDpiFromDeviceContext) != CanvasImageGetD2DImageFlags.None) + { + // If ReadDpiFromDeviceContext is used, the context cannot be null + if (deviceContext is null) + { + return E.E_POINTER; + } + + if (deviceContext->HasCommandListTarget()) + { + // Command lists are DPI dependent, so DPI compensation effects are always needed + flags |= CanvasImageGetD2DImageFlags.AlwaysInsertDpiCompensation; + } + else + { + // If the effect is not being drawn onto a command list, the DPIs can be read from the device context + targetDpi = deviceContext->GetDpi(); + } + + // ReadDpiFromDeviceContext has been processed, so it can be removed now + flags &= ~CanvasImageGetD2DImageFlags.ReadDpiFromDeviceContext; + } + + using ComPtr d2D1Device1 = default; + + // Get the underlying ID2D1Device1 instance in use + device->GetD2DDevice(d2D1Device1.GetAddressOf()).Assert(); + + // Check that the input D2D device is the same instance as the current realization device, if any. + // If not and the effect has already been realized, unrealize it and store the new device to use. + if (!d2D1Device1.IsSameInstance(in this.d2D1RealizationDevice)) + { + Unrealize(); + + // Store the input realization device and canvas device for future uses + d2D1Device1.CopyTo(ref this.d2D1RealizationDevice).Assert(); + + fixed (ICanvasDevice** canvasDevice = this.canvasDevice) + { + device->QueryInterface(Win32.__uuidof(), (void**)canvasDevice).Assert(); + } + } + + // Create the effect, if it doesn't exist already + if (this.d2D1Effect.Get() is null) + { + Realize(flags, targetDpi, deviceContext); + } + else if (!flags.HasFlag(CanvasImageGetD2DImageFlags.MinimalRealization)) + { + // Recurse through the effect graph and ensure all nodes are initialized + RefreshInputs(flags, targetDpi, deviceContext); + } + + // The realized DPIs are always 0 for pixel shader effects + if (realizeDpi is not null) + { + *realizeDpi = 0; + } + + this.d2D1Effect.CopyTo(ppImage).Assert(); + + return S.S_OK; + } + } + catch (Exception e) + { + *ppImage = null; + + return e.HResult; + } + finally + { + // Ensure that reset this flag so that this method can be called again + this.isInsideGetD2DImage = 0; + } + } + + /// + /// Unrealizes the currently realized object. + /// + private void Unrealize() + { + // If there is no ID2D1Effect object, there is nothing left to do + if (this.d2D1Effect.Get() is null) + { + return; + } + + // Cache the last update value of the cache and precision properties + this.cacheOutput = this.d2D1Effect.Get()->GetCachedProperty(); + this.d2D1BufferPrecision = this.d2D1Effect.Get()->GetPrecisionProperty(); + + // TODO: read back D2D sources from the effect + + // Finally release the effect as well + this.d2D1Effect.Dispose(); + } + + /// + /// Realizes the underlying for this object. + /// + /// The current flags in use. + /// The target DPI in use. + /// The instance in use. + private void Realize(CanvasImageGetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) + { + using ComPtr d2D1Factory = default; + + // Get the underlying ID2D1Factory from the input context, so we can register and create the effect + deviceContext->GetFactory(d2D1Factory.GetAddressOf()); + + using ComPtr d2D1Factory1 = default; + + // D2D1PixelShaderEffect APIs specifically need an ID2D1Factory1 (as ID2D1Factory1::RegisterEffectFromString is used) + d2D1Factory.CopyTo(d2D1Factory1.GetAddressOf()).Assert(); + + bool isPossiblyRegistered = true; + + // If the effect hasn't been initialized explicitly, initialize it now + if (!PixelShaderEffect.For.TryGetId(out Guid effectId)) + { + PixelShaderEffect.For.Initialize(null); + + effectId = PixelShaderEffect.For.Id; + isPossiblyRegistered = false; + } + + fixed (ID2D1Effect** d2D1Effect = this.d2D1Effect) + { + HRESULT hresult = D2DERR.D2DERR_EFFECT_IS_NOT_REGISTERED; + + // Try to create an instance of the effect in use and store it in the current object + if (isPossiblyRegistered) + { + hresult = deviceContext->CreateEffect(effectId: &effectId, effect: d2D1Effect); + } + + // Check if creation failed due to the effect not being registered. In that case, register + // it and then try again. This is much faster than check whether the effect is registered + // manually every time, by enumerating all registered effects for the target device context. + if (hresult == D2DERR.D2DERR_EFFECT_IS_NOT_REGISTERED) + { + // Register the effect with the factory (pass the same D2D1 draw transform mapper factory that was used before) + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory1.Get(), PixelShaderEffect.For.D2D1DrawTransformMapperFactory, out _); + + // Try to create the effect again + hresult = deviceContext->CreateEffect(effectId: &effectId, effect: d2D1Effect); + } + + // Rethrow any other errors + hresult.Assert(); + } + + // TODO: transfer properties (eg. D2D1ResourceTextureManager-s) + + // If cache input has been set, forward that to the new effect + if (this.cacheOutput) + { + this.d2D1Effect.Get()->SetCachedProperty(true); + } + + // If the buffer precision isn't unknown, forward that as well + if (this.d2D1BufferPrecision != D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_UNKNOWN) + { + this.d2D1Effect.Get()->SetPrecisionProperty(this.d2D1BufferPrecision); + } + + // TODO: port base CanvasEffect::Realize logic + + // Also set the current constants for the effect + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.d2D1Effect.Get()); + } + + /// + /// Updates the draw state for the currently realized effect. + /// + /// The current flags in use. + /// The target DPI in use. + /// The instance in use. + private void RefreshInputs(CanvasImageGetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) + { + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.d2D1Effect.Get()); + + // TODO + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs index 3a3d2cdc..2069042c 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs @@ -1,9 +1,6 @@ using System; using System.Numerics; -using System.Threading; using ABI.Microsoft.Graphics.Canvas; -using ComputeSharp.D2D1.Extensions; -using ComputeSharp.D2D1.Interop; using ComputeSharp.D2D1.Interop.Effects; using ComputeSharp.D2D1.Uwp.Extensions; using ComputeSharp.Interop; @@ -11,7 +8,6 @@ using Microsoft.Graphics.Canvas; using Windows.Foundation; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; -using Win32 = TerraFX.Interop.Windows.Windows; namespace ComputeSharp.D2D1.Uwp; @@ -185,251 +181,4 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan { throw new NotSupportedException(); } - - /// - unsafe int ICanvasImageInterop.GetDevice(ICanvasDevice** device) - { - using ReferenceTracker.Lease _0 = GetReferenceTracker().TryGetLease(out bool leaseTaken); - - // Check for disposal - if (!leaseTaken) - { - return RO.RO_E_CLOSED; - } - - // Ensure we can take a lock without blocking. We can't access the realization device with no - // lock, as that could lead to memory leaks or corruption if GetD2DImage was to manipulate that - // field concurrently. We also cannot lock directly, because that would deadlock if someone was - // to (incorrectly) try to use the same effect from two different threads. To protect against - // that, we try to lock, and just return E_NOT_VALID_STATE if another thread holds the lock. If - // this call had GetD2DImage in the stack, that would work fine because locks are recursive. - if (!Monitor.TryEnter(this.lockObject)) - { - return E.E_NOT_VALID_STATE; - } - - try - { - // Copy the device over to the target - return this.canvasDevice.CopyTo(device); - } - finally - { - Monitor.Exit(this.lockObject); - } - } - - /// - unsafe int ICanvasImageInterop.GetD2DImage( - ICanvasDevice* device, - ID2D1DeviceContext* deviceContext, - CanvasImageGetD2DImageFlags flags, - float targetDpi, - float* realizeDpi, - ID2D1Image** ppImage) - { - using ReferenceTracker.Lease _0 = GetReferenceTracker().TryGetLease(out bool leaseTaken); - - // Check for disposal - if (!leaseTaken) - { - return RO.RO_E_CLOSED; - } - - // Check for graph cycles - if (Interlocked.CompareExchange(ref this.isInsideGetD2DImage, 1, 0) == 1) - { - return D2DERR.D2DERR_CYCLIC_GRAPH; - } - - try - { - // Lock after checking for graph cycles (other public APIs also lock on this object) - lock (this.lockObject) - { - // Process the ReadDpiFromDeviceContext flag (same logic as CanvasEffect::GetD2DImage) - if ((flags & CanvasImageGetD2DImageFlags.ReadDpiFromDeviceContext) != CanvasImageGetD2DImageFlags.None) - { - // If ReadDpiFromDeviceContext is used, the context cannot be null - if (deviceContext is null) - { - return E.E_POINTER; - } - - if (deviceContext->HasCommandListTarget()) - { - // Command lists are DPI dependent, so DPI compensation effects are always needed - flags |= CanvasImageGetD2DImageFlags.AlwaysInsertDpiCompensation; - } - else - { - // If the effect is not being drawn onto a command list, the DPIs can be read from the device context - targetDpi = deviceContext->GetDpi(); - } - - // ReadDpiFromDeviceContext has been processed, so it can be removed now - flags &= ~CanvasImageGetD2DImageFlags.ReadDpiFromDeviceContext; - } - - using ComPtr d2D1Device1 = default; - - // Get the underlying ID2D1Device1 instance in use - device->GetD2DDevice(d2D1Device1.GetAddressOf()).Assert(); - - // Check that the input D2D device is the same instance as the current realization device, if any. - // If not and the effect has already been realized, unrealize it and store the new device to use. - if (!d2D1Device1.IsSameInstance(in this.d2D1RealizationDevice)) - { - Unrealize(); - - // Store the input realization device and canvas device for future uses - d2D1Device1.CopyTo(ref this.d2D1RealizationDevice).Assert(); - - fixed (ICanvasDevice** canvasDevice = this.canvasDevice) - { - device->QueryInterface(Win32.__uuidof(), (void**)canvasDevice).Assert(); - } - } - - // Create the effect, if it doesn't exist already - if (this.d2D1Effect.Get() is null) - { - Realize(flags, targetDpi, deviceContext); - } - else if (!flags.HasFlag(CanvasImageGetD2DImageFlags.MinimalRealization)) - { - // Recurse through the effect graph and ensure all nodes are initialized - RefreshInputs(flags, targetDpi, deviceContext); - } - - // The realized DPIs are always 0 for pixel shader effects - if (realizeDpi is not null) - { - *realizeDpi = 0; - } - - this.d2D1Effect.CopyTo(ppImage).Assert(); - - return S.S_OK; - } - } - catch (Exception e) - { - *ppImage = null; - - return e.HResult; - } - finally - { - // Ensure that reset this flag so that this method can be called again - this.isInsideGetD2DImage = 0; - } - } - - /// - /// Unrealizes the currently realized object. - /// - private unsafe void Unrealize() - { - // If there is no ID2D1Effect object, there is nothing left to do - if (this.d2D1Effect.Get() is null) - { - return; - } - - // Cache the last update value of the cache and precision properties - this.cacheOutput = this.d2D1Effect.Get()->GetCachedProperty(); - this.d2D1BufferPrecision = this.d2D1Effect.Get()->GetPrecisionProperty(); - - // TODO: read back D2D sources from the effect - - // Finally release the effect as well - this.d2D1Effect.Dispose(); - } - - /// - /// Realizes the underlying for this object. - /// - /// The current flags in use. - /// The target DPI in use. - /// The instance in use. - private unsafe void Realize(CanvasImageGetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) - { - using ComPtr d2D1Factory = default; - - // Get the underlying ID2D1Factory from the input context, so we can register and create the effect - deviceContext->GetFactory(d2D1Factory.GetAddressOf()); - - using ComPtr d2D1Factory1 = default; - - // D2D1PixelShaderEffect APIs specifically need an ID2D1Factory1 (as ID2D1Factory1::RegisterEffectFromString is used) - d2D1Factory.CopyTo(d2D1Factory1.GetAddressOf()).Assert(); - - bool isPossiblyRegistered = true; - - // If the effect hasn't been initialized explicitly, initialize it now - if (!PixelShaderEffect.For.TryGetId(out Guid effectId)) - { - PixelShaderEffect.For.Initialize(null); - - effectId = PixelShaderEffect.For.Id; - isPossiblyRegistered = false; - } - - fixed (ID2D1Effect** d2D1Effect = this.d2D1Effect) - { - HRESULT hresult = D2DERR.D2DERR_EFFECT_IS_NOT_REGISTERED; - - // Try to create an instance of the effect in use and store it in the current object - if (isPossiblyRegistered) - { - hresult = deviceContext->CreateEffect(effectId: &effectId, effect: d2D1Effect); - } - - // Check if creation failed due to the effect not being registered. In that case, register - // it and then try again. This is much faster than check whether the effect is registered - // manually every time, by enumerating all registered effects for the target device context. - if (hresult == D2DERR.D2DERR_EFFECT_IS_NOT_REGISTERED) - { - // Register the effect with the factory (pass the same D2D1 draw transform mapper factory that was used before) - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory1.Get(), PixelShaderEffect.For.D2D1DrawTransformMapperFactory, out _); - - // Try to create the effect again - hresult = deviceContext->CreateEffect(effectId: &effectId, effect: d2D1Effect); - } - - // Rethrow any other errors - hresult.Assert(); - } - - // If cache input has been set, forward that to the new effect - if (this.cacheOutput) - { - this.d2D1Effect.Get()->SetCachedProperty(true); - } - - // If the buffer precision isn't unknown, forward that as well - if (this.d2D1BufferPrecision != D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_UNKNOWN) - { - this.d2D1Effect.Get()->SetPrecisionProperty(this.d2D1BufferPrecision); - } - - // TODO: port base CanvasEffect::Realize logic - - // Also set the current constants for the effect - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.d2D1Effect.Get()); - } - - /// - /// Updates the draw state for the currently realized effect. - /// - /// The current flags in use. - /// The target DPI in use. - /// The instance in use. - private unsafe void RefreshInputs(CanvasImageGetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) - { - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.d2D1Effect.Get()); - - // TODO - } } \ No newline at end of file From a32fc9ec646b7bd02fe8737aff8708b543330601 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 24 Oct 2022 02:21:44 +0200 Subject: [PATCH 15/59] More code refactoring --- .../PixelShaderEffect{T}.ICanvasImage.cs | 22 +++ ...ixelShaderEffect{T}.ICanvasImageInterop.cs | 4 +- ...PixelShaderEffect{T}.Properties.Interop.cs | 108 +++++++++++++++ .../PixelShaderEffect{T}.Properties.cs | 71 ++++++++++ .../PixelShaderEffect{T}.cs | 129 ------------------ 5 files changed, 203 insertions(+), 131 deletions(-) create mode 100644 src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImage.cs create mode 100644 src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs create mode 100644 src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImage.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImage.cs new file mode 100644 index 00000000..8c026cc7 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImage.cs @@ -0,0 +1,22 @@ +using System; +using System.Numerics; +using Microsoft.Graphics.Canvas; +using Windows.Foundation; + +namespace ComputeSharp.D2D1.Uwp; + +/// +partial class PixelShaderEffect +{ + /// + Rect ICanvasImage.GetBounds(ICanvasResourceCreator resourceCreator) + { + throw new NotSupportedException(); + } + + /// + Rect ICanvasImage.GetBounds(ICanvasResourceCreator resourceCreator, Matrix3x2 transform) + { + throw new NotSupportedException(); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index f7235629..d4652e8c 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -248,7 +248,7 @@ unsafe partial class PixelShaderEffect // TODO: port base CanvasEffect::Realize logic // Also set the current constants for the effect - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.d2D1Effect.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(Value, this.d2D1Effect.Get()); } /// @@ -259,7 +259,7 @@ unsafe partial class PixelShaderEffect /// The instance in use. private void RefreshInputs(CanvasImageGetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) { - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.d2D1Effect.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(Value, this.d2D1Effect.Get()); // TODO } diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs new file mode 100644 index 00000000..e5a12ea1 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs @@ -0,0 +1,108 @@ +using ComputeSharp.D2D1.Uwp.Extensions; +using ComputeSharp.Interop; +using Microsoft.Graphics.Canvas; +using TerraFX.Interop.DirectX; + +namespace ComputeSharp.D2D1.Uwp; + +/// +unsafe partial class PixelShaderEffect +{ + /// + /// Gets the marshalled value for . + /// + /// The marshalled value for . + private bool GetCacheOutput() + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + // If the effect is realized, get the latest value from it + if (this.d2D1Effect.Get() is not null) + { + this.cacheOutput = this.d2D1Effect.Get()->GetCachedProperty(); + } + + return this.cacheOutput; + } + } + + /// + /// Sets the marshalled value for . + /// + /// The value to set for . + private void SetCacheOutput(bool value) + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + this.cacheOutput = value; + + // If the effect is realized, set the property on the underlying ID2D1Effect object too + if (this.d2D1Effect.Get() is not null) + { + this.d2D1Effect.Get()->SetCachedProperty(value); + } + } + } + + /// + /// Gets the marshalled value for . + /// + /// The marshalled value for . + private CanvasBufferPrecision? GetBufferPrecision() + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + // If the effect is realized, get the latest value from it + if (this.d2D1Effect.Get() is not null) + { + this.d2D1BufferPrecision = this.d2D1Effect.Get()->GetPrecisionProperty(); + } + + // Map from D2D1_BUFFER_PRECISION to CanvasBufferPrecision, and return null for D2D1_BUFFER_PRECISION_UNKNOWN + return this.d2D1BufferPrecision switch + { + D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM => CanvasBufferPrecision.Precision8UIntNormalized, + D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM_SRGB => CanvasBufferPrecision.Precision8UIntNormalizedSrgb, + D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_16BPC_UNORM => CanvasBufferPrecision.Precision16UIntNormalized, + D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_16BPC_FLOAT => CanvasBufferPrecision.Precision16Float, + D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_32BPC_FLOAT => CanvasBufferPrecision.Precision32Float, + _ => null + }; + } + } + + /// + /// Sets the marshalled value for . + /// + /// The value to set for . + private void SetBufferPrecision(CanvasBufferPrecision? value) + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + // Map back from CanvasBufferPrecision? to D2D1_BUFFER_PRECISION (null results in D2D1_BUFFER_PRECISION_UNKNOWN) + this.d2D1BufferPrecision = value switch + { + CanvasBufferPrecision.Precision8UIntNormalized => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM, + CanvasBufferPrecision.Precision8UIntNormalizedSrgb => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM_SRGB, + CanvasBufferPrecision.Precision16UIntNormalized => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_16BPC_UNORM, + CanvasBufferPrecision.Precision16Float => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_16BPC_FLOAT, + CanvasBufferPrecision.Precision32Float => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_32BPC_FLOAT, + _ => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_UNKNOWN + }; + + // If the effect is realized, set the property on the underlying ID2D1Effect object too + if (this.d2D1Effect.Get() is not null) + { + this.d2D1Effect.Get()->SetPrecisionProperty(this.d2D1BufferPrecision); + } + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs new file mode 100644 index 00000000..2042522d --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs @@ -0,0 +1,71 @@ +using System; +using ComputeSharp.D2D1.Interop.Effects; +using Microsoft.Graphics.Canvas; +using Windows.Graphics.Effects; + +namespace ComputeSharp.D2D1.Uwp; + +/// +partial class PixelShaderEffect +{ + /// + /// Configures the to use for effects of type . + /// + /// The factory of instances to use for each created effect. + /// Thrown if initialization is attempted with a mismatched transform factory. + /// + /// Initialization can only be done once, and is shared across all effects of type . + /// Initializing an effect is not necessary before using it: if no transform has been set, the default one will be used. + /// + public static void ConfigureD2D1TransformMapperFactory(ID2D1TransformMapperFactory? d2D1DrawTransformMapperFactory) + { + PixelShaderEffect.For.Initialize(d2D1DrawTransformMapperFactory); + } + + /// + /// Gets or sets the current value in use. + /// + public T Value { get; set; } + + /// + /// Gets the object associated with the current instance. + /// + public SourceCollection Sources { get; } = new(); + + /// + /// Gets or sets a value indicating whether to enable caching the output from drawing this effect. + /// + public bool CacheOutput + { + get => GetCacheOutput(); + set => SetCacheOutput(value); + } + + /// + /// Gets or sets the precision to use for intermediate buffers when drawing this effect. + /// + /// If , the default precision for effects will be used. + public CanvasBufferPrecision? BufferPrecision + { + get => GetBufferPrecision(); + set => SetBufferPrecision(value); + } + + /// + /// Represents the collection of sources in a instance. + /// + public sealed class SourceCollection + { + /// + /// Gets or sets the source at a specified index. + /// + /// The index of the source to get or set. + /// The source at the specified index. + /// Thrown if is not a valid index for the current effect. + public IGraphicsEffectSource this[int index] + { + get => null!; + set { } + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs index 2069042c..68e11821 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs @@ -1,11 +1,6 @@ -using System; -using System.Numerics; using ABI.Microsoft.Graphics.Canvas; -using ComputeSharp.D2D1.Interop.Effects; -using ComputeSharp.D2D1.Uwp.Extensions; using ComputeSharp.Interop; using Microsoft.Graphics.Canvas; -using Windows.Foundation; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -57,128 +52,4 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan /// The backing field for . /// private D2D1_BUFFER_PRECISION d2D1BufferPrecision; - - /// - /// The current value in use. - /// - public T Value; - - /// - /// Configures the to use for effects of type . - /// - /// The factory of instances to use for each created effect. - /// Thrown if initialization is attempted with a mismatched transform factory. - /// - /// Initialization can only be done once, and is shared across all effects of type . - /// Initializing an effect is not necessary before using it: if no transform has been set, the default one will be used. - /// - public static void ConfigureD2D1TransformMapperFactory(ID2D1TransformMapperFactory? d2D1DrawTransformMapperFactory) - { - PixelShaderEffect.For.Initialize(d2D1DrawTransformMapperFactory); - } - - /// - /// Gets or sets a value indicating whether to enable caching the output from drawing this effect. - /// - public unsafe bool CacheOutput - { - get - { - using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); - - lock (this.lockObject) - { - // If the effect is realized, get the latest value from it - if (this.d2D1Effect.Get() is not null) - { - this.cacheOutput = this.d2D1Effect.Get()->GetCachedProperty(); - } - - return this.cacheOutput; - } - } - set - { - using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); - - lock (this.lockObject) - { - this.cacheOutput = value; - - // If the effect is realized, set the property on the underlying ID2D1Effect object too - if (this.d2D1Effect.Get() is not null) - { - this.d2D1Effect.Get()->SetCachedProperty(value); - } - } - } - } - - /// - /// Gets or sets the precision to use for intermediate buffers when drawing this effect. - /// - /// If , the default precision for effects will be used. - public unsafe CanvasBufferPrecision? BufferPrecision - { - get - { - using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); - - lock (this.lockObject) - { - // If the effect is realized, get the latest value from it - if (this.d2D1Effect.Get() is not null) - { - this.d2D1BufferPrecision = this.d2D1Effect.Get()->GetPrecisionProperty(); - } - - // Map from D2D1_BUFFER_PRECISION to CanvasBufferPrecision, and return null for D2D1_BUFFER_PRECISION_UNKNOWN - return this.d2D1BufferPrecision switch - { - D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM => CanvasBufferPrecision.Precision8UIntNormalized, - D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM_SRGB => CanvasBufferPrecision.Precision8UIntNormalizedSrgb, - D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_16BPC_UNORM => CanvasBufferPrecision.Precision16UIntNormalized, - D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_16BPC_FLOAT => CanvasBufferPrecision.Precision16Float, - D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_32BPC_FLOAT => CanvasBufferPrecision.Precision32Float, - _ => null - }; - } - } - set - { - using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); - - lock (this.lockObject) - { - // Map back from CanvasBufferPrecision? to D2D1_BUFFER_PRECISION (null results in D2D1_BUFFER_PRECISION_UNKNOWN) - this.d2D1BufferPrecision = value switch - { - CanvasBufferPrecision.Precision8UIntNormalized => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM, - CanvasBufferPrecision.Precision8UIntNormalizedSrgb => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM_SRGB, - CanvasBufferPrecision.Precision16UIntNormalized => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_16BPC_UNORM, - CanvasBufferPrecision.Precision16Float => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_16BPC_FLOAT, - CanvasBufferPrecision.Precision32Float => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_32BPC_FLOAT, - _ => D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_UNKNOWN - }; - - // If the effect is realized, set the property on the underlying ID2D1Effect object too - if (this.d2D1Effect.Get() is not null) - { - this.d2D1Effect.Get()->SetPrecisionProperty(this.d2D1BufferPrecision); - } - } - } - } - - /// - Rect ICanvasImage.GetBounds(ICanvasResourceCreator resourceCreator) - { - throw new NotSupportedException(); - } - - /// - Rect ICanvasImage.GetBounds(ICanvasResourceCreator resourceCreator, Matrix3x2 transform) - { - throw new NotSupportedException(); - } } \ No newline at end of file From c083fdc6ff7f6882e545869cdf9b1cbd3af68561 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 24 Oct 2022 23:46:42 +0200 Subject: [PATCH 16/59] Add ICanvasImageInterop raw binding type --- .../CanvasImageGetD2DImageFlags.cs | 2 +- .../ICanvasImageInterop.cs | 101 ++++++++++-------- .../ICanvasResourceWrapperNative.cs | 5 +- ...ixelShaderEffect{T}.ICanvasImageInterop.cs | 4 +- .../PixelShaderEffect{T}.cs | 4 +- 5 files changed, 64 insertions(+), 52 deletions(-) diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/CanvasImageGetD2DImageFlags.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/CanvasImageGetD2DImageFlags.cs index 613d6221..23ecb8cc 100644 --- a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/CanvasImageGetD2DImageFlags.cs +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/CanvasImageGetD2DImageFlags.cs @@ -3,7 +3,7 @@ using System; namespace ABI.Microsoft.Graphics.Canvas; /// -/// Options for fine-tuning the behavior of . +/// Options for fine-tuning the behavior of . /// [Flags] internal enum CanvasImageGetD2DImageFlags diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs index b62ce00f..ef451257 100644 --- a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs @@ -1,60 +1,73 @@ -using System.Runtime.InteropServices; using System; +using System.Runtime.InteropServices; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using TerraFX.Interop; +#pragma warning disable CS0649 + namespace ABI.Microsoft.Graphics.Canvas; /// /// An interop Win2D interface for all images and effects that can be drawn. /// -[ComImport] [Guid("E042D1F7-F9AD-4479-A713-67627EA31863")] -[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] -internal unsafe interface ICanvasImageInterop +[NativeTypeName("class ICanvasImageInterop : IUnknown")] +[NativeInheritance("IUnknown")] +internal unsafe struct ICanvasImageInterop { - /// - /// Gets the device that the effect is currently realized on, if any. - /// - /// The resulting device, if available ((as a marshalled )). - /// The for the operation. - [PreserveSig] - [return: NativeTypeName("HRESULT")] - int GetDevice(ICanvasDevice** device); + public void** lpVtbl; /// - /// Gets an from an instance. + /// The implementation of . /// - /// The input canvas device (as a marshalled ). - /// - /// The device context in use. This value is is optional (but recommended), except when the - /// flag is specified. This is because - /// not all callers of have easy access to a context. It is always - /// possible to get a resource creation context from the device, but the context is only - /// actually necessary if a new effect realization needs to be created, so it is more efficient - /// to have the implementation do this lookup only if/when it turns out to be needed. - /// - /// The flags to use to get the image. - /// - /// The DPI of the target device context. This is used to determine when a D2D1DpiCompensation - /// effect needs to be inserted. Behavior of this parameter can be overridden by the flag values - /// , - /// or - /// - /// - /// The DPI of a source bitmap, or zero if the image does not have a fixed DPI. A D2D1DpiCompensation effect - /// will be inserted if and are different (flags permitting). - /// - /// The resulting for the effect. - /// The for the operation. - [PreserveSig] - [return: NativeTypeName("HRESULT")] - int GetD2DImage( - ICanvasDevice* device, - ID2D1DeviceContext* deviceContext, - CanvasImageGetD2DImageFlags flags, - float targetDpi, - float* realizeDpi, - ID2D1Image** ppImage); + [ComImport] + [Guid("E042D1F7-F9AD-4479-A713-67627EA31863")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + public interface Interface + { + /// + /// Gets the device that the effect is currently realized on, if any. + /// + /// The resulting device, if available ((as a marshalled )). + /// The for the operation. + [PreserveSig] + [return: NativeTypeName("HRESULT")] + int GetDevice(ICanvasDevice** device); + + /// + /// Gets an from an instance. + /// + /// The input canvas device (as a marshalled ). + /// + /// The device context in use. This value is is optional (but recommended), except when the + /// flag is specified. This is because + /// not all callers of have easy access to a context. It is always + /// possible to get a resource creation context from the device, but the context is only + /// actually necessary if a new effect realization needs to be created, so it is more efficient + /// to have the implementation do this lookup only if/when it turns out to be needed. + /// + /// The flags to use to get the image. + /// + /// The DPI of the target device context. This is used to determine when a D2D1DpiCompensation + /// effect needs to be inserted. Behavior of this parameter can be overridden by the flag values + /// , + /// or + /// + /// + /// The DPI of a source bitmap, or zero if the image does not have a fixed DPI. A D2D1DpiCompensation effect + /// will be inserted if and are different (flags permitting). + /// + /// The resulting for the effect. + /// The for the operation. + [PreserveSig] + [return: NativeTypeName("HRESULT")] + int GetD2DImage( + ICanvasDevice* device, + ID2D1DeviceContext* deviceContext, + CanvasImageGetD2DImageFlags flags, + float targetDpi, + float* realizeDpi, + ID2D1Image** ppImage); + } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceWrapperNative.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceWrapperNative.cs index 7d877958..2f31d72e 100644 --- a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceWrapperNative.cs +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceWrapperNative.cs @@ -49,9 +49,8 @@ internal unsafe struct ICanvasResourceWrapperNative /// [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(3)] - [return: NativeTypeName("HRESULT")] - public HRESULT GetNativeResource([NativeTypeName("ICanvasDevice*")] void* device, float dpi, [NativeTypeName("REFIID")] Guid* iid, void** resource) + public HRESULT GetNativeResource(ICanvasDevice* device, float dpi, [NativeTypeName("REFIID")] Guid* iid, void** resource) { - return ((delegate* unmanaged[Stdcall])this.lpVtbl[3])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this), device, dpi, iid, resource); + return ((delegate* unmanaged[Stdcall])this.lpVtbl[3])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this), device, dpi, iid, resource); } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index d4652e8c..0712a2f6 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -16,7 +16,7 @@ namespace ComputeSharp.D2D1.Uwp; unsafe partial class PixelShaderEffect { /// - int ICanvasImageInterop.GetDevice(ICanvasDevice** device) + int ICanvasImageInterop.Interface.GetDevice(ICanvasDevice** device) { using ReferenceTracker.Lease _0 = GetReferenceTracker().TryGetLease(out bool leaseTaken); @@ -49,7 +49,7 @@ unsafe partial class PixelShaderEffect } /// - int ICanvasImageInterop.GetD2DImage( + int ICanvasImageInterop.Interface.GetD2DImage( ICanvasDevice* device, ID2D1DeviceContext* deviceContext, CanvasImageGetD2DImageFlags flags, diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs index 68e11821..e8a1273c 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs @@ -10,7 +10,7 @@ namespace ComputeSharp.D2D1.Uwp; /// A custom implementation powered by a supplied shader type. /// /// The type of shader to use to render frames. -public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICanvasImage, ICanvasImageInterop +public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICanvasImage, ICanvasImageInterop.Interface where T : unmanaged, ID2D1PixelShader { /// @@ -24,7 +24,7 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan private readonly object lockObject = new(); /// - /// Flag to track whether a given call is recursively invoked by , to avoid graph cycles. + /// Flag to track whether a given call is recursively invoked by , to avoid graph cycles. /// private volatile int isInsideGetD2DImage; From f6366343a00acffffc32fc2e3af82825d0c7250e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 25 Oct 2022 01:19:33 +0200 Subject: [PATCH 17/59] Add ICanvasResourceCreator native interface --- .../ICanvasResourceCreator.cs | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceCreator.cs diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceCreator.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceCreator.cs new file mode 100644 index 00000000..099af42d --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceCreator.cs @@ -0,0 +1,46 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace ABI.Microsoft.Graphics.Canvas; + +/// +/// The native WinRT interface for objects. +/// +[Guid("8F6D8AA8-492F-4BC6-B3D0-E7F5EAE84B11")] +[NativeTypeName("class ICanvasResourceCreator : IInspectable")] +[NativeInheritance("IInspectable")] +internal unsafe struct ICanvasResourceCreator +{ + public void** lpVtbl; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(0)] + public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[0])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(1)] + [return: NativeTypeName("ULONG")] + public uint AddRef() + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[1])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this)); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(2)] + [return: NativeTypeName("ULONG")] + public uint Release() + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[2])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this)); + } +} \ No newline at end of file From b6f739ca9daa28635cfe768d7eeb83477d3e0083 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 25 Oct 2022 00:41:46 +0200 Subject: [PATCH 18/59] Implement ICanvasImage public APIs --- .../ABI.Microsoft.Graphics.Canvas/Win2D.cs | 27 ++++++++++++ .../PixelShaderEffect{T}.ICanvasImage.cs | 44 +++++++++++++++++-- 2 files changed, 67 insertions(+), 4 deletions(-) create mode 100644 src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/Win2D.cs diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/Win2D.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/Win2D.cs new file mode 100644 index 00000000..9674c68d --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/Win2D.cs @@ -0,0 +1,27 @@ +using System.Numerics; +using System.Runtime.InteropServices; +using TerraFX.Interop; +using Windows.Foundation; + +namespace ABI.Microsoft.Graphics.Canvas; + +/// +/// Native APIs from Microsoft.Graphics.Canvas (ie. Win2D). +/// +internal static unsafe class Win2D +{ + /// + /// Calculates the bounds for a given instance. + /// + /// The object in use. + /// The input instance to compute the bounds for. + /// The transform to use (optional). + /// The resulting bounds. + /// The for the operation. + [DllImport("Microsoft.Graphics.Canvas.dll", PreserveSig = true, ExactSpelling = true)] + public static extern int GetBoundsForICanvasImageInterop( + ICanvasResourceCreator* resourceCreator, + ICanvasImageInterop* image, + [NativeTypeName("Windows::Foundation::Numerics::Matrix3x2 const*")] Matrix3x2* transform, + Rect* rect); +} diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImage.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImage.cs index 8c026cc7..62f2c3d9 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImage.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImage.cs @@ -1,22 +1,58 @@ -using System; using System.Numerics; +using System.Runtime.InteropServices; +using ABI.Microsoft.Graphics.Canvas; +using ComputeSharp.D2D1.Extensions; +using ComputeSharp.Interop; using Microsoft.Graphics.Canvas; +using TerraFX.Interop.Windows; using Windows.Foundation; +using ICanvasResourceCreator = Microsoft.Graphics.Canvas.ICanvasResourceCreator; namespace ComputeSharp.D2D1.Uwp; /// -partial class PixelShaderEffect +unsafe partial class PixelShaderEffect { /// Rect ICanvasImage.GetBounds(ICanvasResourceCreator resourceCreator) { - throw new NotSupportedException(); + return GetBounds(resourceCreator, null); } /// Rect ICanvasImage.GetBounds(ICanvasResourceCreator resourceCreator, Matrix3x2 transform) { - throw new NotSupportedException(); + return GetBounds(resourceCreator, &transform); + } + + /// + private Rect GetBounds(ICanvasResourceCreator resourceCreator, Matrix3x2* transform) + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + using ComPtr canvasResourceCreatorUnknown = default; + using ComPtr canvasImageInteropUnknown = default; + + // Get the IUnknown* references for the ICanvasResourceCreator and ICanvasImageInterop objects + canvasResourceCreatorUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(resourceCreator)); + canvasImageInteropUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(this)); + + using ComPtr canvasResourceCreator = default; + using ComPtr canvasImageInterop = default; + + // Get the ICanvasResourceCreator* and ICanvasImageInterop* pointers + canvasResourceCreatorUnknown.CopyTo(canvasResourceCreator.GetAddressOf()).Assert(); + canvasImageInteropUnknown.CopyTo(canvasImageInterop.GetAddressOf()).Assert(); + + Rect bounds; + + // Forward the actual logic to Win2D to compute the image bounds (it needs the internal context) + Win2D.GetBoundsForICanvasImageInterop( + resourceCreator: canvasResourceCreator.Get(), + image: canvasImageInterop.Get(), + transform: transform, + rect: &bounds).Assert(); + + return bounds; } } \ No newline at end of file From c58695cb5f37f4a8a07b1b76089ea0baec547d49 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 27 Oct 2022 00:36:19 +0200 Subject: [PATCH 19/59] Implement PixelShaderEffect.Value property --- .../Extensions/ID2D1EffectExtensions.cs | 34 ++++++++++ ...ixelShaderEffect{T}.ICanvasImageInterop.cs | 11 ++- ...PixelShaderEffect{T}.Properties.Interop.cs | 68 +++++++++++++++---- .../PixelShaderEffect{T}.Properties.cs | 6 +- .../PixelShaderEffect{T}.cs | 5 ++ 5 files changed, 104 insertions(+), 20 deletions(-) diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs index ffd7a850..38968217 100644 --- a/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs @@ -1,5 +1,11 @@ +using System.Buffers; +using System.Runtime.CompilerServices; +using System; using ComputeSharp.D2D1.Extensions; using TerraFX.Interop.DirectX; +using ComputeSharp.D2D1.Interop; + +#pragma warning disable CS0618 namespace ComputeSharp.D2D1.Uwp.Extensions; @@ -8,6 +14,34 @@ namespace ComputeSharp.D2D1.Uwp.Extensions; /// internal static unsafe class ID2D1EffectExtensions { + /// + /// Gets the constant buffer of type from a given object. + /// + /// The input instance. + /// The constant buffer of type for . + public static T GetConstantBuffer(this ref ID2D1Effect d2D1Effect) + where T : unmanaged, ID2D1PixelShader + { + int constantBufferSize = D2D1PixelShader.GetConstantBufferSize(); + byte[] buffer = ArrayPool.Shared.Rent(constantBufferSize); + + fixed (byte* p = buffer) + { + // Get the raw constant buffer from the effect + d2D1Effect.GetValue( + index: D2D1PixelShaderEffectProperty.ConstantBuffer, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BLOB, + data: p, + dataSize: (uint)constantBufferSize).Assert(); + } + + Unsafe.SkipInit(out T shader); + + shader.InitializeFromDispatchData(buffer.AsSpan(0, constantBufferSize)); + + return shader; + } + /// /// Gets the property for a given object. /// diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index 0712a2f6..7e819cba 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -166,7 +166,8 @@ unsafe partial class PixelShaderEffect return; } - // Cache the last update value of the cache and precision properties + // Cache the last update values for the constant buffer, cache output and buffer precision properties + this.value = this.d2D1Effect.Get()->GetConstantBuffer(); this.cacheOutput = this.d2D1Effect.Get()->GetCachedProperty(); this.d2D1BufferPrecision = this.d2D1Effect.Get()->GetPrecisionProperty(); @@ -231,7 +232,8 @@ unsafe partial class PixelShaderEffect hresult.Assert(); } - // TODO: transfer properties (eg. D2D1ResourceTextureManager-s) + // Set the constant buffer for the effect + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(this.value, this.d2D1Effect.Get()); // If cache input has been set, forward that to the new effect if (this.cacheOutput) @@ -247,8 +249,7 @@ unsafe partial class PixelShaderEffect // TODO: port base CanvasEffect::Realize logic - // Also set the current constants for the effect - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(Value, this.d2D1Effect.Get()); + // TODO: transfer properties (eg. D2D1ResourceTextureManager-s) } /// @@ -259,8 +260,6 @@ unsafe partial class PixelShaderEffect /// The instance in use. private void RefreshInputs(CanvasImageGetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) { - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(Value, this.d2D1Effect.Get()); - // TODO } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs index e5a12ea1..324c7a06 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs @@ -1,3 +1,4 @@ +using ComputeSharp.D2D1.Interop; using ComputeSharp.D2D1.Uwp.Extensions; using ComputeSharp.Interop; using Microsoft.Graphics.Canvas; @@ -8,6 +9,47 @@ namespace ComputeSharp.D2D1.Uwp; /// unsafe partial class PixelShaderEffect { + /// + /// Gets the marshalled value for . + /// + /// The marshalled value for . + private T GetConstantBuffer() + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + return this.d2D1Effect.Get() switch + { + not null => this.d2D1Effect.Get()->GetConstantBuffer(), + _ => this.value + }; + } + } + + /// + /// Sets the marshalled value for . + /// + /// The value to set for . + private void SetConstantBuffer(in T value) + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + // If the effect is realized, set the property on the underlying ID2D1Effect object + if (this.d2D1Effect.Get() is not null) + { + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in value, this.d2D1Effect.Get()); + } + else + { + // Otherwise, just store the value locally + this.value = value; + } + } + } + /// /// Gets the marshalled value for . /// @@ -18,13 +60,11 @@ unsafe partial class PixelShaderEffect lock (this.lockObject) { - // If the effect is realized, get the latest value from it - if (this.d2D1Effect.Get() is not null) + return this.d2D1Effect.Get() switch { - this.cacheOutput = this.d2D1Effect.Get()->GetCachedProperty(); - } - - return this.cacheOutput; + not null => this.d2D1Effect.Get()->GetCachedProperty(), + _ => this.cacheOutput + }; } } @@ -38,13 +78,15 @@ unsafe partial class PixelShaderEffect lock (this.lockObject) { - this.cacheOutput = value; - - // If the effect is realized, set the property on the underlying ID2D1Effect object too + // If the effect is realized, set the property on the underlying ID2D1Effect object if (this.d2D1Effect.Get() is not null) { this.d2D1Effect.Get()->SetCachedProperty(value); } + else + { + this.cacheOutput = value; + } } } @@ -58,11 +100,11 @@ unsafe partial class PixelShaderEffect lock (this.lockObject) { - // If the effect is realized, get the latest value from it - if (this.d2D1Effect.Get() is not null) + D2D1_BUFFER_PRECISION d2D1BufferPrecision = this.d2D1Effect.Get() switch { - this.d2D1BufferPrecision = this.d2D1Effect.Get()->GetPrecisionProperty(); - } + not null => this.d2D1Effect.Get()->GetPrecisionProperty(), + _ => this.d2D1BufferPrecision + }; // Map from D2D1_BUFFER_PRECISION to CanvasBufferPrecision, and return null for D2D1_BUFFER_PRECISION_UNKNOWN return this.d2D1BufferPrecision switch diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs index 2042522d..9904cecc 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs @@ -25,7 +25,11 @@ partial class PixelShaderEffect /// /// Gets or sets the current value in use. /// - public T Value { get; set; } + public T Value + { + get => GetConstantBuffer(); + set => SetConstantBuffer(in value); + } /// /// Gets the object associated with the current instance. diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs index e8a1273c..1b3a1754 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs @@ -43,6 +43,11 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan /// private ComPtr d2D1Effect; + /// + /// The backing field for . + /// + private T value; + /// /// The backing field for . /// From 0e7c28f86e646a1c26f1a7ca3343b05b1bb63258 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 27 Oct 2022 01:08:24 +0200 Subject: [PATCH 20/59] Centralize [ComVisible(false)] for UWP projects in .targets --- .../Properties/AssemblyInfo.cs | 3 --- src/ComputeSharp.Uwp/Properties/AssemblyInfo.cs | 3 --- src/Directory.Build.targets | 17 +++++++++++++---- 3 files changed, 13 insertions(+), 10 deletions(-) delete mode 100644 src/ComputeSharp.D2D1.Uwp/Properties/AssemblyInfo.cs delete mode 100644 src/ComputeSharp.Uwp/Properties/AssemblyInfo.cs diff --git a/src/ComputeSharp.D2D1.Uwp/Properties/AssemblyInfo.cs b/src/ComputeSharp.D2D1.Uwp/Properties/AssemblyInfo.cs deleted file mode 100644 index 5777bd26..00000000 --- a/src/ComputeSharp.D2D1.Uwp/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,3 +0,0 @@ -using System.Runtime.InteropServices; - -[assembly: ComVisible(false)] \ No newline at end of file diff --git a/src/ComputeSharp.Uwp/Properties/AssemblyInfo.cs b/src/ComputeSharp.Uwp/Properties/AssemblyInfo.cs deleted file mode 100644 index 5777bd26..00000000 --- a/src/ComputeSharp.Uwp/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,3 +0,0 @@ -using System.Runtime.InteropServices; - -[assembly: ComVisible(false)] \ No newline at end of file diff --git a/src/Directory.Build.targets b/src/Directory.Build.targets index a1b282c8..8c724af5 100644 --- a/src/Directory.Build.targets +++ b/src/Directory.Build.targets @@ -2,20 +2,18 @@ + - - true true + - - <_Parameter1>$(SupportedOSVersion) @@ -23,9 +21,20 @@ + + + + + <_Parameter1>false + + + + $(IntermediateOutputPath)$(MSBuildProjectName).SkipLocalsInit.g.cs From f31627c472b006b44643bf10a9a0ccf604d6ef78 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 3 Nov 2022 23:44:46 +0100 Subject: [PATCH 21/59] Update GetD2DImageFlags type with new Win2D changes --- ...mageGetD2DImageFlags.cs => GetD2DImageFlags.cs} | 9 +++++++-- .../ICanvasImageInterop.cs | 8 ++++---- .../PixelShaderEffect{T}.ICanvasImageInterop.cs | 14 +++++++------- .../D2D1TransformMapper{T, TParameters}.cs | 1 + 4 files changed, 19 insertions(+), 13 deletions(-) rename src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/{CanvasImageGetD2DImageFlags.cs => GetD2DImageFlags.cs} (81%) diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/CanvasImageGetD2DImageFlags.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/GetD2DImageFlags.cs similarity index 81% rename from src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/CanvasImageGetD2DImageFlags.cs rename to src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/GetD2DImageFlags.cs index 23ecb8cc..85af8c4c 100644 --- a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/CanvasImageGetD2DImageFlags.cs +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/GetD2DImageFlags.cs @@ -6,7 +6,7 @@ namespace ABI.Microsoft.Graphics.Canvas; /// Options for fine-tuning the behavior of . /// [Flags] -internal enum CanvasImageGetD2DImageFlags +internal enum GetD2DImageFlags { /// /// No options specified. @@ -36,5 +36,10 @@ internal enum CanvasImageGetD2DImageFlags /// /// Allow partially configured effect graphs where some inputs are . /// - AllowNullEffectInputs = 16 + AllowNullEffectInputs = 16, + + /// + /// If an input is invalid, unrealize the effect and set the output image to . + /// + UnrealizeOnFailure = 32 } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs index ef451257..7deb3cc3 100644 --- a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs @@ -41,7 +41,7 @@ internal unsafe struct ICanvasImageInterop /// The input canvas device (as a marshalled ). /// /// The device context in use. This value is is optional (but recommended), except when the - /// flag is specified. This is because + /// flag is specified. This is because /// not all callers of have easy access to a context. It is always /// possible to get a resource creation context from the device, but the context is only /// actually necessary if a new effect realization needs to be created, so it is more efficient @@ -51,8 +51,8 @@ internal unsafe struct ICanvasImageInterop /// /// The DPI of the target device context. This is used to determine when a D2D1DpiCompensation /// effect needs to be inserted. Behavior of this parameter can be overridden by the flag values - /// , - /// or + /// , + /// or /// /// /// The DPI of a source bitmap, or zero if the image does not have a fixed DPI. A D2D1DpiCompensation effect @@ -65,7 +65,7 @@ internal unsafe struct ICanvasImageInterop int GetD2DImage( ICanvasDevice* device, ID2D1DeviceContext* deviceContext, - CanvasImageGetD2DImageFlags flags, + GetD2DImageFlags flags, float targetDpi, float* realizeDpi, ID2D1Image** ppImage); diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index 7e819cba..ec8b40cb 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -52,7 +52,7 @@ unsafe partial class PixelShaderEffect int ICanvasImageInterop.Interface.GetD2DImage( ICanvasDevice* device, ID2D1DeviceContext* deviceContext, - CanvasImageGetD2DImageFlags flags, + GetD2DImageFlags flags, float targetDpi, float* realizeDpi, ID2D1Image** ppImage) @@ -77,7 +77,7 @@ unsafe partial class PixelShaderEffect lock (this.lockObject) { // Process the ReadDpiFromDeviceContext flag (same logic as CanvasEffect::GetD2DImage) - if ((flags & CanvasImageGetD2DImageFlags.ReadDpiFromDeviceContext) != CanvasImageGetD2DImageFlags.None) + if ((flags & GetD2DImageFlags.ReadDpiFromDeviceContext) != GetD2DImageFlags.None) { // If ReadDpiFromDeviceContext is used, the context cannot be null if (deviceContext is null) @@ -88,7 +88,7 @@ unsafe partial class PixelShaderEffect if (deviceContext->HasCommandListTarget()) { // Command lists are DPI dependent, so DPI compensation effects are always needed - flags |= CanvasImageGetD2DImageFlags.AlwaysInsertDpiCompensation; + flags |= GetD2DImageFlags.AlwaysInsertDpiCompensation; } else { @@ -97,7 +97,7 @@ unsafe partial class PixelShaderEffect } // ReadDpiFromDeviceContext has been processed, so it can be removed now - flags &= ~CanvasImageGetD2DImageFlags.ReadDpiFromDeviceContext; + flags &= ~GetD2DImageFlags.ReadDpiFromDeviceContext; } using ComPtr d2D1Device1 = default; @@ -125,7 +125,7 @@ unsafe partial class PixelShaderEffect { Realize(flags, targetDpi, deviceContext); } - else if (!flags.HasFlag(CanvasImageGetD2DImageFlags.MinimalRealization)) + else if (!flags.HasFlag(GetD2DImageFlags.MinimalRealization)) { // Recurse through the effect graph and ensure all nodes are initialized RefreshInputs(flags, targetDpi, deviceContext); @@ -183,7 +183,7 @@ unsafe partial class PixelShaderEffect /// The current flags in use. /// The target DPI in use. /// The instance in use. - private void Realize(CanvasImageGetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) + private void Realize(GetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) { using ComPtr d2D1Factory = default; @@ -258,7 +258,7 @@ unsafe partial class PixelShaderEffect /// The current flags in use. /// The target DPI in use. /// The instance in use. - private void RefreshInputs(CanvasImageGetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) + private void RefreshInputs(GetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) { // TODO } 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 5f602c97..774f063c 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 @@ -35,6 +35,7 @@ internal abstract class D2D1TransformMapper : D2D1TransformMappe Unsafe.SkipInit(out output); output.ToD2D1Infinite(); + opaqueOutput = Rectangle.Empty; } else From baa1d54cc586735b2e01e7ddf7c57a21e9156913 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 25 Nov 2022 13:14:31 +0100 Subject: [PATCH 22/59] Fix naming rule violations --- .../ABI.Microsoft.Graphics.Canvas/ICanvasDevice.cs | 2 +- .../ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs | 2 +- .../ABI.Microsoft.Graphics.Canvas/ICanvasResourceCreator.cs | 2 +- .../ICanvasResourceWrapperNative.cs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasDevice.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasDevice.cs index 32fc10b5..4264c5a3 100644 --- a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasDevice.cs +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasDevice.cs @@ -4,7 +4,7 @@ using System.Runtime.InteropServices; using TerraFX.Interop; using TerraFX.Interop.Windows; -#pragma warning disable CS0649 +#pragma warning disable CS0649, IDE1006 namespace ABI.Microsoft.Graphics.Canvas; diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs index 7deb3cc3..292d499c 100644 --- a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs @@ -4,7 +4,7 @@ using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using TerraFX.Interop; -#pragma warning disable CS0649 +#pragma warning disable CS0649, IDE1006 namespace ABI.Microsoft.Graphics.Canvas; diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceCreator.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceCreator.cs index 099af42d..6e21f388 100644 --- a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceCreator.cs +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceCreator.cs @@ -4,7 +4,7 @@ using System.Runtime.InteropServices; using TerraFX.Interop; using TerraFX.Interop.Windows; -#pragma warning disable CS0649 +#pragma warning disable CS0649, IDE1006 namespace ABI.Microsoft.Graphics.Canvas; diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceWrapperNative.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceWrapperNative.cs index 2f31d72e..2df7b92d 100644 --- a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceWrapperNative.cs +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasResourceWrapperNative.cs @@ -4,7 +4,7 @@ using System.Runtime.InteropServices; using TerraFX.Interop; using TerraFX.Interop.Windows; -#pragma warning disable CS0649 +#pragma warning disable CS0649, IDE1006 namespace ABI.Microsoft.Graphics.Canvas; From 6f726a5951046ad173409a94247aa73831d4956e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 29 Nov 2022 23:59:58 +0100 Subject: [PATCH 23/59] Remove leftover ID2D1TransformMapperFactory references --- ...ixelShaderEffect{T}.ICanvasImageInterop.cs | 20 +++---------------- .../PixelShaderEffect{T}.Properties.cs | 15 -------------- 2 files changed, 3 insertions(+), 32 deletions(-) diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index ec8b40cb..cce1ce96 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -195,26 +195,12 @@ unsafe partial class PixelShaderEffect // D2D1PixelShaderEffect APIs specifically need an ID2D1Factory1 (as ID2D1Factory1::RegisterEffectFromString is used) d2D1Factory.CopyTo(d2D1Factory1.GetAddressOf()).Assert(); - bool isPossiblyRegistered = true; - - // If the effect hasn't been initialized explicitly, initialize it now - if (!PixelShaderEffect.For.TryGetId(out Guid effectId)) - { - PixelShaderEffect.For.Initialize(null); - - effectId = PixelShaderEffect.For.Id; - isPossiblyRegistered = false; - } - fixed (ID2D1Effect** d2D1Effect = this.d2D1Effect) { - HRESULT hresult = D2DERR.D2DERR_EFFECT_IS_NOT_REGISTERED; + Guid effectId = PixelShaderEffect.For.Instance.Id; // Try to create an instance of the effect in use and store it in the current object - if (isPossiblyRegistered) - { - hresult = deviceContext->CreateEffect(effectId: &effectId, effect: d2D1Effect); - } + HRESULT hresult = deviceContext->CreateEffect(effectId: &effectId, effect: d2D1Effect); // Check if creation failed due to the effect not being registered. In that case, register // it and then try again. This is much faster than check whether the effect is registered @@ -222,7 +208,7 @@ unsafe partial class PixelShaderEffect if (hresult == D2DERR.D2DERR_EFFECT_IS_NOT_REGISTERED) { // Register the effect with the factory (pass the same D2D1 draw transform mapper factory that was used before) - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory1.Get(), PixelShaderEffect.For.D2D1DrawTransformMapperFactory, out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory1.Get(), out _); // Try to create the effect again hresult = deviceContext->CreateEffect(effectId: &effectId, effect: d2D1Effect); diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs index 9904cecc..92d56049 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs @@ -1,5 +1,4 @@ using System; -using ComputeSharp.D2D1.Interop.Effects; using Microsoft.Graphics.Canvas; using Windows.Graphics.Effects; @@ -8,20 +7,6 @@ namespace ComputeSharp.D2D1.Uwp; /// partial class PixelShaderEffect { - /// - /// Configures the to use for effects of type . - /// - /// The factory of instances to use for each created effect. - /// Thrown if initialization is attempted with a mismatched transform factory. - /// - /// Initialization can only be done once, and is shared across all effects of type . - /// Initializing an effect is not necessary before using it: if no transform has been set, the default one will be used. - /// - public static void ConfigureD2D1TransformMapperFactory(ID2D1TransformMapperFactory? d2D1DrawTransformMapperFactory) - { - PixelShaderEffect.For.Initialize(d2D1DrawTransformMapperFactory); - } - /// /// Gets or sets the current value in use. /// From 9e95a1cb80a5259a485b7637945370a3e68309e8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 30 Nov 2022 01:06:51 +0100 Subject: [PATCH 24/59] Add ID2D1TransformMapperInternal interface --- ...ransformMapperImpl.ID2D1TransformMapper.cs | 267 +++++++++++------- ...MapperImpl.ID2D1TransformMapperInternal.cs | 87 ++++++ .../D2D1TransformMapperImpl.cs | 137 ++++----- .../ID2D1TransformMapperInternal.cs | 57 ++++ 4 files changed, 367 insertions(+), 181 deletions(-) create mode 100644 src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.ID2D1TransformMapperInternal.cs create mode 100644 src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/ID2D1TransformMapperInternal.cs diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.ID2D1TransformMapper.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.ID2D1TransformMapper.cs index 1dedba7f..930b7409 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.ID2D1TransformMapper.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.ID2D1TransformMapper.cs @@ -1,9 +1,7 @@ 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; @@ -16,128 +14,193 @@ namespace ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; /// unsafe partial struct D2D1TransformMapperImpl { - /// - [UnmanagedCallersOnly] - private static int QueryInterface(D2D1TransformMapperImpl* @this, Guid* riid, void** ppvObject) + /// + /// The implementation for . + /// + private static class ID2D1TransformMapperMethods { - return @this->QueryInterface(riid, ppvObject); - } +#if !NET6_0_OR_GREATER + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int MapInputRectsToOutputRectDelegate( + D2D1TransformMapperImpl* @this, + ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext, + RECT* inputRects, + RECT* inputOpaqueSubRects, + uint inputRectCount, + RECT* outputRect, + RECT* outputOpaqueSubRect); - /// - [UnmanagedCallersOnly] - private static uint AddRef(D2D1TransformMapperImpl* @this) - { - return @this->AddRef(); - } + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int MapOutputRectToInputRectsDelegate( + D2D1TransformMapperImpl* @this, + RECT* outputRect, + RECT* inputRects, + uint inputRectsCount); - /// - [UnmanagedCallersOnly] - private static uint Release(D2D1TransformMapperImpl* @this) - { - return @this->Release(); - } + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int MapInvalidRectDelegate( + D2D1TransformMapperImpl* @this, + uint inputIndex, + RECT invalidInputRect, + RECT* invalidOutputRect); - /// - [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); + /// + /// A cached instance wrapping . + /// + public static readonly QueryInterfaceDelegate QueryInterfaceWrapper = QueryInterface; - for (int i = 0; i < (int)inputRectCount; i++) + /// + /// 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 MapInputRectsToOutputRectDelegate MapInputRectsToOutputRectWrapper = MapInputRectsToOutputRect; + + /// + /// A cached instance wrapping . + /// + public static readonly MapOutputRectToInputRectsDelegate MapOutputRectToInputRectsWrapper = MapOutputRectToInputRects; + + /// + /// A cached instance wrapping . + /// + public static readonly MapInvalidRectDelegate MapInvalidRectWrapper = MapInvalidRect; +#endif + + /// + [UnmanagedCallersOnly] + public static int QueryInterface(D2D1TransformMapperImpl* @this, Guid* riid, void** ppvObject) { - inputs[i] = inputRects[i].ToRectangle(); - opaqueInputs[i] = inputOpaqueSubRects[i].ToRectangle(); + return @this->QueryInterface(riid, ppvObject); } - Rectangle output; - Rectangle opaqueOutput; - - // Invoke MapInputsToOutput and handle exceptions so they don't cross the ABI boundary - try + /// + [UnmanagedCallersOnly] + public static uint AddRef(D2D1TransformMapperImpl* @this) { - Unsafe.As(@this->transformMapperHandle.Target!).MapInputsToOutput( - d2D1DrawInfoUpdateContext, - inputs, - opaqueInputs, - out output, - out opaqueOutput); - } - catch (Exception e) - { - return e.HResult; + return @this->AddRef(); } - *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++) + /// + [UnmanagedCallersOnly] + public static uint Release(D2D1TransformMapperImpl* @this) { - inputs[i] = inputRects[i].ToRectangle(); + return @this->Release(); } - // Handle exceptions, as mentioned above - try + /// + [UnmanagedCallersOnly] + public static int MapInputRectsToOutputRect( + D2D1TransformMapperImpl* @this, + ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext, + RECT* inputRects, + RECT* inputOpaqueSubRects, + uint inputRectCount, + RECT* outputRect, + RECT* outputOpaqueSubRect) { - Unsafe.As(@this->transformMapperHandle.Target!).MapOutputToInputs(in output, inputs); - } - catch (Exception e) - { - return e.HResult; + 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; } - for (int i = 0; i < (int)inputRectsCount; i++) + /// + [UnmanagedCallersOnly] + public static int MapOutputRectToInputRects( + D2D1TransformMapperImpl* @this, + RECT* outputRect, + RECT* inputRects, + uint inputRectsCount) { - inputRects[i] = inputs[i].ToRECT(); + 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; } - 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 + /// + [UnmanagedCallersOnly] + public static int MapInvalidRect( + D2D1TransformMapperImpl* @this, + uint inputIndex, + RECT invalidInputRect, + RECT* invalidOutputRect) { - Unsafe.As(@this->transformMapperHandle.Target!).MapInvalidOutput((int)inputIndex, invalidInput, out invalidOutput); - } - catch (Exception e) - { - return e.HResult; - } + Rectangle invalidInput = invalidInputRect.ToRectangle(); + Rectangle invalidOutput; - *invalidOutputRect = invalidOutput.ToRECT(); + // Handle exceptions once again + try + { + Unsafe.As(@this->transformMapperHandle.Target!).MapInvalidOutput((int)inputIndex, invalidInput, out invalidOutput); + } + catch (Exception e) + { + return e.HResult; + } - return S.S_OK; + *invalidOutputRect = invalidOutput.ToRECT(); + + return S.S_OK; + } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.ID2D1TransformMapperInternal.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.ID2D1TransformMapperInternal.cs new file mode 100644 index 00000000..a8b27553 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.ID2D1TransformMapperInternal.cs @@ -0,0 +1,87 @@ +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 D2D1TransformMapperImpl +{ + /// + /// The implementation for . + /// + private static class ID2D1TransformMapperInternalMethods + { +#if !NET6_0_OR_GREATER + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int GetManagedWrapperHandleDelegate(D2D1TransformMapperImpl* @this, void** ppvHandle); + + /// + /// 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 GetManagedWrapperHandleDelegate GetManagedWrapperHandleWrapper = GetManagedWrapperHandle; +#endif + + /// + [UnmanagedCallersOnly] + public static int QueryInterface(D2D1TransformMapperImpl* @this, Guid* riid, void** ppvObject) + { + @this = (D2D1TransformMapperImpl*)&((void**)@this)[-1]; + + return @this->QueryInterface(riid, ppvObject); + } + + /// + [UnmanagedCallersOnly] + public static uint AddRef(D2D1TransformMapperImpl* @this) + { + @this = (D2D1TransformMapperImpl*)&((void**)@this)[-1]; + + return @this->AddRef(); + } + + /// + [UnmanagedCallersOnly] + public static uint Release(D2D1TransformMapperImpl* @this) + { + @this = (D2D1TransformMapperImpl*)&((void**)@this)[-1]; + + return @this->Release(); + } + + /// + [UnmanagedCallersOnly] + public static int GetManagedWrapperHandle(D2D1TransformMapperImpl* @this, void** ppvHandle) + { + @this = (D2D1TransformMapperImpl*)&((void**)@this)[-1]; + + if (ppvHandle is null) + { + return E.E_POINTER; + } + + *ppvHandle = (void*)GCHandle.ToIntPtr(@this->transformMapperHandle); + + 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 index 0454c6e2..c8cce206 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.cs @@ -30,101 +30,68 @@ internal unsafe partial struct D2D1TransformMapperImpl /// [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. + /// The shared vtable pointer for instance, for . /// - private static readonly void** Vtbl = InitVtbl(); + private static readonly void** VtblForID2D1TransformMapper = InitVtblForID2D1TransformMapperAndID2D1TransformMapperInternal(); /// - /// Builds the custom method table pointer for . + /// The shared vtable pointer for instance, for . /// - /// The method table pointer for . - private static void** InitVtbl() - { - void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(D2D1TransformMapperImpl), sizeof(void*) * 6); + private static readonly void** VtblForID2D1TransformMapperInternal = &VtblForID2D1TransformMapper[6]; + /// + /// Initializes the combined vtable for and . + /// + /// The combined vtable for and . + private static void** InitVtblForID2D1TransformMapperAndID2D1TransformMapperInternal() + { + void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(D2D1TransformMapperImpl), sizeof(void*) * 10); + + // ID2D1ResourceTextureManager #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; + lpVtbl[0] = (delegate* unmanaged)&ID2D1TransformMapperMethods.QueryInterface; + lpVtbl[1] = (delegate* unmanaged)&ID2D1TransformMapperMethods.AddRef; + lpVtbl[2] = (delegate* unmanaged)&ID2D1TransformMapperMethods.Release; + lpVtbl[3] = (delegate* unmanaged)&ID2D1TransformMapperMethods.MapInputRectsToOutputRect; + lpVtbl[4] = (delegate* unmanaged)&ID2D1TransformMapperMethods.MapOutputRectToInputRects; + lpVtbl[5] = (delegate* unmanaged)&ID2D1TransformMapperMethods.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); + lpVtbl[0] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1TransformMapperMethods.QueryInterfaceWrapper); + lpVtbl[1] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1TransformMapperMethods.AddRefWrapper); + lpVtbl[2] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1TransformMapperMethods.ReleaseWrapper); + lpVtbl[3] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1TransformMapperMethods.MapInputRectsToOutputRectWrapper); + lpVtbl[4] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1TransformMapperMethods.MapOutputRectToInputRectsWrapper); + lpVtbl[5] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1TransformMapperMethods.MapInvalidRectWrapper); +#endif + + // ID2D1TransformMapperInternal +#if NET6_0_OR_GREATER + lpVtbl[6 + 0] = (delegate* unmanaged)&ID2D1TransformMapperInternalMethods.QueryInterface; + lpVtbl[6 + 1] = (delegate* unmanaged)&ID2D1TransformMapperInternalMethods.AddRef; + lpVtbl[6 + 2] = (delegate* unmanaged)&ID2D1TransformMapperInternalMethods.Release; + lpVtbl[6 + 3] = (delegate* unmanaged)&ID2D1TransformMapperInternalMethods.GetManagedWrapperHandle; +#else + lpVtbl[6 + 0] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1TransformMapperInternalMethods.QueryInterfaceWrapper); + lpVtbl[6 + 1] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1TransformMapperInternalMethods.AddRefWrapper); + lpVtbl[6 + 2] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1TransformMapperInternalMethods.ReleaseWrapper); + lpVtbl[6 + 3] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1TransformMapperInternalMethods.GetManagedWrapperHandleWrapper); #endif return lpVtbl; } /// - /// The vtable pointer for the current instance. + /// The vtable pointer for the current instance, for . /// - private void** lpVtbl; + private void** lpVtblForID2D1TransformMapper; + + /// + /// The vtable pointer for the current instance, for . + /// + private void** lpVtblForID2D1TransformMapperInternal; /// /// The current reference count for the object (from ). @@ -152,7 +119,8 @@ internal unsafe partial struct D2D1TransformMapperImpl { D2D1TransformMapperImpl* @this = (D2D1TransformMapperImpl*)NativeMemory.Alloc((nuint)sizeof(D2D1TransformMapperImpl)); - @this->lpVtbl = Vtbl; + @this->lpVtblForID2D1TransformMapper = VtblForID2D1TransformMapper; + @this->lpVtblForID2D1TransformMapperInternal = VtblForID2D1TransformMapperInternal; @this->referenceCount = 1; @this->transformMapperHandle = GCHandle.Alloc(transformMapper); @this->spinLock = new SpinLock(enableThreadOwnerTracking: false); @@ -203,6 +171,7 @@ internal unsafe partial struct D2D1TransformMapperImpl return E.E_POINTER; } + // ID2D1TransformMapper if (riid->Equals(Windows.__uuidof()) || riid->Equals(ID2D1TransformMapper.Guid)) { @@ -213,6 +182,16 @@ internal unsafe partial struct D2D1TransformMapperImpl return S.S_OK; } + // ID2D1TransformMapperInternal + if (riid->Equals(ID2D1TransformMapperInternal.Guid)) + { + this.referenceCount++; + + *ppvObject = (void**)Unsafe.AsPointer(ref this) + 1; + + return S.S_OK; + } + *ppvObject = null; return E.E_NOINTERFACE; diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/ID2D1TransformMapperInternal.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/ID2D1TransformMapperInternal.cs new file mode 100644 index 00000000..bf88f527 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/ID2D1TransformMapperInternal.cs @@ -0,0 +1,57 @@ +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 internal transform mapper manager interface. +/// +[Guid("C5D8FC65-FB86-4C2D-9EF5-95AEC639C952")] +internal unsafe struct ID2D1TransformMapperInternal +{ + /// + /// Gets the for (C5D8FC65-FB86-4C2D-9EF5-95AEC639C952). + /// + public static ref readonly Guid Guid + { + get + { + ReadOnlySpan data = new byte[] { + 0x65, 0xFC, 0xD8, 0xC5, + 0x86, 0xFB, + 0xF5, 0x9E, + 0x9E, 0xF5, + 0x95, + 0xAE, + 0xC6, + 0x39, + 0xC9, + 0x52 + }; + + return ref Unsafe.As(ref MemoryMarshal.GetReference(data)); + } + } + + /// + /// The vtable for the current instance. + /// + private readonly void** lpVtbl; + + /// + /// Gets a value for the managed wrapper associated with this CCW. + /// + /// The value for the managed wrapper associated with this CCW. + /// An for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public HRESULT GetManagedWrapperHandle(void** ppvHandle) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[3])( + (ID2D1TransformMapperInternal*)Unsafe.AsPointer(ref this), + ppvHandle); + } +} \ No newline at end of file From e57caf94b2c9e90630f882c180ac86410c722228 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 30 Nov 2022 01:19:23 +0100 Subject: [PATCH 25/59] Add ID2D1TransformMapperInternal unit tests --- .../ID2D1TransformMapperInternal.cs | 2 +- .../D2D1TransformMapperTests.cs | 42 ++++++++++++++++++- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/ID2D1TransformMapperInternal.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/ID2D1TransformMapperInternal.cs index bf88f527..276434ef 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/ID2D1TransformMapperInternal.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/ID2D1TransformMapperInternal.cs @@ -23,7 +23,7 @@ internal unsafe struct ID2D1TransformMapperInternal ReadOnlySpan data = new byte[] { 0x65, 0xFC, 0xD8, 0xC5, 0x86, 0xFB, - 0xF5, 0x9E, + 0x2D, 0x4C, 0x9E, 0xF5, 0x95, 0xAE, diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1TransformMapperTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1TransformMapperTests.cs index d72014fe..ee0e42a4 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1TransformMapperTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1TransformMapperTests.cs @@ -14,6 +14,7 @@ using Win32.Graphics.Direct2D; namespace ComputeSharp.D2D1.Tests; +using HRESULT = HResult; using D2D1_MAPPED_RECT = MappedRect; using Rectangle = System.Drawing.Rectangle; @@ -28,16 +29,20 @@ public partial class D2D1TransformMapperTests using ComPtr unknown = default; using ComPtr transformMapper2 = default; + using ComPtr transformMapperInternal = default; Guid uuidOfIUnknown = typeof(IUnknown).GUID; Guid uuidOfTransformMapper = new("02E6D48D-B892-4FBC-AA54-119203BAB802"); + Guid uuidOfTransformMapperInternal = new("C5D8FC65-FB86-4C2D-9EF5-95AEC639C952"); - // The object implements IUnknown and the transform mapper interface + // The object implements IUnknown and the transform mapper interfaces 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.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)transformMapper).GetInterface(ref uuidOfTransformMapperInternal, out *(IntPtr*)transformMapperInternal.GetAddressOf())); Assert.IsTrue(unknown.Get() is not null); Assert.IsTrue(transformMapper2.Get() is not null); + Assert.IsTrue(transformMapperInternal.Get() is not null); using ComPtr garbage = default; @@ -96,6 +101,41 @@ public partial class D2D1TransformMapperTests Assert.AreEqual(2u, transformMapper2.Get()->Release()); } + [TestMethod] + public unsafe void VerifyManagedWrapperRetrieval() + { + D2D1TransformMapper transformMapper = D2D1TransformMapperFactory.Inflate(4); + + using ComPtr unknown = default; + using ComPtr transformMapperInternal = default; + + Guid uuidOfIUnknown = typeof(IUnknown).GUID; + Guid uuidOfTransformMapperInternal = new("C5D8FC65-FB86-4C2D-9EF5-95AEC639C952"); + + Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)transformMapper).GetInterface(ref uuidOfIUnknown, out *(IntPtr*)unknown.GetAddressOf())); + + Assert.IsTrue(unknown.Get() is not null); + + HRESULT hresult = unknown.CopyTo(&uuidOfTransformMapperInternal, (void**)transformMapperInternal.GetAddressOf()); + + Assert.AreEqual(hresult, HRESULT.Ok); + Assert.IsTrue(transformMapperInternal.Get() is not null); + + IntPtr handlePtr; + + // Invoke GetManagedWrapperHandle + hresult = ((delegate* unmanaged[Stdcall])(*(void***)transformMapperInternal.Get())[3])( + transformMapperInternal.Get(), + (void**)&handlePtr); + + Assert.AreEqual(hresult, HRESULT.Ok); + + GCHandle handle = GCHandle.FromIntPtr(handlePtr); + + Assert.IsNotNull(handle.Target); + Assert.AreSame(handle.Target, transformMapper); + } + [D2DInputCount(0)] private partial struct DummyShader : ID2D1PixelShader { From 68bf5fe9b38d292b899cc5e9619237b939774d3e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 30 Nov 2022 01:25:43 +0100 Subject: [PATCH 26/59] Add PixelShaderEffect.TransformMapper property --- .../ComputeSharp.D2D1.NetStandard.projitems | 1 + .../DisallowNullAttribute.cs | 13 ++++++ .../Extensions/ID2D1EffectExtensions.cs | 42 +++++++++++++++++++ ...ixelShaderEffect{T}.ICanvasImageInterop.cs | 7 ++++ ...PixelShaderEffect{T}.Properties.Interop.cs | 40 +++++++++++++++++- .../PixelShaderEffect{T}.Properties.cs | 17 +++++++- .../PixelShaderEffect{T}.cs | 6 +++ 7 files changed, 123 insertions(+), 3 deletions(-) create mode 100644 src/ComputeSharp.D2D1.NetStandard/System/Diagnostics.CodeAnalysis/DisallowNullAttribute.cs diff --git a/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems b/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems index e130179f..d973ffe7 100644 --- a/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems +++ b/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems @@ -11,6 +11,7 @@ + diff --git a/src/ComputeSharp.D2D1.NetStandard/System/Diagnostics.CodeAnalysis/DisallowNullAttribute.cs b/src/ComputeSharp.D2D1.NetStandard/System/Diagnostics.CodeAnalysis/DisallowNullAttribute.cs new file mode 100644 index 00000000..a584aa30 --- /dev/null +++ b/src/ComputeSharp.D2D1.NetStandard/System/Diagnostics.CodeAnalysis/DisallowNullAttribute.cs @@ -0,0 +1,13 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Diagnostics.CodeAnalysis; + +/// +/// Specifies that null is disallowed as an input even if the corresponding type allows it. +/// +[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)] +internal sealed class DisallowNullAttribute : Attribute +{ +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs index 38968217..7111671b 100644 --- a/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs @@ -4,6 +4,9 @@ using System; using ComputeSharp.D2D1.Extensions; using TerraFX.Interop.DirectX; using ComputeSharp.D2D1.Interop; +using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; +using TerraFX.Interop.Windows; +using System.Runtime.InteropServices; #pragma warning disable CS0618 @@ -17,6 +20,7 @@ internal static unsafe class ID2D1EffectExtensions /// /// Gets the constant buffer of type from a given object. /// + /// The type of shader being used. /// The input instance. /// The constant buffer of type for . public static T GetConstantBuffer(this ref ID2D1Effect d2D1Effect) @@ -42,6 +46,44 @@ internal static unsafe class ID2D1EffectExtensions return shader; } + /// + /// Gets the instance from a given object. + /// + /// The type of shader being used. + /// The input instance. + /// The instance for . + public static D2D1TransformMapper? GetTransformMapper(this ref ID2D1Effect d2D1Effect) + where T : unmanaged, ID2D1PixelShader + { + using ComPtr d2D1TransformMapper = default; + + // Get the ID2D1TransformMapper object from the effect + d2D1Effect.GetValue( + index: D2D1PixelShaderEffectProperty.TransformMapper, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_IUNKNOWN, + data: (byte*)d2D1TransformMapper.GetAddressOf(), + dataSize: (uint)sizeof(void*)).Assert(); + + // If there is no transform, just return null (this is the default state) + if (d2D1TransformMapper.Get() is null) + { + return null; + } + + // Otherwise, check if it's an internal CCW and retrieve the managed wrapper + using ComPtr d2D1TransformMapperInternal = default; + + d2D1TransformMapper.CopyTo(d2D1TransformMapperInternal.GetAddressOf()).Assert(); + + IntPtr handlePtr; + + // Get the underlying GCHandle value + d2D1TransformMapperInternal.Get()->GetManagedWrapperHandle((void**)&handlePtr).Assert(); + + // Retrieve the managed wrapper from the GCHandle + return (D2D1TransformMapper)GCHandle.FromIntPtr(handlePtr).Target!; + } + /// /// Gets the property for a given object. /// diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index cce1ce96..01db5a66 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -168,6 +168,7 @@ unsafe partial class PixelShaderEffect // Cache the last update values for the constant buffer, cache output and buffer precision properties this.value = this.d2D1Effect.Get()->GetConstantBuffer(); + this.transformMapper = this.d2D1Effect.Get()->GetTransformMapper(); this.cacheOutput = this.d2D1Effect.Get()->GetCachedProperty(); this.d2D1BufferPrecision = this.d2D1Effect.Get()->GetPrecisionProperty(); @@ -221,6 +222,12 @@ unsafe partial class PixelShaderEffect // Set the constant buffer for the effect D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(this.value, this.d2D1Effect.Get()); + // If there is a transform mapper, set it in the effect + if (this.transformMapper is not null) + { + D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(this.d2D1Effect.Get(), this.transformMapper); + } + // If cache input has been set, forward that to the new effect if (this.cacheOutput) { diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs index 324c7a06..24e3f12d 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs @@ -50,6 +50,45 @@ unsafe partial class PixelShaderEffect } } + /// + /// Gets the marshalled value for . + /// + /// The marshalled value for . + private D2D1TransformMapper? GetTransformMapper() + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + return this.d2D1Effect.Get() switch + { + not null => this.d2D1Effect.Get()->GetTransformMapper(), + _ => this.transformMapper + }; + } + } + + /// + /// Sets the marshalled value for . + /// + /// The value to set for . + private void SetTransformMapper(D2D1TransformMapper value) + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + if (this.d2D1Effect.Get() is not null) + { + D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(this.d2D1Effect.Get(), value); + } + else + { + this.transformMapper = value; + } + } + } + /// /// Gets the marshalled value for . /// @@ -78,7 +117,6 @@ unsafe partial class PixelShaderEffect lock (this.lockObject) { - // If the effect is realized, set the property on the underlying ID2D1Effect object if (this.d2D1Effect.Get() is not null) { this.d2D1Effect.Get()->SetCachedProperty(value); diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs index 92d56049..2fc34204 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs @@ -1,4 +1,6 @@ using System; +using System.Diagnostics.CodeAnalysis; +using ComputeSharp.D2D1.Interop; using Microsoft.Graphics.Canvas; using Windows.Graphics.Effects; @@ -17,9 +19,15 @@ partial class PixelShaderEffect } /// - /// Gets the object associated with the current instance. + /// Gets or sets the instance to use for the effect, if any. /// - public SourceCollection Sources { get; } = new(); + /// Thrown if the value is set to . + [DisallowNull] + public D2D1TransformMapper? TransformMapper + { + get => GetTransformMapper(); + set => SetTransformMapper(value); + } /// /// Gets or sets a value indicating whether to enable caching the output from drawing this effect. @@ -40,6 +48,11 @@ partial class PixelShaderEffect set => SetBufferPrecision(value); } + /// + /// Gets the object associated with the current instance. + /// + public SourceCollection Sources { get; } = new(); + /// /// Represents the collection of sources in a instance. /// diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs index 1b3a1754..b98ef02e 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs @@ -1,4 +1,5 @@ using ABI.Microsoft.Graphics.Canvas; +using ComputeSharp.D2D1.Interop; using ComputeSharp.Interop; using Microsoft.Graphics.Canvas; using TerraFX.Interop.DirectX; @@ -48,6 +49,11 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan /// private T value; + /// + /// The backing field for . + /// + private D2D1TransformMapper? transformMapper; + /// /// The backing field for . /// From 4a5bf75db63f02e02121b420512edad7f6e96a31 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 30 Nov 2022 01:48:37 +0100 Subject: [PATCH 27/59] Move constructor, add resource texture manager collection --- .../PixelShaderEffect{T}.Properties.cs | 55 ++++++++++++++++++- .../PixelShaderEffect{T}.ReferenceTracking.cs | 8 --- .../PixelShaderEffect{T}.cs | 11 ++++ 3 files changed, 65 insertions(+), 9 deletions(-) diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs index 2fc34204..2d5db8e2 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs @@ -51,13 +51,32 @@ partial class PixelShaderEffect /// /// Gets the object associated with the current instance. /// - public SourceCollection Sources { get; } = new(); + public SourceCollection Sources { get; } + + /// + /// Gets the object associated with the current instance. + /// + public ResourceTextureManagerCollection ResourceTextureManagers { get; } /// /// Represents the collection of sources in a instance. /// public sealed class SourceCollection { + /// + /// Creates a new instance with the specified parameters. + /// + /// The owning instance. + internal SourceCollection(PixelShaderEffect owner) + { + Owner = owner; + } + + /// + /// The owning instance. + /// + internal PixelShaderEffect Owner { get; } + /// /// Gets or sets the source at a specified index. /// @@ -70,4 +89,38 @@ partial class PixelShaderEffect set { } } } + + /// + /// Represents the collection of objects in a instance. + /// + public sealed class ResourceTextureManagerCollection + { + /// + /// Creates a new instance with the specified parameters. + /// + /// The owning instance. + internal ResourceTextureManagerCollection(PixelShaderEffect owner) + { + Owner = owner; + } + + /// + /// The owning instance. + /// + internal PixelShaderEffect Owner { get; } + + /// + /// Gets or sets the object at a specified index. + /// + /// The index of the source to get or set. + /// The object at the specified index. + /// Thrown if the value is set to . + /// Thrown if is not a valid index for the current effect. + [DisallowNull] + public D2D1ResourceTextureManager this[int index] + { + get => null!; + set { } + } + } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs index 49ca9198..9ff4da45 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs @@ -7,14 +7,6 @@ namespace ComputeSharp.D2D1.Uwp; /// partial class PixelShaderEffect { - /// - /// Creates a new instance. - /// - public PixelShaderEffect() - { - this.referenceTracker = new(); - } - /// /// Releases unmanaged resources and performs other cleanup operations. /// diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs index b98ef02e..24264553 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs @@ -63,4 +63,15 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan /// The backing field for . /// private D2D1_BUFFER_PRECISION d2D1BufferPrecision; + + /// + /// Creates a new instance. + /// + public PixelShaderEffect() + { + this.referenceTracker = new ReferenceTracker(this); + + Sources = new SourceCollection(this); + ResourceTextureManagers = new ResourceTextureManagerCollection(this); + } } \ No newline at end of file From e64b638454a009076a0f894f17c770ff48f152ce Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 30 Nov 2022 02:50:17 +0100 Subject: [PATCH 28/59] Add PixelShaderEffect.ResourceTextureManagers property --- .../Extensions/ID2D1EffectExtensions.cs | 61 ++++++- ...ixelShaderEffect{T}.ICanvasImageInterop.cs | 14 +- ...PixelShaderEffect{T}.Properties.Interop.cs | 43 +++++ ...erties.ResourceTextureManagerCollection.cs | 165 ++++++++++++++++++ .../PixelShaderEffect{T}.Properties.cs | 34 ---- .../Shaders/Interop/Helpers/Rectangle64.cs | 12 +- 6 files changed, 282 insertions(+), 47 deletions(-) create mode 100644 src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs index 7111671b..c36f62bb 100644 --- a/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs @@ -1,12 +1,14 @@ +using System; using System.Buffers; using System.Runtime.CompilerServices; -using System; -using ComputeSharp.D2D1.Extensions; -using TerraFX.Interop.DirectX; -using ComputeSharp.D2D1.Interop; -using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; -using TerraFX.Interop.Windows; using System.Runtime.InteropServices; +using ComputeSharp.D2D1.Extensions; +using ComputeSharp.D2D1.Helpers; +using ComputeSharp.D2D1.Interop; +using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; +using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; #pragma warning disable CS0618 @@ -84,6 +86,53 @@ internal static unsafe class ID2D1EffectExtensions return (D2D1TransformMapper)GCHandle.FromIntPtr(handlePtr).Target!; } + /// + /// Gets the instance from a given object. + /// + /// The input instance. + /// The current cached source instance. + /// The index of the resource texture manager to retrieve. + /// The instance for . + public static D2D1ResourceTextureManager? GetResourceTextureManager( + this ref ID2D1Effect d2D1Effect, + D2D1ResourceTextureManager? source, + int index) + { + using ComPtr d2D1ResourceTextureManager = default; + + // Get the ID2D1ResourceTextureManager object from the effect + d2D1Effect.GetValue( + index: (uint)(D2D1PixelShaderEffectProperty.ResourceTextureManager0 + index), + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_IUNKNOWN, + data: (byte*)d2D1ResourceTextureManager.GetAddressOf(), + dataSize: (uint)sizeof(void*)).Assert(); + + // If there is no resource texture manager, just return null (this is the default state) + if (d2D1ResourceTextureManager.Get() is null) + { + return null; + } + + // Otherwise, the source must not be null and wrapping the same CCW + if (source is not null) + { + using ComPtr d2D1ResourceTextureManagerSource = default; + + source.GetD2D1ResourceTextureManager(d2D1ResourceTextureManagerSource.GetAddressOf()); + + // Check if the instances match, and return the managed wrapper we already have + if (d2D1ResourceTextureManager.IsSameInstance(in d2D1ResourceTextureManagerSource)) + { + return source; + } + } + + // There was no way to retrieve the correct managed wrapper + ThrowHelper.ThrowInvalidOperationException("Cannot retrieve a D2D1ResourceTextureManager instance wrapping a native object that was set externally."); + + return null; + } + /// /// Gets the property for a given object. /// diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index 01db5a66..a8c2afce 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -166,7 +166,10 @@ unsafe partial class PixelShaderEffect return; } - // Cache the last update values for the constant buffer, cache output and buffer precision properties + // Cache the last update values for the constant buffer, cache output, buffer precision properties, etc. + // Note: the resource texture managers are deliberately not read back, as the only supported way to set + // those is directly from the current effect instance. As such, they'd all either be the same instances + // that are already stored locally, or trying to retrieve them would just throw an exception. this.value = this.d2D1Effect.Get()->GetConstantBuffer(); this.transformMapper = this.d2D1Effect.Get()->GetTransformMapper(); this.cacheOutput = this.d2D1Effect.Get()->GetCachedProperty(); @@ -240,6 +243,15 @@ unsafe partial class PixelShaderEffect this.d2D1Effect.Get()->SetPrecisionProperty(this.d2D1BufferPrecision); } + // Set all available resource texture managers (only set those that are not null, as they're all null by default anyway) + for (int i = 0; i < 16; i++) + { + if (ResourceTextureManagers.Storage[i] is D2D1ResourceTextureManager resourceTextureManager) + { + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(this.d2D1Effect.Get(), resourceTextureManager, i); + } + } + // TODO: port base CanvasEffect::Realize logic // TODO: transfer properties (eg. D2D1ResourceTextureManager-s) diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs index 24e3f12d..b011115e 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs @@ -89,6 +89,49 @@ unsafe partial class PixelShaderEffect } } + /// + /// Gets the marshalled value for . + /// + /// The index of the source to get or set. + /// The marshalled value for . + private D2D1ResourceTextureManager? GetResourceTextureManager(int index) + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + D2D1ResourceTextureManager? resourceTextureManager = ResourceTextureManagers.Storage[index]; + + return this.d2D1Effect.Get() switch + { + not null => this.d2D1Effect.Get()->GetResourceTextureManager(resourceTextureManager, index), + _ => resourceTextureManager + }; + } + } + + /// + /// Sets the marshalled value for . + /// + /// The value to set for . + /// The index of the source to get or set. + private void SetResourceTextureManager(D2D1ResourceTextureManager value, int index) + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + if (this.d2D1Effect.Get() is not null) + { + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(this.d2D1Effect.Get(), value, index); + } + else + { + ResourceTextureManagers.Storage[index] = value; + } + } + } + /// /// Gets the marshalled value for . /// diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs new file mode 100644 index 00000000..fed84087 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs @@ -0,0 +1,165 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using ComputeSharp.D2D1.Helpers; +using ComputeSharp.D2D1.Interop; + +namespace ComputeSharp.D2D1.Uwp; + +/// +partial class PixelShaderEffect +{ + /// + /// Represents the collection of objects in a instance. + /// + public sealed class ResourceTextureManagerCollection + { + /// + /// The fixed buffer of instances. + /// + private FixedBuffer fixedBuffer; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The owning instance. + internal ResourceTextureManagerCollection(PixelShaderEffect owner) + { + Owner = owner; + } + + /// + /// The owning instance. + /// + internal PixelShaderEffect Owner { get; } + + /// + /// Gets a reference to the value containing the available -s. + /// + internal ref FixedBuffer Storage => ref this.fixedBuffer; + + /// + /// Gets or sets the object at a specified index. + /// + /// The index of the source to get or set. + /// The object at the specified index. + /// Thrown if the value is set to . + /// Thrown if is not a valid index for the current effect. + [DisallowNull] + public D2D1ResourceTextureManager? this[int index] + { + get => Owner.GetResourceTextureManager(index); + set => Owner.SetResourceTextureManager(value, index); + } + + /// + /// A fixed buffer type containing 16 fields. + /// + internal struct FixedBuffer + { + /// + /// The instance at index 0. + /// + public D2D1ResourceTextureManager? ResourceTextureManager0; + + /// + /// The instance at index 1. + /// + public D2D1ResourceTextureManager? ResourceTextureManager1; + + /// + /// The instance at index 2. + /// + public D2D1ResourceTextureManager? ResourceTextureManager2; + + /// + /// The instance at index 3. + /// + public D2D1ResourceTextureManager? ResourceTextureManager3; + + /// + /// The instance at index 4. + /// + public D2D1ResourceTextureManager? ResourceTextureManager4; + + /// + /// The instance at index 5. + /// + public D2D1ResourceTextureManager? ResourceTextureManager5; + + /// + /// The instance at index 6. + /// + public D2D1ResourceTextureManager? ResourceTextureManager6; + + /// + /// The instance at index 7. + /// + public D2D1ResourceTextureManager? ResourceTextureManager7; + + /// + /// The instance at index 8. + /// + public D2D1ResourceTextureManager? ResourceTextureManager8; + + /// + /// The instance at index 9. + /// + public D2D1ResourceTextureManager? ResourceTextureManager9; + + /// + /// The instance at index 10. + /// + public D2D1ResourceTextureManager? ResourceTextureManager10; + + /// + /// The instance at index 11. + /// + public D2D1ResourceTextureManager? ResourceTextureManager11; + + /// + /// The instance at index 12. + /// + public D2D1ResourceTextureManager? ResourceTextureManager12; + + /// + /// The instance at index 13. + /// + public D2D1ResourceTextureManager? ResourceTextureManager13; + + /// + /// The instance at index 14. + /// + public D2D1ResourceTextureManager? ResourceTextureManager14; + + /// + /// The instance at index 15. + /// + public D2D1ResourceTextureManager? ResourceTextureManager15; + + /// + /// Gets a reference to the value at a given index. + /// + /// The index of the value to get a reference to. + /// A reference to the value at a given index. + /// Thrown if is not a valid index for the current effect. + [UnscopedRef] + public ref D2D1ResourceTextureManager? this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if ((uint)index >= 16) + { + ThrowHelper.ThrowArgumentOutOfRangeException(nameof(index), "The index must be in the [0, 15] range."); + } + + ref D2D1ResourceTextureManager? r0 = ref Unsafe.As(ref this); + ref D2D1ResourceTextureManager? r1 = ref Unsafe.Add(ref r0, index); + + return ref r1; + } + } + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs index 2d5db8e2..15d321de 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs @@ -89,38 +89,4 @@ partial class PixelShaderEffect set { } } } - - /// - /// Represents the collection of objects in a instance. - /// - public sealed class ResourceTextureManagerCollection - { - /// - /// Creates a new instance with the specified parameters. - /// - /// The owning instance. - internal ResourceTextureManagerCollection(PixelShaderEffect owner) - { - Owner = owner; - } - - /// - /// The owning instance. - /// - internal PixelShaderEffect Owner { get; } - - /// - /// Gets or sets the object at a specified index. - /// - /// The index of the source to get or set. - /// The object at the specified index. - /// Thrown if the value is set to . - /// Thrown if is not a valid index for the current effect. - [DisallowNull] - public D2D1ResourceTextureManager this[int index] - { - get => null!; - set { } - } - } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Helpers/Rectangle64.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Helpers/Rectangle64.cs index 1a20b3db..c72945b1 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Helpers/Rectangle64.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Helpers/Rectangle64.cs @@ -95,10 +95,10 @@ internal struct Rectangle64 /// The input instance to compute the union with. public void Union(Rectangle64 rectangle) { - long left = Math.Min(this.Left, rectangle.Left); - long top = Math.Min(this.Top, rectangle.Top); - long right = Math.Max(this.Right, rectangle.Right); - long bottom = Math.Max(this.Bottom, rectangle.Bottom); + long left = Math.Min(Left, rectangle.Left); + long top = Math.Min(Top, rectangle.Top); + long right = Math.Max(Right, rectangle.Right); + long bottom = Math.Max(Bottom, rectangle.Bottom); this.x = left; this.y = top; @@ -114,8 +114,8 @@ internal struct Rectangle64 { long left = Math.Max(this.x, rectangle.x); long top = Math.Max(this.y, rectangle.y); - long right = Math.Min(this.Right, rectangle.Right); - long bottom = Math.Min(this.Bottom, rectangle.Bottom); + long right = Math.Min(Right, rectangle.Right); + long bottom = Math.Min(Bottom, rectangle.Bottom); this.x = left; this.y = top; From 7761d0bbd8eba349fb0f11ca31e04fcd2fe670e7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 30 Nov 2022 03:10:24 +0100 Subject: [PATCH 29/59] Improve consistency in interop API parameters ordering --- .../PixelShaderEffect{T}.ICanvasImageInterop.cs | 2 +- .../PixelShaderEffect{T}.Properties.Interop.cs | 2 +- .../Shaders/Interop/D2D1PixelShader.cs | 4 ++-- .../Shaders/Interop/D2D1PixelShaderEffect.cs | 4 ++-- .../D2D1PixelShaderEffectTests.cs | 2 +- .../D2D1PixelShaderTests.cs | 2 +- .../D2D1ResourceTextureManagerTests.cs | 16 ++++++++-------- .../D2D1TransformMapperTests.cs | 2 +- .../Effects/BokehBlurEffect.cs | 6 +++--- .../Helpers/D2D1TestRunner.cs | 4 ++-- 10 files changed, 22 insertions(+), 22 deletions(-) diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index a8c2afce..210da512 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -223,7 +223,7 @@ unsafe partial class PixelShaderEffect } // Set the constant buffer for the effect - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(this.value, this.d2D1Effect.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(this.d2D1Effect.Get(), in this.value); // If there is a transform mapper, set it in the effect if (this.transformMapper is not null) diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs index b011115e..eb9d81d0 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs @@ -40,7 +40,7 @@ unsafe partial class PixelShaderEffect // If the effect is realized, set the property on the underlying ID2D1Effect object if (this.d2D1Effect.Get() is not null) { - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in value, this.d2D1Effect.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(this.d2D1Effect.Get(), in value); } else { diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs index 4203a859..e49184e8 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs @@ -426,11 +426,11 @@ public static class D2D1PixelShader /// Sets the constant buffer from an input D2D1 pixel shader, by calling ID2D1DrawInfo::SetPixelShaderConstantBuffer. /// /// The type of D2D1 pixel shader to set the constant buffer for. - /// The input D2D1 pixel shader to set the contant buffer for. /// A pointer to the ID2D1DrawInfo instance to use. + /// The input D2D1 pixel shader to set the contant buffer for. /// Thrown if is . /// For more info, see . - public static unsafe void SetConstantBufferForD2D1DrawInfo(in T shader, void* d2D1DrawInfo) + public static unsafe void SetConstantBufferForD2D1DrawInfo(void* d2D1DrawInfo, in T shader) where T : unmanaged, ID2D1PixelShader { if (d2D1DrawInfo is null) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs index b0b63c86..3ce44ca3 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs @@ -497,11 +497,11 @@ public static unsafe class D2D1PixelShaderEffect /// Sets the constant buffer from an input D2D1 effect, by calling ID2D1Effect::SetValue. /// /// The type of D2D1 pixel shader to set the constant buffer for. - /// The input D2D1 pixel shader to set the contant buffer for. /// A pointer to the ID2D1Effect instance to use. + /// The input D2D1 pixel shader to set the contant buffer for. /// Thrown if is . /// For more info, see . - public static void SetConstantBufferForD2D1Effect(in T shader, void* d2D1Effect) + public static void SetConstantBufferForD2D1Effect(void* d2D1Effect, in T shader) where T : unmanaged, ID2D1PixelShader { if (d2D1Effect is null) diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs index f6782eba..ac7a715f 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs @@ -47,7 +47,7 @@ public partial class D2D1PixelShaderEffectTests [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)] public unsafe void SetConstantBufferForD2D1Effect_NullD2D1Effect() { - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(default, null); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(null, default); } [TestMethod] diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs index 6c264798..abbee5eb 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs @@ -630,6 +630,6 @@ public partial class D2D1PixelShaderTests [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)] public unsafe void SetConstantBufferForD2D1DrawInfo_NullD2D1DrawInfo() { - D2D1PixelShader.SetConstantBufferForD2D1DrawInfo(default, null); + D2D1PixelShader.SetConstantBufferForD2D1DrawInfo(null, default); } } \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1ResourceTextureManagerTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1ResourceTextureManagerTests.cs index 61dd5d58..47f3c49b 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1ResourceTextureManagerTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1ResourceTextureManagerTests.cs @@ -198,7 +198,7 @@ public partial class D2D1ResourceTextureManagerTests D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(default(IndexFrom2DResourceTextureShader), d2D1Effect.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), default(IndexFrom2DResourceTextureShader)); using ComPtr resourceTextureManager = default; @@ -257,7 +257,7 @@ public partial class D2D1ResourceTextureManagerTests D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(default(IndexFrom2DResourceTextureShader), d2D1Effect.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), default(IndexFrom2DResourceTextureShader)); using ComPtr resourceTextureManager = default; @@ -321,7 +321,7 @@ public partial class D2D1ResourceTextureManagerTests D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(default(IndexFrom2DResourceTextureShader), d2D1Effect.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), default(IndexFrom2DResourceTextureShader)); string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!; string expectedPath = Path.Combine(assemblyPath, "Assets", "Landscape.png"); @@ -498,7 +498,7 @@ public partial class D2D1ResourceTextureManagerTests IndexFrom3DResourceTextureShader shader = new(expected.Height / 4); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in shader, d2D1Effect.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader); using ComPtr resourceTextureManager = default; @@ -575,7 +575,7 @@ public partial class D2D1ResourceTextureManagerTests CopyFromResourceTexture1DShader shader = new(width); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in shader, d2D1Effect.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader); byte[] texture = new byte[width]; @@ -663,7 +663,7 @@ public partial class D2D1ResourceTextureManagerTests CopyFromResourceTexture2DShader shader = new(width, height); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in shader, d2D1Effect.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader); byte[] texture = new byte[width * height]; @@ -766,7 +766,7 @@ public partial class D2D1ResourceTextureManagerTests CopyFromResourceTexture3DShader shader = new(width, height, depth); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in shader, d2D1Effect.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader); byte[] texture = new byte[width * height * depth]; @@ -860,7 +860,7 @@ public partial class D2D1ResourceTextureManagerTests D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(default(NullResourceTextureShader), d2D1Effect.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), default(NullResourceTextureShader)); using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), 128, 128); diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1TransformMapperTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1TransformMapperTests.cs index ee0e42a4..b7be7722 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1TransformMapperTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1TransformMapperTests.cs @@ -158,7 +158,7 @@ public partial class D2D1TransformMapperTests D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new ShaderWithDispatchArea(111, 222), d2D1Effect.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), new ShaderWithDispatchArea(111, 222)); DispatchAreaTransformMapper transformMapper = new() { ExpectedWidth = 111, ExpectedHeight = 222 }; diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs index c3b1d893..9fcd8452 100644 --- a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs +++ b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs @@ -425,9 +425,9 @@ public sealed partial class BokehBlurEffect // Set the constant buffers for (int i = 0; i < numberOfComponents; i++) { - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new VerticalConvolution.Shader((int)kernelSize), verticalConvolutionEffectsForReals[i].Get()); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new VerticalConvolution.Shader((int)kernelSize), verticalConvolutionEffectsForImaginaries[i].Get()); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new HorizontalConvolutionAndAccumulatePartials.Shader((int)kernelSize, this.kernelParameters[i].Z, this.kernelParameters[i].W), horizontalConvolutionEffects[i].Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(verticalConvolutionEffectsForReals[i].Get(), new VerticalConvolution.Shader((int)kernelSize)); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(verticalConvolutionEffectsForImaginaries[i].Get(), new VerticalConvolution.Shader((int)kernelSize)); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(horizontalConvolutionEffects[i].Get(), new HorizontalConvolutionAndAccumulatePartials.Shader((int)kernelSize, this.kernelParameters[i].Z, this.kernelParameters[i].W)); } // Build the effect graph: diff --git a/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1TestRunner.cs b/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1TestRunner.cs index df176f89..2e7de96e 100644 --- a/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1TestRunner.cs +++ b/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1TestRunner.cs @@ -124,7 +124,7 @@ internal static class D2D1TestRunner D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in shader, d2D1Effect.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader); if (transformMapper is not null) { @@ -173,7 +173,7 @@ internal static class D2D1TestRunner D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in shader, d2D1Effect.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader); if (transformMapper is not null) { From e2550a2b548a50a433a94f641f39de95269b52c8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 2 Dec 2022 15:12:54 +0100 Subject: [PATCH 30/59] Add fixed buffer type for SourceCollection --- ...erties.ResourceTextureManagerCollection.cs | 20 +-- ...PixelShaderEffect{T}.Properties.Sources.cs | 163 ++++++++++++++++++ .../PixelShaderEffect{T}.Properties.cs | 33 ---- 3 files changed, 173 insertions(+), 43 deletions(-) create mode 100644 src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs index fed84087..65922e42 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs @@ -28,16 +28,6 @@ partial class PixelShaderEffect Owner = owner; } - /// - /// The owning instance. - /// - internal PixelShaderEffect Owner { get; } - - /// - /// Gets a reference to the value containing the available -s. - /// - internal ref FixedBuffer Storage => ref this.fixedBuffer; - /// /// Gets or sets the object at a specified index. /// @@ -52,6 +42,16 @@ partial class PixelShaderEffect set => Owner.SetResourceTextureManager(value, index); } + /// + /// The owning instance. + /// + internal PixelShaderEffect Owner { get; } + + /// + /// Gets a reference to the value containing the available -s. + /// + internal ref FixedBuffer Storage => ref this.fixedBuffer; + /// /// A fixed buffer type containing 16 fields. /// diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs new file mode 100644 index 00000000..c1d9654a --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs @@ -0,0 +1,163 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using ComputeSharp.D2D1.Helpers; +using Windows.Graphics.Effects; + +namespace ComputeSharp.D2D1.Uwp; + +/// +partial class PixelShaderEffect +{ + /// + /// Represents the collection of sources in a instance. + /// + public sealed class SourceCollection + { + /// + /// The fixed buffer of instances. + /// + private FixedBuffer fixedBuffer; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The owning instance. + internal SourceCollection(PixelShaderEffect owner) + { + Owner = owner; + } + + /// + /// Gets or sets the source at a specified index. + /// + /// The index of the source to get or set. + /// The source at the specified index. + /// Thrown if is not a valid index for the current effect. + public IGraphicsEffectSource this[int index] + { + get => null!; + set { } + } + + /// + /// The owning instance. + /// + internal PixelShaderEffect Owner { get; } + + /// + /// Gets a reference to the value containing the available -s. + /// + internal ref FixedBuffer Storage => ref this.fixedBuffer; + + /// + /// A fixed buffer type containing 16 fields. + /// + internal struct FixedBuffer + { + /// + /// The instance at index 0. + /// + public IGraphicsEffectSource? Source0; + + /// + /// The instance at index 1. + /// + public IGraphicsEffectSource? Source1; + + /// + /// The instance at index 2. + /// + public IGraphicsEffectSource? Source2; + + /// + /// The instance at index 3. + /// + public IGraphicsEffectSource? Source3; + + /// + /// The instance at index 4. + /// + public IGraphicsEffectSource? Source4; + + /// + /// The instance at index 5. + /// + public IGraphicsEffectSource? Source5; + + /// + /// The instance at index 6. + /// + public IGraphicsEffectSource? Source6; + + /// + /// The instance at index 7. + /// + public IGraphicsEffectSource? Source7; + + /// + /// The instance at index 8. + /// + public IGraphicsEffectSource? Source8; + + /// + /// The instance at index 9. + /// + public IGraphicsEffectSource? Source9; + + /// + /// The instance at index 10. + /// + public IGraphicsEffectSource? Source10; + + /// + /// The instance at index 11. + /// + public IGraphicsEffectSource? Source11; + + /// + /// The instance at index 12. + /// + public IGraphicsEffectSource? Source12; + + /// + /// The instance at index 13. + /// + public IGraphicsEffectSource? Source13; + + /// + /// The instance at index 14. + /// + public IGraphicsEffectSource? Source14; + + /// + /// The instance at index 15. + /// + public IGraphicsEffectSource? Source15; + + /// + /// Gets a reference to the value at a given index. + /// + /// The index of the value to get a reference to. + /// A reference to the value at a given index. + /// Thrown if is not a valid index for the current effect. + [UnscopedRef] + public ref IGraphicsEffectSource? this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if ((uint)index >= 16) + { + ThrowHelper.ThrowArgumentOutOfRangeException(nameof(index), "The index must be in the [0, 15] range."); + } + + ref IGraphicsEffectSource? r0 = ref Unsafe.As(ref this); + ref IGraphicsEffectSource? r1 = ref Unsafe.Add(ref r0, index); + + return ref r1; + } + } + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs index 15d321de..74954eda 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs @@ -2,7 +2,6 @@ using System; using System.Diagnostics.CodeAnalysis; using ComputeSharp.D2D1.Interop; using Microsoft.Graphics.Canvas; -using Windows.Graphics.Effects; namespace ComputeSharp.D2D1.Uwp; @@ -57,36 +56,4 @@ partial class PixelShaderEffect /// Gets the object associated with the current instance. /// public ResourceTextureManagerCollection ResourceTextureManagers { get; } - - /// - /// Represents the collection of sources in a instance. - /// - public sealed class SourceCollection - { - /// - /// Creates a new instance with the specified parameters. - /// - /// The owning instance. - internal SourceCollection(PixelShaderEffect owner) - { - Owner = owner; - } - - /// - /// The owning instance. - /// - internal PixelShaderEffect Owner { get; } - - /// - /// Gets or sets the source at a specified index. - /// - /// The index of the source to get or set. - /// The source at the specified index. - /// Thrown if is not a valid index for the current effect. - public IGraphicsEffectSource this[int index] - { - get => null!; - set { } - } - } } \ No newline at end of file From d6cd052791a687390737eb626c8d99d3a7dee8a0 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 2 Dec 2022 16:48:55 +0100 Subject: [PATCH 31/59] Refactor ComPtr.IsSameInstance extension --- .../Extensions/ComPtrExtensions.cs | 41 ------------------ .../Extensions/IUnknownExtensions.cs | 43 +++++++++++++++++++ ...ixelShaderEffect{T}.ICanvasImageInterop.cs | 2 +- 3 files changed, 44 insertions(+), 42 deletions(-) delete mode 100644 src/ComputeSharp.D2D1.Uwp/Extensions/ComPtrExtensions.cs create mode 100644 src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/ComPtrExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/ComPtrExtensions.cs deleted file mode 100644 index 8e51d066..00000000 --- a/src/ComputeSharp.D2D1.Uwp/Extensions/ComPtrExtensions.cs +++ /dev/null @@ -1,41 +0,0 @@ -using ComputeSharp.D2D1.Extensions; -using TerraFX.Interop.Windows; - -namespace ComputeSharp.D2D1.Uwp.Extensions; - -/// -/// Helper methods for working with the type. -/// -internal static class ComPtrExtensions -{ - /// - /// Checks whether two values have the same underlying COM object. - /// - /// The type of the first value to check. - /// The type of the second value to check. - /// The first object to compare. - /// The second object to compare. - /// Whether and point to the same COM object. - public static unsafe bool IsSameInstance(this in ComPtr left, in ComPtr right) - where T : unmanaged - where U : unmanaged - { - if (left.Get() == right.Get()) - { - return true; - } - - if (left.Get() is null || right.Get() is null) - { - return false; - } - - using ComPtr leftUnknown = default; - using ComPtr rightUnknown = default; - - left.CopyTo(leftUnknown.GetAddressOf()).Assert(); - right.CopyTo(rightUnknown.GetAddressOf()).Assert(); - - return leftUnknown.Get() == rightUnknown.Get(); - } -} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs new file mode 100644 index 00000000..75fcb82d --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs @@ -0,0 +1,43 @@ +using System.Runtime.CompilerServices; +using ComputeSharp.D2D1.Extensions; +using TerraFX.Interop.Windows; +using Win32 = TerraFX.Interop.Windows.Windows; + +namespace ComputeSharp.D2D1.Uwp.Extensions; + +/// +/// Helper methods for working with the type. +/// +internal static class IUnknownExtensions +{ + /// + /// Checks whether two values have the same underlying COM object. + /// + /// The type of the first value to check. + /// The type of the second value to check. + /// The first object to compare. + /// The second object to compare. + /// Whether and point to the same COM object. + public static unsafe bool IsSameInstance(this ref T left, U* right) + where T : unmanaged // IUnknown + where U : unmanaged // IUnknown + { + if (Unsafe.AreSame(ref left, ref *(T*)right)) + { + return true; + } + + if (Unsafe.IsNullRef(ref left) || right is null) + { + return false; + } + + using ComPtr leftUnknown = default; + using ComPtr rightUnknown = default; + + ((IUnknown*)Unsafe.AsPointer(ref left))->QueryInterface(Win32.__uuidof(), (void**)leftUnknown.GetAddressOf()).Assert(); + ((IUnknown*)right)->QueryInterface(Win32.__uuidof(), (void**)rightUnknown.GetAddressOf()).Assert(); + + return leftUnknown.Get() == rightUnknown.Get(); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index 210da512..e227672a 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -107,7 +107,7 @@ unsafe partial class PixelShaderEffect // Check that the input D2D device is the same instance as the current realization device, if any. // If not and the effect has already been realized, unrealize it and store the new device to use. - if (!d2D1Device1.IsSameInstance(in this.d2D1RealizationDevice)) + if (!d2D1Device1.Get()->IsSameInstance(this.d2D1RealizationDevice.Get())) { Unrealize(); From 6628f4d2052e67da0a6664f965be90f2448c9d93 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 2 Dec 2022 17:57:16 +0100 Subject: [PATCH 32/59] Implement PixelShaderEffect.GetSource(int) --- .../Extensions/ICanvasDeviceExtensions.cs | 2 +- .../Extensions/ID2D1EffectExtensions.cs | 48 ++++- .../Extensions/IUnknownExtensions.cs | 4 +- ...PixelShaderEffect{T}.Properties.Interop.cs | 22 ++ ...PixelShaderEffect{T}.Properties.Sources.cs | 203 ++++++++++++++---- .../DirectX/um/d2d1_1/ID2D1Effect.cs | 7 + 6 files changed, 244 insertions(+), 42 deletions(-) diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/ICanvasDeviceExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/ICanvasDeviceExtensions.cs index 9cdc9de8..d73d7534 100644 --- a/src/ComputeSharp.D2D1.Uwp/Extensions/ICanvasDeviceExtensions.cs +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/ICanvasDeviceExtensions.cs @@ -24,7 +24,7 @@ internal static unsafe class ICanvasDeviceExtensions // Get the ICanvasResourceWrapperNative wrapper around the input device canvasDevice.QueryInterface( riid: Win32.__uuidof(), - ppvObject: (void**)canvasDeviceResourceWrapperNative.GetAddressOf()).Assert(); + ppvObject: canvasDeviceResourceWrapperNative.GetVoidAddressOf()).Assert(); // Get the underlying ID2D1Device1 instance in use HRESULT hresult = canvasDeviceResourceWrapperNative.Get()->GetNativeResource( diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs index c36f62bb..736d3fb0 100644 --- a/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs @@ -2,6 +2,7 @@ using System; using System.Buffers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using ABI.Microsoft.Graphics.Canvas; using ComputeSharp.D2D1.Extensions; using ComputeSharp.D2D1.Helpers; using ComputeSharp.D2D1.Interop; @@ -9,6 +10,7 @@ using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; +using Windows.Graphics.Effects; #pragma warning disable CS0618 @@ -86,6 +88,50 @@ internal static unsafe class ID2D1EffectExtensions return (D2D1TransformMapper)GCHandle.FromIntPtr(handlePtr).Target!; } + /// + /// Gets the source from a given object, at a specified index. + /// + /// The type of shader being used. + /// The input instance. + /// The realization device currently in use. + /// The input object for the target index. + /// The index for the source to retrieve. + /// The source from a given object, at a specified index. + public static IGraphicsEffectSource? GetSource( + this ref ID2D1Effect d2D1Effect, + ICanvasDevice* canvasDevice, + ref PixelShaderEffect.SourceCollection.SourceReference source, + int index) + where T : unmanaged, ID2D1PixelShader + { + using ComPtr d2D1Image = default; + + // Get the ID2D1Image input from the effect + d2D1Effect.GetInput( + index: (uint)index, + input: d2D1Image.GetAddressOf()); + + // Check whether the input had a DPI compensation effect added to it, and skip it if so + if (source.HasDpiCompensationEffect) + { + // Since a realized effect is the only source of authority for the effect state, we also + // need to check that the actual source is in fact the same that was previous set by the + // managed wrapper. If it is, we get the input and return that (ie. the underlying image). + // If not, we just return it directly and reset the locally stored DPI compensation effect. + if (d2D1Image.Get()->IsSameInstance(source.GetDpiCompensationEffect())) + { + source.GetDpiCompensationEffect()->GetInput(0, d2D1Image.ReleaseAndGetAddressOf()); + } + else + { + source.SetDpiCompensationEffect(null); + } + } + + // Get or create a wrapper for the input image + return source.GetOrCreateWrapper(null, d2D1Image.Get()); + } + /// /// Gets the instance from a given object. /// @@ -121,7 +167,7 @@ internal static unsafe class ID2D1EffectExtensions source.GetD2D1ResourceTextureManager(d2D1ResourceTextureManagerSource.GetAddressOf()); // Check if the instances match, and return the managed wrapper we already have - if (d2D1ResourceTextureManager.IsSameInstance(in d2D1ResourceTextureManagerSource)) + if (d2D1ResourceTextureManager.Get()->IsSameInstance(d2D1ResourceTextureManagerSource.Get())) { return source; } diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs index 75fcb82d..8b1e1b0c 100644 --- a/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs @@ -35,8 +35,8 @@ internal static class IUnknownExtensions using ComPtr leftUnknown = default; using ComPtr rightUnknown = default; - ((IUnknown*)Unsafe.AsPointer(ref left))->QueryInterface(Win32.__uuidof(), (void**)leftUnknown.GetAddressOf()).Assert(); - ((IUnknown*)right)->QueryInterface(Win32.__uuidof(), (void**)rightUnknown.GetAddressOf()).Assert(); + ((IUnknown*)Unsafe.AsPointer(ref left))->QueryInterface(Win32.__uuidof(), leftUnknown.GetVoidAddressOf()).Assert(); + ((IUnknown*)right)->QueryInterface(Win32.__uuidof(), rightUnknown.GetVoidAddressOf()).Assert(); return leftUnknown.Get() == rightUnknown.Get(); } diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs index eb9d81d0..5e3b1847 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs @@ -3,6 +3,7 @@ using ComputeSharp.D2D1.Uwp.Extensions; using ComputeSharp.Interop; using Microsoft.Graphics.Canvas; using TerraFX.Interop.DirectX; +using Windows.Graphics.Effects; namespace ComputeSharp.D2D1.Uwp; @@ -89,6 +90,27 @@ unsafe partial class PixelShaderEffect } } + /// + /// Gets the marshalled value for . + /// + /// The index of the source to get or set. + /// The marshalled value for . + private IGraphicsEffectSource? GetSource(int index) + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + ref SourceCollection.SourceReference source = ref Sources.Storage[index]; + + return this.d2D1Effect.Get() switch + { + not null => this.d2D1Effect.Get()->GetSource(this.canvasDevice.Get(), ref source, index), + _ => source.GetWrapper() + }; + } + } + /// /// Gets the marshalled value for . /// diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs index c1d9654a..938dced2 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs @@ -1,7 +1,11 @@ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; +using ABI.Microsoft.Graphics.Canvas; using ComputeSharp.D2D1.Helpers; +using ComputeSharp.D2D1.Uwp.Extensions; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; using Windows.Graphics.Effects; namespace ComputeSharp.D2D1.Uwp; @@ -56,93 +60,93 @@ partial class PixelShaderEffect internal struct FixedBuffer { /// - /// The instance at index 0. + /// The instance at index 0. /// - public IGraphicsEffectSource? Source0; + public SourceReference Source0; /// - /// The instance at index 1. + /// The instance at index 1. /// - public IGraphicsEffectSource? Source1; + public SourceReference Source1; /// - /// The instance at index 2. + /// The instance at index 2. /// - public IGraphicsEffectSource? Source2; + public SourceReference Source2; /// - /// The instance at index 3. + /// The instance at index 3. /// - public IGraphicsEffectSource? Source3; + public SourceReference Source3; /// - /// The instance at index 4. + /// The instance at index 4. /// - public IGraphicsEffectSource? Source4; + public SourceReference Source4; /// - /// The instance at index 5. + /// The instance at index 5. /// - public IGraphicsEffectSource? Source5; + public SourceReference Source5; /// - /// The instance at index 6. + /// The instance at index 6. /// - public IGraphicsEffectSource? Source6; + public SourceReference Source6; /// - /// The instance at index 7. + /// The instance at index 7. /// - public IGraphicsEffectSource? Source7; + public SourceReference Source7; /// - /// The instance at index 8. + /// The instance at index 8. /// - public IGraphicsEffectSource? Source8; + public SourceReference Source8; /// - /// The instance at index 9. + /// The instance at index 9. /// - public IGraphicsEffectSource? Source9; + public SourceReference Source9; /// - /// The instance at index 10. + /// The instance at index 10. /// - public IGraphicsEffectSource? Source10; + public SourceReference Source10; /// - /// The instance at index 11. + /// The instance at index 11. /// - public IGraphicsEffectSource? Source11; + public SourceReference Source11; /// - /// The instance at index 12. + /// The instance at index 12. /// - public IGraphicsEffectSource? Source12; + public SourceReference Source12; /// - /// The instance at index 13. + /// The instance at index 13. /// - public IGraphicsEffectSource? Source13; + public SourceReference Source13; /// - /// The instance at index 14. + /// The instance at index 14. /// - public IGraphicsEffectSource? Source14; + public SourceReference Source14; /// - /// The instance at index 15. + /// The instance at index 15. /// - public IGraphicsEffectSource? Source15; + public SourceReference Source15; /// - /// Gets a reference to the value at a given index. + /// Gets a reference to the value at a given index. /// - /// The index of the value to get a reference to. - /// A reference to the value at a given index. + /// The index of the value to get a reference to. + /// A reference to the value at a given index. /// Thrown if is not a valid index for the current effect. [UnscopedRef] - public ref IGraphicsEffectSource? this[int index] + public ref SourceReference this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get @@ -152,12 +156,135 @@ partial class PixelShaderEffect ThrowHelper.ThrowArgumentOutOfRangeException(nameof(index), "The index must be in the [0, 15] range."); } - ref IGraphicsEffectSource? r0 = ref Unsafe.As(ref this); - ref IGraphicsEffectSource? r1 = ref Unsafe.Add(ref r0, index); + ref SourceReference r0 = ref Unsafe.As(ref this); + ref SourceReference r1 = ref Unsafe.Add(ref r0, index); return ref r1; } } } + + /// + /// A wrapper type for an input and its underlying native D2D images. + /// + /// + /// + /// This type is meant to support these two common operations: + /// + /// Look up a D2D resource from a property of some other D2D interface. + /// Get a managed wrapper from a D2D interface. + /// + /// With this, the generated D2D objects can be associated with each original managed wrapper. Similarly, + /// when the other way around is used, this type can also store the generated wrapper for future use. + /// + /// + /// This gives the following improvements: + /// + /// Improved performance for the common case of repeated calls using the same D2D instance. + /// Maintaining a reference to the wrapper avoids it being repeatedly released and recreated. + /// + /// + /// + /// Just like with all other members of an effect, values in this object are considered authoritative when the + /// effect is not realized, otherwise they just act as a cache to speedup the reverse managed wrapper lookups. + /// + /// + /// For realized effects, tracks both the resource and its + /// wrapper (and optional being the DPI compensation effect, + /// if one is needed. For unrealized effects, the resource is and only the wrapper part is used. + /// + /// + internal unsafe struct SourceReference + { + /// + /// The produced by calling + /// on the input managed wrapper used as source for the effect (ie. ). + /// + private ComPtr d2D1ImageSource; + + /// + /// The for DPI compensation wrapping , if needed. + /// + private ComPtr d2D1EffectDpiCompensation; + + /// + /// The instance being a managed wrapper for the current effect input. + /// + private IGraphicsEffectSource? graphicsEffectSourceWrapper; + + /// + /// Gets whether or not this source ference has a DPI compensation effect. + /// + public readonly bool HasDpiCompensationEffect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => this.d2D1EffectDpiCompensation.Get() is not null; + } + + /// + /// Gets the object for the DPI compensation effect used, if any. + /// + /// The object for the DPI compensation effect used, if any. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly ID2D1Effect* GetDpiCompensationEffect() + { + return this.d2D1EffectDpiCompensation.Get(); + } + + /// + /// Sets the DPI compensation effet being used, + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetDpiCompensationEffect(ID2D1Effect* d2D1Effect) + { + _ = this.d2D1EffectDpiCompensation.Reset(); + + if (d2D1Effect is not null) + { + this.d2D1EffectDpiCompensation = new ComPtr(d2D1Effect); + } + } + + /// + /// Gets the instance being a managed wrapper for the current effect input. + /// + /// The instance being a managed wrapper for the current effect input. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly IGraphicsEffectSource? GetWrapper() + { + return this.graphicsEffectSourceWrapper; + } + + /// + /// Gets or creates an wrapper for a given object. + /// + /// The input object the source effect is realized on. + /// The input object to get or create a wrapper for. + /// An wrapper for a given object. + public IGraphicsEffectSource? GetOrCreateWrapper(ICanvasDevice* canvasDevice, ID2D1Image* d2D1Image) + { + // Check if there already is a matching managed wrapper for the input image + if (!this.d2D1ImageSource.Get()->IsSameInstance(d2D1Image)) + { + // If that's not the case, create a new wrapper if the input image is not null + if (d2D1Image is not null) + { + // m_wrapper = ResourceManager::GetOrCreate(device, resource); + throw new NotImplementedException(); + } + else + { + _ = this.d2D1ImageSource.Reset(); + } + + _ = this.d2D1ImageSource.Reset(); + + this.d2D1ImageSource = new ComPtr(d2D1Image); + } + + return this.graphicsEffectSourceWrapper; + } + } } } \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Effect.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Effect.cs index 1d5dcb4a..43851234 100644 --- a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Effect.cs +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Effect.cs @@ -32,4 +32,11 @@ internal unsafe partial struct ID2D1Effect { return ((delegate* unmanaged[Stdcall])(lpVtbl[11]))((ID2D1Effect*)Unsafe.AsPointer(ref this), index, type, data, dataSize); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(16)] + public void GetInput([NativeTypeName("UINT32")] uint index, ID2D1Image** input) + { + ((delegate* unmanaged[Stdcall])(lpVtbl[16]))((ID2D1Effect*)Unsafe.AsPointer(ref this), index, input); + } } \ No newline at end of file From a91ed7b70d1e02fafd4e7be11003942b965716c6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 3 Dec 2022 03:25:49 +0100 Subject: [PATCH 33/59] Implement PixelShaderEffect.SetSource --- .../ICanvasImageInterop.cs | 90 ++++--- .../Buffers/GraphicsEffectSourceBuffer.cs | 117 ++++++++ .../Buffers/ResourceTextureManagerBuffer.cs | 117 ++++++++ .../Buffers/SourceReference.cs | 154 +++++++++++ .../Extensions/ID2D1EffectExtensions.cs | 108 +++++++- ...PixelShaderEffect{T}.Properties.Interop.cs | 44 ++- ...erties.ResourceTextureManagerCollection.cs | 119 +------- ...PixelShaderEffect{T}.Properties.Sources.cs | 253 +----------------- .../DirectX/um/d2d1_1/ID2D1Effect.cs | 7 + 9 files changed, 612 insertions(+), 397 deletions(-) create mode 100644 src/ComputeSharp.D2D1.Uwp/Buffers/GraphicsEffectSourceBuffer.cs create mode 100644 src/ComputeSharp.D2D1.Uwp/Buffers/ResourceTextureManagerBuffer.cs create mode 100644 src/ComputeSharp.D2D1.Uwp/Buffers/SourceReference.cs diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs index 292d499c..3d6c8e3e 100644 --- a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -18,6 +19,63 @@ internal unsafe struct ICanvasImageInterop { public void** lpVtbl; + /// + /// Gets the device that the effect is currently realized on, if any. + /// + /// The resulting device, if available ((as a marshalled )). + /// The for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(3)] + public HRESULT GetDevice(ICanvasDevice** device) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[3])((ICanvasImageInterop*)Unsafe.AsPointer(ref this), device); + } + + /// + /// Gets an from an instance. + /// + /// The input canvas device (as a marshalled ). + /// + /// The device context in use. This value is is optional (but recommended), except when the + /// flag is specified. This is because + /// not all callers of have easy access to a context. It is always + /// possible to get a resource creation context from the device, but the context is only + /// actually necessary if a new effect realization needs to be created, so it is more efficient + /// to have the implementation do this lookup only if/when it turns out to be needed. + /// + /// The flags to use to get the image. + /// + /// The DPI of the target device context. This is used to determine when a D2D1DpiCompensation + /// effect needs to be inserted. Behavior of this parameter can be overridden by the flag values + /// , + /// or + /// + /// + /// The DPI of a source bitmap, or zero if the image does not have a fixed DPI. A D2D1DpiCompensation effect + /// will be inserted if and are different (flags permitting). + /// + /// The resulting for the effect. + /// The for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(4)] + public HRESULT GetD2DImage( + ICanvasDevice* device, + ID2D1DeviceContext* deviceContext, + GetD2DImageFlags flags, + float targetDpi, + float* realizeDpi, + ID2D1Image** ppImage) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[4])( + (ICanvasImageInterop*)Unsafe.AsPointer(ref this), + device, + deviceContext, + flags, + targetDpi, + realizeDpi, + ppImage); + } + /// /// The implementation of . /// @@ -26,40 +84,12 @@ internal unsafe struct ICanvasImageInterop [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface Interface { - /// - /// Gets the device that the effect is currently realized on, if any. - /// - /// The resulting device, if available ((as a marshalled )). - /// The for the operation. + /// [PreserveSig] [return: NativeTypeName("HRESULT")] int GetDevice(ICanvasDevice** device); - /// - /// Gets an from an instance. - /// - /// The input canvas device (as a marshalled ). - /// - /// The device context in use. This value is is optional (but recommended), except when the - /// flag is specified. This is because - /// not all callers of have easy access to a context. It is always - /// possible to get a resource creation context from the device, but the context is only - /// actually necessary if a new effect realization needs to be created, so it is more efficient - /// to have the implementation do this lookup only if/when it turns out to be needed. - /// - /// The flags to use to get the image. - /// - /// The DPI of the target device context. This is used to determine when a D2D1DpiCompensation - /// effect needs to be inserted. Behavior of this parameter can be overridden by the flag values - /// , - /// or - /// - /// - /// The DPI of a source bitmap, or zero if the image does not have a fixed DPI. A D2D1DpiCompensation effect - /// will be inserted if and are different (flags permitting). - /// - /// The resulting for the effect. - /// The for the operation. + /// [PreserveSig] [return: NativeTypeName("HRESULT")] int GetD2DImage( diff --git a/src/ComputeSharp.D2D1.Uwp/Buffers/GraphicsEffectSourceBuffer.cs b/src/ComputeSharp.D2D1.Uwp/Buffers/GraphicsEffectSourceBuffer.cs new file mode 100644 index 00000000..364e72b4 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/Buffers/GraphicsEffectSourceBuffer.cs @@ -0,0 +1,117 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using ComputeSharp.D2D1.Helpers; +using Windows.Graphics.Effects; + +namespace ComputeSharp.D2D1.Uwp.Buffers; + +/// +/// A fixed buffer type containing 16 fields. +/// +internal struct GraphicsEffectSourceBuffer +{ + /// + /// The instance at index 0. + /// + public SourceReference Source0; + + /// + /// The instance at index 1. + /// + public SourceReference Source1; + + /// + /// The instance at index 2. + /// + public SourceReference Source2; + + /// + /// The instance at index 3. + /// + public SourceReference Source3; + + /// + /// The instance at index 4. + /// + public SourceReference Source4; + + /// + /// The instance at index 5. + /// + public SourceReference Source5; + + /// + /// The instance at index 6. + /// + public SourceReference Source6; + + /// + /// The instance at index 7. + /// + public SourceReference Source7; + + /// + /// The instance at index 8. + /// + public SourceReference Source8; + + /// + /// The instance at index 9. + /// + public SourceReference Source9; + + /// + /// The instance at index 10. + /// + public SourceReference Source10; + + /// + /// The instance at index 11. + /// + public SourceReference Source11; + + /// + /// The instance at index 12. + /// + public SourceReference Source12; + + /// + /// The instance at index 13. + /// + public SourceReference Source13; + + /// + /// The instance at index 14. + /// + public SourceReference Source14; + + /// + /// The instance at index 15. + /// + public SourceReference Source15; + + /// + /// Gets a reference to the value at a given index. + /// + /// The index of the value to get a reference to. + /// A reference to the value at a given index. + /// Thrown if is not a valid index for the current effect. + [UnscopedRef] + public ref SourceReference this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if ((uint)index >= 16) + { + ThrowHelper.ThrowArgumentOutOfRangeException(nameof(index), "The index must be in the [0, 15] range."); + } + + ref SourceReference r0 = ref Unsafe.As(ref this); + ref SourceReference r1 = ref Unsafe.Add(ref r0, index); + + return ref r1; + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/Buffers/ResourceTextureManagerBuffer.cs b/src/ComputeSharp.D2D1.Uwp/Buffers/ResourceTextureManagerBuffer.cs new file mode 100644 index 00000000..c9ab2eab --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/Buffers/ResourceTextureManagerBuffer.cs @@ -0,0 +1,117 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using ComputeSharp.D2D1.Helpers; +using ComputeSharp.D2D1.Interop; + +namespace ComputeSharp.D2D1.Uwp.Buffers; + +/// +/// A fixed buffer type containing 16 fields. +/// +internal struct ResourceTextureManagerBuffer +{ + /// + /// The instance at index 0. + /// + public D2D1ResourceTextureManager? ResourceTextureManager0; + + /// + /// The instance at index 1. + /// + public D2D1ResourceTextureManager? ResourceTextureManager1; + + /// + /// The instance at index 2. + /// + public D2D1ResourceTextureManager? ResourceTextureManager2; + + /// + /// The instance at index 3. + /// + public D2D1ResourceTextureManager? ResourceTextureManager3; + + /// + /// The instance at index 4. + /// + public D2D1ResourceTextureManager? ResourceTextureManager4; + + /// + /// The instance at index 5. + /// + public D2D1ResourceTextureManager? ResourceTextureManager5; + + /// + /// The instance at index 6. + /// + public D2D1ResourceTextureManager? ResourceTextureManager6; + + /// + /// The instance at index 7. + /// + public D2D1ResourceTextureManager? ResourceTextureManager7; + + /// + /// The instance at index 8. + /// + public D2D1ResourceTextureManager? ResourceTextureManager8; + + /// + /// The instance at index 9. + /// + public D2D1ResourceTextureManager? ResourceTextureManager9; + + /// + /// The instance at index 10. + /// + public D2D1ResourceTextureManager? ResourceTextureManager10; + + /// + /// The instance at index 11. + /// + public D2D1ResourceTextureManager? ResourceTextureManager11; + + /// + /// The instance at index 12. + /// + public D2D1ResourceTextureManager? ResourceTextureManager12; + + /// + /// The instance at index 13. + /// + public D2D1ResourceTextureManager? ResourceTextureManager13; + + /// + /// The instance at index 14. + /// + public D2D1ResourceTextureManager? ResourceTextureManager14; + + /// + /// The instance at index 15. + /// + public D2D1ResourceTextureManager? ResourceTextureManager15; + + /// + /// Gets a reference to the value at a given index. + /// + /// The index of the value to get a reference to. + /// A reference to the value at a given index. + /// Thrown if is not a valid index for the current effect. + [UnscopedRef] + public ref D2D1ResourceTextureManager? this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if ((uint)index >= 16) + { + ThrowHelper.ThrowArgumentOutOfRangeException(nameof(index), "The index must be in the [0, 15] range."); + } + + ref D2D1ResourceTextureManager? r0 = ref Unsafe.As(ref this); + ref D2D1ResourceTextureManager? r1 = ref Unsafe.Add(ref r0, index); + + return ref r1; + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/Buffers/SourceReference.cs b/src/ComputeSharp.D2D1.Uwp/Buffers/SourceReference.cs new file mode 100644 index 00000000..0e106017 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/Buffers/SourceReference.cs @@ -0,0 +1,154 @@ +using System; +using System.Runtime.CompilerServices; +using ABI.Microsoft.Graphics.Canvas; +using ComputeSharp.D2D1.Uwp.Extensions; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using Windows.Graphics.Effects; + +namespace ComputeSharp.D2D1.Uwp.Buffers; + +/// +/// A wrapper type for an input and its underlying native D2D images. +/// +/// +/// +/// This type is meant to support these two common operations: +/// +/// Look up a D2D resource from a property of some other D2D interface. +/// Get a managed wrapper from a D2D interface. +/// +/// With this, the generated D2D objects can be associated with each original managed wrapper. Similarly, +/// when the other way around is used, this type can also store the generated wrapper for future use. +/// +/// +/// This gives the following improvements: +/// +/// Improved performance for the common case of repeated calls using the same D2D instance. +/// Maintaining a reference to the wrapper avoids it being repeatedly released and recreated. +/// +/// +/// +/// Just like with all other members of an effect, values in this object are considered authoritative when the +/// effect is not realized, otherwise they just act as a cache to speedup the reverse managed wrapper lookups. +/// +/// +/// For realized effects, tracks both the resource and its +/// wrapper (and optional being the DPI compensation effect, +/// if one is needed. For unrealized effects, the resource is and only the wrapper part is used. +/// +/// +internal unsafe struct SourceReference +{ + /// + /// The produced by calling + /// on the input managed wrapper used as source for the effect (ie. ). + /// + private ComPtr d2D1ImageSource; + + /// + /// The for DPI compensation wrapping , if needed. + /// + private ComPtr d2D1EffectDpiCompensation; + + /// + /// The instance being a managed wrapper for the current effect input. + /// + private IGraphicsEffectSource? graphicsEffectSourceWrapper; + + /// + /// Gets whether or not this source ference has a DPI compensation effect. + /// + public readonly bool HasDpiCompensationEffect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => this.d2D1EffectDpiCompensation.Get() is not null; + } + + /// + /// Gets the object for the DPI compensation effect used, if any. + /// + /// The object for the DPI compensation effect used, if any. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly ID2D1Effect* GetDpiCompensationEffect() + { + return this.d2D1EffectDpiCompensation.Get(); + } + + /// + /// Sets the DPI compensation effet being used, + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetDpiCompensationEffect(ID2D1Effect* d2D1Effect) + { + this.d2D1EffectDpiCompensation.Dispose(); + + if (d2D1Effect is not null) + { + this.d2D1EffectDpiCompensation = new ComPtr(d2D1Effect); + } + } + + /// + /// Gets the instance being a managed wrapper for the current effect input. + /// + /// The instance being a managed wrapper for the current effect input. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly IGraphicsEffectSource? GetWrapper() + { + return this.graphicsEffectSourceWrapper; + } + + /// + /// Sets the instance being a managed wrapper for the current effect input. + /// + /// The instance being a managed wrapper for the current effect input. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetWrapper(IGraphicsEffectSource? wrapper) + { + this.graphicsEffectSourceWrapper = wrapper; + } + + /// + /// Sets the wrapper and underlying realized resource for the current source reference. + /// + /// The instance being a managed wrapper for the current effect input. + /// The underlying relized instance for . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetWrapperAndResource(IGraphicsEffectSource? wrapper, ID2D1Image* d2D1Image) + { + this.d2D1ImageSource.Dispose(); + + this.d2D1ImageSource = new ComPtr(d2D1Image); + this.graphicsEffectSourceWrapper = wrapper; + } + + /// + /// Gets or creates an wrapper for a given object. + /// + /// The input object the source effect is realized on. + /// The input object to get or create a wrapper for. + /// An wrapper for a given object. + public IGraphicsEffectSource? GetOrCreateWrapper(ICanvasDevice* canvasDevice, ID2D1Image* d2D1Image) + { + // Check if there already is a matching managed wrapper for the input image + if (!this.d2D1ImageSource.Get()->IsSameInstance(d2D1Image)) + { + // If that's not the case, create a new wrapper if the input image is not null + if (d2D1Image is not null) + { + // m_wrapper = ResourceManager::GetOrCreate(device, resource); + throw new NotImplementedException(); + } + else + { + this.d2D1ImageSource.Dispose(); + } + + this.d2D1ImageSource = new ComPtr(d2D1Image); + } + + return this.graphicsEffectSourceWrapper; + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs index 736d3fb0..f1b9fe74 100644 --- a/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs @@ -8,9 +8,11 @@ using ComputeSharp.D2D1.Helpers; using ComputeSharp.D2D1.Interop; using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; +using ComputeSharp.D2D1.Uwp.Buffers; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using Windows.Graphics.Effects; +using Win32 = TerraFX.Interop.Windows.Windows; #pragma warning disable CS0618 @@ -91,18 +93,16 @@ internal static unsafe class ID2D1EffectExtensions /// /// Gets the source from a given object, at a specified index. /// - /// The type of shader being used. /// The input instance. /// The realization device currently in use. - /// The input object for the target index. + /// The input object for the target index. /// The index for the source to retrieve. /// The source from a given object, at a specified index. - public static IGraphicsEffectSource? GetSource( + public static IGraphicsEffectSource? GetSource( this ref ID2D1Effect d2D1Effect, ICanvasDevice* canvasDevice, - ref PixelShaderEffect.SourceCollection.SourceReference source, + ref SourceReference source, int index) - where T : unmanaged, ID2D1PixelShader { using ComPtr d2D1Image = default; @@ -132,6 +132,104 @@ internal static unsafe class ID2D1EffectExtensions return source.GetOrCreateWrapper(null, d2D1Image.Get()); } + /// + /// Sets the source for a given object, at a specified index. + /// + /// The input instance. + /// The realization device currently in use. + /// The device context currently in use. + /// The realization flags to use. + /// The target DPI value for the source. + /// The input value to set. + /// The target value, for caching. + /// The index of the source to set. + /// Whether the operation succeeded (if it didn't the effect should be unrealized). + public static bool TrySetSource( + this ref ID2D1Effect d2D1Effect, + ICanvasDevice* canvasDevice, + ID2D1DeviceContext* deviceContext, + GetD2DImageFlags flags, + float targetDpi, + IGraphicsEffectSource? value, + ref SourceReference source, + int index) + { + using ComPtr d2D1Image = default; + + float realizedDpi = 0; + + if (value is not null) + { + using ComPtr canvasImageUnknown = default; + + // Get the underlying IUnknown object for the input source + canvasImageUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(value)); + + using ComPtr canvasImageInterop = default; + + // Try to get the ICanvasImageInterop interface from the input source + HRESULT hresult = canvasImageUnknown.CopyTo(canvasImageInterop.GetAddressOf()); + + if (!Win32.SUCCEEDED(hresult)) + { + // If unrealization isn't requested for failures, just throw + if ((flags & GetD2DImageFlags.UnrealizeOnFailure) == GetD2DImageFlags.None) + { + ThrowHelper.ThrowArgumentException(nameof(value), "The effect source is not valid (it must implement ICanvasImageInterop)."); + } + + return false; + } + + using ComPtr sourceCanvasDevice = default; + + // Get the canvas device the source is realized on, if any + canvasImageInterop.Get()->GetDevice(sourceCanvasDevice.GetAddressOf()).Assert(); + + // If a device was retrieved, it must be the same as the input one. If the source has no device, + // that is fine, as it just means that its underlying D2D image has not been realized yet. + if (sourceCanvasDevice.Get() is not null && !canvasDevice->IsSameInstance(sourceCanvasDevice.Get())) + { + if ((flags & GetD2DImageFlags.UnrealizeOnFailure) == GetD2DImageFlags.None) + { + ThrowHelper.ThrowArgumentException(nameof(value), "The effect source is realized on a different canvas device."); + } + + return false; + } + + // Try to realize the image from the input source + hresult = canvasImageInterop.Get()->GetD2DImage( + device: canvasDevice, + deviceContext: deviceContext, + flags: flags, + targetDpi: targetDpi, + realizeDpi: &realizedDpi, + ppImage: d2D1Image.GetAddressOf()); + + // Unless requested, a failure to retrieve the image should just bubble up the HRESULT in an exception + if ((flags & GetD2DImageFlags.UnrealizeOnFailure) == GetD2DImageFlags.None) + { + hresult.Assert(); + } + } + else if ((flags & GetD2DImageFlags.AllowNullEffectInputs) == GetD2DImageFlags.None) + { + // If the source is null and this is not explicitly allowed, the invocation is not valid + ThrowHelper.ThrowArgumentNullException(nameof(value), "The effect source cannot be null."); + } + + // Save the managed wrapper and realized image + source.SetWrapperAndResource(value, d2D1Image.Get()); + + // TODO: handle DPI compensation + + // Set the actual effect input + d2D1Effect.SetInput(index: (uint)index, input: d2D1Image.Get()); + + return true; + } + /// /// Gets the instance from a given object. /// diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs index 5e3b1847..54a6ce52 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs @@ -1,4 +1,6 @@ +using ABI.Microsoft.Graphics.Canvas; using ComputeSharp.D2D1.Interop; +using ComputeSharp.D2D1.Uwp.Buffers; using ComputeSharp.D2D1.Uwp.Extensions; using ComputeSharp.Interop; using Microsoft.Graphics.Canvas; @@ -101,7 +103,7 @@ unsafe partial class PixelShaderEffect lock (this.lockObject) { - ref SourceCollection.SourceReference source = ref Sources.Storage[index]; + ref SourceReference source = ref Sources.Storage[index]; return this.d2D1Effect.Get() switch { @@ -111,6 +113,46 @@ unsafe partial class PixelShaderEffect } } + /// + /// Sets the marshalled value for . + /// + /// The value to set for . + /// The index of the source to get or set. + private void SetSource(IGraphicsEffectSource? value, int index) + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + ref SourceReference source = ref Sources.Storage[index]; + + if (this.d2D1Effect.Get() is not null) + { + const GetD2DImageFlags sourceFlags = + GetD2DImageFlags.MinimalRealization | + GetD2DImageFlags.AllowNullEffectInputs | + GetD2DImageFlags.UnrealizeOnFailure; + + // Try to set the source, and unrealize if the operation failed + if (!this.d2D1Effect.Get()->TrySetSource( + canvasDevice: this.canvasDevice.Get(), + deviceContext: null, + flags: sourceFlags, + targetDpi: 0, + value: value, + source: ref source, + index: index)) + { + Unrealize(); + } + } + else + { + source.SetWrapper(value); + } + } + } + /// /// Gets the marshalled value for . /// diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs index 65922e42..e214a282 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs @@ -1,8 +1,7 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; -using ComputeSharp.D2D1.Helpers; using ComputeSharp.D2D1.Interop; +using ComputeSharp.D2D1.Uwp.Buffers; namespace ComputeSharp.D2D1.Uwp; @@ -17,7 +16,7 @@ partial class PixelShaderEffect /// /// The fixed buffer of instances. /// - private FixedBuffer fixedBuffer; + private ResourceTextureManagerBuffer fixedBuffer; /// /// Creates a new instance with the specified parameters. @@ -48,118 +47,8 @@ partial class PixelShaderEffect internal PixelShaderEffect Owner { get; } /// - /// Gets a reference to the value containing the available -s. + /// Gets a reference to the value containing the available -s. /// - internal ref FixedBuffer Storage => ref this.fixedBuffer; - - /// - /// A fixed buffer type containing 16 fields. - /// - internal struct FixedBuffer - { - /// - /// The instance at index 0. - /// - public D2D1ResourceTextureManager? ResourceTextureManager0; - - /// - /// The instance at index 1. - /// - public D2D1ResourceTextureManager? ResourceTextureManager1; - - /// - /// The instance at index 2. - /// - public D2D1ResourceTextureManager? ResourceTextureManager2; - - /// - /// The instance at index 3. - /// - public D2D1ResourceTextureManager? ResourceTextureManager3; - - /// - /// The instance at index 4. - /// - public D2D1ResourceTextureManager? ResourceTextureManager4; - - /// - /// The instance at index 5. - /// - public D2D1ResourceTextureManager? ResourceTextureManager5; - - /// - /// The instance at index 6. - /// - public D2D1ResourceTextureManager? ResourceTextureManager6; - - /// - /// The instance at index 7. - /// - public D2D1ResourceTextureManager? ResourceTextureManager7; - - /// - /// The instance at index 8. - /// - public D2D1ResourceTextureManager? ResourceTextureManager8; - - /// - /// The instance at index 9. - /// - public D2D1ResourceTextureManager? ResourceTextureManager9; - - /// - /// The instance at index 10. - /// - public D2D1ResourceTextureManager? ResourceTextureManager10; - - /// - /// The instance at index 11. - /// - public D2D1ResourceTextureManager? ResourceTextureManager11; - - /// - /// The instance at index 12. - /// - public D2D1ResourceTextureManager? ResourceTextureManager12; - - /// - /// The instance at index 13. - /// - public D2D1ResourceTextureManager? ResourceTextureManager13; - - /// - /// The instance at index 14. - /// - public D2D1ResourceTextureManager? ResourceTextureManager14; - - /// - /// The instance at index 15. - /// - public D2D1ResourceTextureManager? ResourceTextureManager15; - - /// - /// Gets a reference to the value at a given index. - /// - /// The index of the value to get a reference to. - /// A reference to the value at a given index. - /// Thrown if is not a valid index for the current effect. - [UnscopedRef] - public ref D2D1ResourceTextureManager? this[int index] - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - if ((uint)index >= 16) - { - ThrowHelper.ThrowArgumentOutOfRangeException(nameof(index), "The index must be in the [0, 15] range."); - } - - ref D2D1ResourceTextureManager? r0 = ref Unsafe.As(ref this); - ref D2D1ResourceTextureManager? r1 = ref Unsafe.Add(ref r0, index); - - return ref r1; - } - } - } + internal ref ResourceTextureManagerBuffer Storage => ref this.fixedBuffer; } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs index 938dced2..b9e0afca 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs @@ -1,11 +1,5 @@ using System; -using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; -using ABI.Microsoft.Graphics.Canvas; -using ComputeSharp.D2D1.Helpers; -using ComputeSharp.D2D1.Uwp.Extensions; -using TerraFX.Interop.DirectX; -using TerraFX.Interop.Windows; +using ComputeSharp.D2D1.Uwp.Buffers; using Windows.Graphics.Effects; namespace ComputeSharp.D2D1.Uwp; @@ -21,7 +15,7 @@ partial class PixelShaderEffect /// /// The fixed buffer of instances. /// - private FixedBuffer fixedBuffer; + private GraphicsEffectSourceBuffer fixedBuffer; /// /// Creates a new instance with the specified parameters. @@ -38,10 +32,10 @@ partial class PixelShaderEffect /// The index of the source to get or set. /// The source at the specified index. /// Thrown if is not a valid index for the current effect. - public IGraphicsEffectSource this[int index] + public IGraphicsEffectSource? this[int index] { - get => null!; - set { } + get => Owner.GetSource(index); + set => Owner.SetSource(value, index); } /// @@ -50,241 +44,8 @@ partial class PixelShaderEffect internal PixelShaderEffect Owner { get; } /// - /// Gets a reference to the value containing the available -s. + /// Gets a reference to the value containing the available -s. /// - internal ref FixedBuffer Storage => ref this.fixedBuffer; - - /// - /// A fixed buffer type containing 16 fields. - /// - internal struct FixedBuffer - { - /// - /// The instance at index 0. - /// - public SourceReference Source0; - - /// - /// The instance at index 1. - /// - public SourceReference Source1; - - /// - /// The instance at index 2. - /// - public SourceReference Source2; - - /// - /// The instance at index 3. - /// - public SourceReference Source3; - - /// - /// The instance at index 4. - /// - public SourceReference Source4; - - /// - /// The instance at index 5. - /// - public SourceReference Source5; - - /// - /// The instance at index 6. - /// - public SourceReference Source6; - - /// - /// The instance at index 7. - /// - public SourceReference Source7; - - /// - /// The instance at index 8. - /// - public SourceReference Source8; - - /// - /// The instance at index 9. - /// - public SourceReference Source9; - - /// - /// The instance at index 10. - /// - public SourceReference Source10; - - /// - /// The instance at index 11. - /// - public SourceReference Source11; - - /// - /// The instance at index 12. - /// - public SourceReference Source12; - - /// - /// The instance at index 13. - /// - public SourceReference Source13; - - /// - /// The instance at index 14. - /// - public SourceReference Source14; - - /// - /// The instance at index 15. - /// - public SourceReference Source15; - - /// - /// Gets a reference to the value at a given index. - /// - /// The index of the value to get a reference to. - /// A reference to the value at a given index. - /// Thrown if is not a valid index for the current effect. - [UnscopedRef] - public ref SourceReference this[int index] - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - if ((uint)index >= 16) - { - ThrowHelper.ThrowArgumentOutOfRangeException(nameof(index), "The index must be in the [0, 15] range."); - } - - ref SourceReference r0 = ref Unsafe.As(ref this); - ref SourceReference r1 = ref Unsafe.Add(ref r0, index); - - return ref r1; - } - } - } - - /// - /// A wrapper type for an input and its underlying native D2D images. - /// - /// - /// - /// This type is meant to support these two common operations: - /// - /// Look up a D2D resource from a property of some other D2D interface. - /// Get a managed wrapper from a D2D interface. - /// - /// With this, the generated D2D objects can be associated with each original managed wrapper. Similarly, - /// when the other way around is used, this type can also store the generated wrapper for future use. - /// - /// - /// This gives the following improvements: - /// - /// Improved performance for the common case of repeated calls using the same D2D instance. - /// Maintaining a reference to the wrapper avoids it being repeatedly released and recreated. - /// - /// - /// - /// Just like with all other members of an effect, values in this object are considered authoritative when the - /// effect is not realized, otherwise they just act as a cache to speedup the reverse managed wrapper lookups. - /// - /// - /// For realized effects, tracks both the resource and its - /// wrapper (and optional being the DPI compensation effect, - /// if one is needed. For unrealized effects, the resource is and only the wrapper part is used. - /// - /// - internal unsafe struct SourceReference - { - /// - /// The produced by calling - /// on the input managed wrapper used as source for the effect (ie. ). - /// - private ComPtr d2D1ImageSource; - - /// - /// The for DPI compensation wrapping , if needed. - /// - private ComPtr d2D1EffectDpiCompensation; - - /// - /// The instance being a managed wrapper for the current effect input. - /// - private IGraphicsEffectSource? graphicsEffectSourceWrapper; - - /// - /// Gets whether or not this source ference has a DPI compensation effect. - /// - public readonly bool HasDpiCompensationEffect - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => this.d2D1EffectDpiCompensation.Get() is not null; - } - - /// - /// Gets the object for the DPI compensation effect used, if any. - /// - /// The object for the DPI compensation effect used, if any. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public readonly ID2D1Effect* GetDpiCompensationEffect() - { - return this.d2D1EffectDpiCompensation.Get(); - } - - /// - /// Sets the DPI compensation effet being used, - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void SetDpiCompensationEffect(ID2D1Effect* d2D1Effect) - { - _ = this.d2D1EffectDpiCompensation.Reset(); - - if (d2D1Effect is not null) - { - this.d2D1EffectDpiCompensation = new ComPtr(d2D1Effect); - } - } - - /// - /// Gets the instance being a managed wrapper for the current effect input. - /// - /// The instance being a managed wrapper for the current effect input. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public readonly IGraphicsEffectSource? GetWrapper() - { - return this.graphicsEffectSourceWrapper; - } - - /// - /// Gets or creates an wrapper for a given object. - /// - /// The input object the source effect is realized on. - /// The input object to get or create a wrapper for. - /// An wrapper for a given object. - public IGraphicsEffectSource? GetOrCreateWrapper(ICanvasDevice* canvasDevice, ID2D1Image* d2D1Image) - { - // Check if there already is a matching managed wrapper for the input image - if (!this.d2D1ImageSource.Get()->IsSameInstance(d2D1Image)) - { - // If that's not the case, create a new wrapper if the input image is not null - if (d2D1Image is not null) - { - // m_wrapper = ResourceManager::GetOrCreate(device, resource); - throw new NotImplementedException(); - } - else - { - _ = this.d2D1ImageSource.Reset(); - } - - _ = this.d2D1ImageSource.Reset(); - - this.d2D1ImageSource = new ComPtr(d2D1Image); - } - - return this.graphicsEffectSourceWrapper; - } - } + internal ref GraphicsEffectSourceBuffer Storage => ref this.fixedBuffer; } } \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Effect.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Effect.cs index 43851234..63404b95 100644 --- a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Effect.cs +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Effect.cs @@ -33,6 +33,13 @@ internal unsafe partial struct ID2D1Effect return ((delegate* unmanaged[Stdcall])(lpVtbl[11]))((ID2D1Effect*)Unsafe.AsPointer(ref this), index, type, data, dataSize); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(14)] + public void SetInput([NativeTypeName("UINT32")] uint index, ID2D1Image* input, [NativeTypeName("BOOL")] int invalidate = 1) + { + ((delegate* unmanaged[Stdcall])(lpVtbl[14]))((ID2D1Effect*)Unsafe.AsPointer(ref this), index, input, invalidate); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(16)] public void GetInput([NativeTypeName("UINT32")] uint index, ID2D1Image** input) From 91ef70907b86d6c5f1676e2955333ab909ca6e63 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 3 Dec 2022 03:26:04 +0100 Subject: [PATCH 34/59] Remove unnecessary constructors --- .../Shaders/Interop/D2D1InputDescription.cs | 16 +++------------- .../Interop/D2D1ResourceTextureDescription.cs | 14 +++----------- 2 files changed, 6 insertions(+), 24 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InputDescription.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InputDescription.cs index fb23e794..26a1909e 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InputDescription.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InputDescription.cs @@ -1,3 +1,5 @@ +using System.Runtime.InteropServices; + namespace ComputeSharp.D2D1.Interop; /// @@ -7,6 +9,7 @@ namespace ComputeSharp.D2D1.Interop; /// This type exposes the values that can be set via ID2D1RenderInfo::SetInputDescription. /// For more info, see . /// +[StructLayout(LayoutKind.Sequential)] public readonly struct D2D1InputDescription { /// @@ -30,19 +33,6 @@ public readonly struct D2D1InputDescription /// private readonly int levelOfDetailCount; - /// - /// Creates a new instance with the specified parameters. - /// - /// The index of the resource the description belongs to. - /// The type of filter to apply to the input texture. - /// The mip level to retrieve from the upstream transform, if specified. - internal D2D1InputDescription(int index, D2D1Filter filter, int levelOfDetailCount) - { - this.index = index; - this.filter = filter; - this.levelOfDetailCount = levelOfDetailCount; - } - /// /// Gets the index of the resource the description belongs to. /// diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureDescription.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureDescription.cs index 0acf68e4..f842ec65 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureDescription.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureDescription.cs @@ -1,8 +1,11 @@ +using System.Runtime.InteropServices; + namespace ComputeSharp.D2D1.Interop; /// /// A type containing info on a description for a given D2D1 pixel shader resource resource. /// +[StructLayout(LayoutKind.Sequential)] public readonly struct D2D1ResourceTextureDescription { /// @@ -16,17 +19,6 @@ public readonly struct D2D1ResourceTextureDescription /// private readonly int dimensions; - /// - /// Creates a new instance with the specified parameters. - /// - /// The index of the resource texture the description belongs to. - /// The number of dimensions of the resource texture the description belongs to. - internal D2D1ResourceTextureDescription(int index, int dimensions) - { - this.index = index; - this.dimensions = dimensions; - } - /// /// Gets the index of the resource texture the description belongs to. /// From eacda866a2cba8522707ce9817495c9dad79f8c2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 8 Dec 2022 03:14:02 +0100 Subject: [PATCH 35/59] Rename GetD2DImageFlags to follow Win2D changes --- .../ICanvasImageInterop.cs | 13 ++++++------ ...eFlags.cs => WIN2D_GET_D2D_IMAGE_FLAGS.cs} | 21 ++++++++++++------- .../Extensions/ID2D1EffectExtensions.cs | 11 +++++----- ...ixelShaderEffect{T}.ICanvasImageInterop.cs | 15 ++++++------- ...PixelShaderEffect{T}.Properties.Interop.cs | 9 ++++---- 5 files changed, 39 insertions(+), 30 deletions(-) rename src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/{GetD2DImageFlags.cs => WIN2D_GET_D2D_IMAGE_FLAGS.cs} (64%) diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs index 3d6c8e3e..4de25009 100644 --- a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs @@ -37,7 +37,7 @@ internal unsafe struct ICanvasImageInterop /// The input canvas device (as a marshalled ). /// /// The device context in use. This value is is optional (but recommended), except when the - /// flag is specified. This is because + /// flag is specified. This is because /// not all callers of have easy access to a context. It is always /// possible to get a resource creation context from the device, but the context is only /// actually necessary if a new effect realization needs to be created, so it is more efficient @@ -47,8 +47,9 @@ internal unsafe struct ICanvasImageInterop /// /// The DPI of the target device context. This is used to determine when a D2D1DpiCompensation /// effect needs to be inserted. Behavior of this parameter can be overridden by the flag values - /// , - /// or + /// , + /// + /// or /// /// /// The DPI of a source bitmap, or zero if the image does not have a fixed DPI. A D2D1DpiCompensation effect @@ -61,12 +62,12 @@ internal unsafe struct ICanvasImageInterop public HRESULT GetD2DImage( ICanvasDevice* device, ID2D1DeviceContext* deviceContext, - GetD2DImageFlags flags, + WIN2D_GET_D2D_IMAGE_FLAGS flags, float targetDpi, float* realizeDpi, ID2D1Image** ppImage) { - return ((delegate* unmanaged[Stdcall])this.lpVtbl[4])( + return ((delegate* unmanaged[Stdcall])this.lpVtbl[4])( (ICanvasImageInterop*)Unsafe.AsPointer(ref this), device, deviceContext, @@ -95,7 +96,7 @@ internal unsafe struct ICanvasImageInterop int GetD2DImage( ICanvasDevice* device, ID2D1DeviceContext* deviceContext, - GetD2DImageFlags flags, + WIN2D_GET_D2D_IMAGE_FLAGS flags, float targetDpi, float* realizeDpi, ID2D1Image** ppImage); diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/GetD2DImageFlags.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/WIN2D_GET_D2D_IMAGE_FLAGS.cs similarity index 64% rename from src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/GetD2DImageFlags.cs rename to src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/WIN2D_GET_D2D_IMAGE_FLAGS.cs index 85af8c4c..a7697b7a 100644 --- a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/GetD2DImageFlags.cs +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/WIN2D_GET_D2D_IMAGE_FLAGS.cs @@ -6,40 +6,45 @@ namespace ABI.Microsoft.Graphics.Canvas; /// Options for fine-tuning the behavior of . /// [Flags] -internal enum GetD2DImageFlags +internal enum WIN2D_GET_D2D_IMAGE_FLAGS : uint { /// /// No options specified. /// - None = 0, + WIN2D_GET_D2D_IMAGE_FLAGS_NONE = 0, /// /// Ignore the targetDpi parameter, read DPI from deviceContext instead. /// - ReadDpiFromDeviceContext = 1, + WIN2D_GET_D2D_IMAGE_FLAGS_READ_DPI_FROM_DEVICE_CONTEXT = 1, /// /// Ignore the targetDpi parameter, always insert DPI compensation. /// - AlwaysInsertDpiCompensation = 2, + WIN2D_GET_D2D_IMAGE_FLAGS_ALWAYS_INSERT_DPI_COMPENSATION = 2, /// /// Ignore the targetDpi parameter, never insert DPI compensation. /// - NeverInsertDpiCompensation = 4, + WIN2D_GET_D2D_IMAGE_FLAGS_NEVER_INSERT_DPI_COMPENSATION = 4, /// /// Do the bare minimum to get back an ID2D1Image, no validation or recursive realization. /// - MinimalRealization = 8, + WIN2D_GET_D2D_IMAGE_FLAGS_MINIMAL_REALIZATION = 8, /// /// Allow partially configured effect graphs where some inputs are . /// - AllowNullEffectInputs = 16, + WIN2D_GET_D2D_IMAGE_FLAGS_ALLOW_NULL_EFFECT_INPUTS = 16, /// /// If an input is invalid, unrealize the effect and set the output image to . /// - UnrealizeOnFailure = 32 + WIN2D_GET_D2D_IMAGE_FLAGS_UNREALIZE_ON_FAILURE = 32, + + /// + /// Ignored. + /// + WIN2D_GET_D2D_IMAGE_FLAGS_FORCE_DWORD = 0xffffffff } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs index f1b9fe74..59f78ae1 100644 --- a/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs @@ -12,6 +12,7 @@ using ComputeSharp.D2D1.Uwp.Buffers; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using Windows.Graphics.Effects; +using static ABI.Microsoft.Graphics.Canvas.WIN2D_GET_D2D_IMAGE_FLAGS; using Win32 = TerraFX.Interop.Windows.Windows; #pragma warning disable CS0618 @@ -148,7 +149,7 @@ internal static unsafe class ID2D1EffectExtensions this ref ID2D1Effect d2D1Effect, ICanvasDevice* canvasDevice, ID2D1DeviceContext* deviceContext, - GetD2DImageFlags flags, + WIN2D_GET_D2D_IMAGE_FLAGS flags, float targetDpi, IGraphicsEffectSource? value, ref SourceReference source, @@ -173,7 +174,7 @@ internal static unsafe class ID2D1EffectExtensions if (!Win32.SUCCEEDED(hresult)) { // If unrealization isn't requested for failures, just throw - if ((flags & GetD2DImageFlags.UnrealizeOnFailure) == GetD2DImageFlags.None) + if ((flags & WIN2D_GET_D2D_IMAGE_FLAGS_UNREALIZE_ON_FAILURE) == WIN2D_GET_D2D_IMAGE_FLAGS_NONE) { ThrowHelper.ThrowArgumentException(nameof(value), "The effect source is not valid (it must implement ICanvasImageInterop)."); } @@ -190,7 +191,7 @@ internal static unsafe class ID2D1EffectExtensions // that is fine, as it just means that its underlying D2D image has not been realized yet. if (sourceCanvasDevice.Get() is not null && !canvasDevice->IsSameInstance(sourceCanvasDevice.Get())) { - if ((flags & GetD2DImageFlags.UnrealizeOnFailure) == GetD2DImageFlags.None) + if ((flags & WIN2D_GET_D2D_IMAGE_FLAGS_UNREALIZE_ON_FAILURE) == WIN2D_GET_D2D_IMAGE_FLAGS_NONE) { ThrowHelper.ThrowArgumentException(nameof(value), "The effect source is realized on a different canvas device."); } @@ -208,12 +209,12 @@ internal static unsafe class ID2D1EffectExtensions ppImage: d2D1Image.GetAddressOf()); // Unless requested, a failure to retrieve the image should just bubble up the HRESULT in an exception - if ((flags & GetD2DImageFlags.UnrealizeOnFailure) == GetD2DImageFlags.None) + if ((flags & WIN2D_GET_D2D_IMAGE_FLAGS_UNREALIZE_ON_FAILURE) == WIN2D_GET_D2D_IMAGE_FLAGS_NONE) { hresult.Assert(); } } - else if ((flags & GetD2DImageFlags.AllowNullEffectInputs) == GetD2DImageFlags.None) + else if ((flags & WIN2D_GET_D2D_IMAGE_FLAGS_ALLOW_NULL_EFFECT_INPUTS) == WIN2D_GET_D2D_IMAGE_FLAGS_NONE) { // If the source is null and this is not explicitly allowed, the invocation is not valid ThrowHelper.ThrowArgumentNullException(nameof(value), "The effect source cannot be null."); diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index e227672a..e2afddb4 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -8,6 +8,7 @@ using ComputeSharp.D2D1.Uwp.Extensions; using ComputeSharp.Interop; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; +using static ABI.Microsoft.Graphics.Canvas.WIN2D_GET_D2D_IMAGE_FLAGS; using Win32 = TerraFX.Interop.Windows.Windows; namespace ComputeSharp.D2D1.Uwp; @@ -52,7 +53,7 @@ unsafe partial class PixelShaderEffect int ICanvasImageInterop.Interface.GetD2DImage( ICanvasDevice* device, ID2D1DeviceContext* deviceContext, - GetD2DImageFlags flags, + WIN2D_GET_D2D_IMAGE_FLAGS flags, float targetDpi, float* realizeDpi, ID2D1Image** ppImage) @@ -77,7 +78,7 @@ unsafe partial class PixelShaderEffect lock (this.lockObject) { // Process the ReadDpiFromDeviceContext flag (same logic as CanvasEffect::GetD2DImage) - if ((flags & GetD2DImageFlags.ReadDpiFromDeviceContext) != GetD2DImageFlags.None) + if ((flags & WIN2D_GET_D2D_IMAGE_FLAGS_READ_DPI_FROM_DEVICE_CONTEXT) != WIN2D_GET_D2D_IMAGE_FLAGS_NONE) { // If ReadDpiFromDeviceContext is used, the context cannot be null if (deviceContext is null) @@ -88,7 +89,7 @@ unsafe partial class PixelShaderEffect if (deviceContext->HasCommandListTarget()) { // Command lists are DPI dependent, so DPI compensation effects are always needed - flags |= GetD2DImageFlags.AlwaysInsertDpiCompensation; + flags |= WIN2D_GET_D2D_IMAGE_FLAGS_ALWAYS_INSERT_DPI_COMPENSATION; } else { @@ -97,7 +98,7 @@ unsafe partial class PixelShaderEffect } // ReadDpiFromDeviceContext has been processed, so it can be removed now - flags &= ~GetD2DImageFlags.ReadDpiFromDeviceContext; + flags &= ~WIN2D_GET_D2D_IMAGE_FLAGS_READ_DPI_FROM_DEVICE_CONTEXT; } using ComPtr d2D1Device1 = default; @@ -125,7 +126,7 @@ unsafe partial class PixelShaderEffect { Realize(flags, targetDpi, deviceContext); } - else if (!flags.HasFlag(GetD2DImageFlags.MinimalRealization)) + else if (!flags.HasFlag(WIN2D_GET_D2D_IMAGE_FLAGS_MINIMAL_REALIZATION)) { // Recurse through the effect graph and ensure all nodes are initialized RefreshInputs(flags, targetDpi, deviceContext); @@ -187,7 +188,7 @@ unsafe partial class PixelShaderEffect /// The current flags in use. /// The target DPI in use. /// The instance in use. - private void Realize(GetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) + private void Realize(WIN2D_GET_D2D_IMAGE_FLAGS flags, float targetDpi, ID2D1DeviceContext* deviceContext) { using ComPtr d2D1Factory = default; @@ -263,7 +264,7 @@ unsafe partial class PixelShaderEffect /// The current flags in use. /// The target DPI in use. /// The instance in use. - private void RefreshInputs(GetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) + private void RefreshInputs(WIN2D_GET_D2D_IMAGE_FLAGS flags, float targetDpi, ID2D1DeviceContext* deviceContext) { // TODO } diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs index 54a6ce52..3b1f8569 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs @@ -6,6 +6,7 @@ using ComputeSharp.Interop; using Microsoft.Graphics.Canvas; using TerraFX.Interop.DirectX; using Windows.Graphics.Effects; +using static ABI.Microsoft.Graphics.Canvas.WIN2D_GET_D2D_IMAGE_FLAGS; namespace ComputeSharp.D2D1.Uwp; @@ -128,10 +129,10 @@ unsafe partial class PixelShaderEffect if (this.d2D1Effect.Get() is not null) { - const GetD2DImageFlags sourceFlags = - GetD2DImageFlags.MinimalRealization | - GetD2DImageFlags.AllowNullEffectInputs | - GetD2DImageFlags.UnrealizeOnFailure; + const WIN2D_GET_D2D_IMAGE_FLAGS sourceFlags = + WIN2D_GET_D2D_IMAGE_FLAGS_MINIMAL_REALIZATION | + WIN2D_GET_D2D_IMAGE_FLAGS_ALLOW_NULL_EFFECT_INPUTS | + WIN2D_GET_D2D_IMAGE_FLAGS_UNREALIZE_ON_FAILURE; // Try to set the source, and unrealize if the operation failed if (!this.d2D1Effect.Get()->TrySetSource( From a33f4ddbb78a572cad18e52b3759226042e1f8fa Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 8 Dec 2022 15:03:43 +0100 Subject: [PATCH 36/59] Refactor D2D sources logic, implement Unrealize() --- .../Buffers/SourceReference.cs | 12 +- .../Extensions/ID2D1EffectExtensions.cs | 145 ------------ ...ixelShaderEffect{T}.ICanvasImageInterop.cs | 35 ++- ...derEffect{T}.Properties.Interop.Sources.cs | 211 ++++++++++++++++++ ...PixelShaderEffect{T}.Properties.Interop.cs | 65 ------ 5 files changed, 255 insertions(+), 213 deletions(-) create mode 100644 src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.Sources.cs diff --git a/src/ComputeSharp.D2D1.Uwp/Buffers/SourceReference.cs b/src/ComputeSharp.D2D1.Uwp/Buffers/SourceReference.cs index 0e106017..25764282 100644 --- a/src/ComputeSharp.D2D1.Uwp/Buffers/SourceReference.cs +++ b/src/ComputeSharp.D2D1.Uwp/Buffers/SourceReference.cs @@ -38,7 +38,7 @@ namespace ComputeSharp.D2D1.Uwp.Buffers; /// if one is needed. For unrealized effects, the resource is and only the wrapper part is used. /// /// -internal unsafe struct SourceReference +internal unsafe struct SourceReference : IDisposable { /// /// The produced by calling @@ -107,6 +107,8 @@ internal unsafe struct SourceReference [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetWrapper(IGraphicsEffectSource? wrapper) { + this.d2D1ImageSource.Dispose(); + this.graphicsEffectSourceWrapper = wrapper; } @@ -151,4 +153,12 @@ internal unsafe struct SourceReference return this.graphicsEffectSourceWrapper; } + + /// + public void Dispose() + { + this.d2D1ImageSource.Dispose(); + this.d2D1EffectDpiCompensation.Dispose(); + this.graphicsEffectSourceWrapper = null; + } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs index 59f78ae1..88822c3c 100644 --- a/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/ID2D1EffectExtensions.cs @@ -2,18 +2,13 @@ using System; using System.Buffers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using ABI.Microsoft.Graphics.Canvas; using ComputeSharp.D2D1.Extensions; using ComputeSharp.D2D1.Helpers; using ComputeSharp.D2D1.Interop; using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers; -using ComputeSharp.D2D1.Uwp.Buffers; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; -using Windows.Graphics.Effects; -using static ABI.Microsoft.Graphics.Canvas.WIN2D_GET_D2D_IMAGE_FLAGS; -using Win32 = TerraFX.Interop.Windows.Windows; #pragma warning disable CS0618 @@ -91,146 +86,6 @@ internal static unsafe class ID2D1EffectExtensions return (D2D1TransformMapper)GCHandle.FromIntPtr(handlePtr).Target!; } - /// - /// Gets the source from a given object, at a specified index. - /// - /// The input instance. - /// The realization device currently in use. - /// The input object for the target index. - /// The index for the source to retrieve. - /// The source from a given object, at a specified index. - public static IGraphicsEffectSource? GetSource( - this ref ID2D1Effect d2D1Effect, - ICanvasDevice* canvasDevice, - ref SourceReference source, - int index) - { - using ComPtr d2D1Image = default; - - // Get the ID2D1Image input from the effect - d2D1Effect.GetInput( - index: (uint)index, - input: d2D1Image.GetAddressOf()); - - // Check whether the input had a DPI compensation effect added to it, and skip it if so - if (source.HasDpiCompensationEffect) - { - // Since a realized effect is the only source of authority for the effect state, we also - // need to check that the actual source is in fact the same that was previous set by the - // managed wrapper. If it is, we get the input and return that (ie. the underlying image). - // If not, we just return it directly and reset the locally stored DPI compensation effect. - if (d2D1Image.Get()->IsSameInstance(source.GetDpiCompensationEffect())) - { - source.GetDpiCompensationEffect()->GetInput(0, d2D1Image.ReleaseAndGetAddressOf()); - } - else - { - source.SetDpiCompensationEffect(null); - } - } - - // Get or create a wrapper for the input image - return source.GetOrCreateWrapper(null, d2D1Image.Get()); - } - - /// - /// Sets the source for a given object, at a specified index. - /// - /// The input instance. - /// The realization device currently in use. - /// The device context currently in use. - /// The realization flags to use. - /// The target DPI value for the source. - /// The input value to set. - /// The target value, for caching. - /// The index of the source to set. - /// Whether the operation succeeded (if it didn't the effect should be unrealized). - public static bool TrySetSource( - this ref ID2D1Effect d2D1Effect, - ICanvasDevice* canvasDevice, - ID2D1DeviceContext* deviceContext, - WIN2D_GET_D2D_IMAGE_FLAGS flags, - float targetDpi, - IGraphicsEffectSource? value, - ref SourceReference source, - int index) - { - using ComPtr d2D1Image = default; - - float realizedDpi = 0; - - if (value is not null) - { - using ComPtr canvasImageUnknown = default; - - // Get the underlying IUnknown object for the input source - canvasImageUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(value)); - - using ComPtr canvasImageInterop = default; - - // Try to get the ICanvasImageInterop interface from the input source - HRESULT hresult = canvasImageUnknown.CopyTo(canvasImageInterop.GetAddressOf()); - - if (!Win32.SUCCEEDED(hresult)) - { - // If unrealization isn't requested for failures, just throw - if ((flags & WIN2D_GET_D2D_IMAGE_FLAGS_UNREALIZE_ON_FAILURE) == WIN2D_GET_D2D_IMAGE_FLAGS_NONE) - { - ThrowHelper.ThrowArgumentException(nameof(value), "The effect source is not valid (it must implement ICanvasImageInterop)."); - } - - return false; - } - - using ComPtr sourceCanvasDevice = default; - - // Get the canvas device the source is realized on, if any - canvasImageInterop.Get()->GetDevice(sourceCanvasDevice.GetAddressOf()).Assert(); - - // If a device was retrieved, it must be the same as the input one. If the source has no device, - // that is fine, as it just means that its underlying D2D image has not been realized yet. - if (sourceCanvasDevice.Get() is not null && !canvasDevice->IsSameInstance(sourceCanvasDevice.Get())) - { - if ((flags & WIN2D_GET_D2D_IMAGE_FLAGS_UNREALIZE_ON_FAILURE) == WIN2D_GET_D2D_IMAGE_FLAGS_NONE) - { - ThrowHelper.ThrowArgumentException(nameof(value), "The effect source is realized on a different canvas device."); - } - - return false; - } - - // Try to realize the image from the input source - hresult = canvasImageInterop.Get()->GetD2DImage( - device: canvasDevice, - deviceContext: deviceContext, - flags: flags, - targetDpi: targetDpi, - realizeDpi: &realizedDpi, - ppImage: d2D1Image.GetAddressOf()); - - // Unless requested, a failure to retrieve the image should just bubble up the HRESULT in an exception - if ((flags & WIN2D_GET_D2D_IMAGE_FLAGS_UNREALIZE_ON_FAILURE) == WIN2D_GET_D2D_IMAGE_FLAGS_NONE) - { - hresult.Assert(); - } - } - else if ((flags & WIN2D_GET_D2D_IMAGE_FLAGS_ALLOW_NULL_EFFECT_INPUTS) == WIN2D_GET_D2D_IMAGE_FLAGS_NONE) - { - // If the source is null and this is not explicitly allowed, the invocation is not valid - ThrowHelper.ThrowArgumentNullException(nameof(value), "The effect source cannot be null."); - } - - // Save the managed wrapper and realized image - source.SetWrapperAndResource(value, d2D1Image.Get()); - - // TODO: handle DPI compensation - - // Set the actual effect input - d2D1Effect.SetInput(index: (uint)index, input: d2D1Image.Get()); - - return true; - } - /// /// Gets the instance from a given object. /// diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index e2afddb4..957d6c4a 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -8,6 +8,7 @@ using ComputeSharp.D2D1.Uwp.Extensions; using ComputeSharp.Interop; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; +using Windows.Graphics.Effects; using static ABI.Microsoft.Graphics.Canvas.WIN2D_GET_D2D_IMAGE_FLAGS; using Win32 = TerraFX.Interop.Windows.Windows; @@ -159,7 +160,22 @@ unsafe partial class PixelShaderEffect /// /// Unrealizes the currently realized object. /// - private void Unrealize() + /// The value to set for . + /// The index of the source to get or set. + private void Unrealize(IGraphicsEffectSource source, int index) + { + // Unrealize the effect and indicate to the logic to skip the source at the current index. + // That is, there is no need to marshal it back to the cache, as we're about to do that here. + Unrealize(index); + + // Once the effect is unrealized, also update the cached source managed wrapper + Sources.Storage[index].SetWrapper(source); + } + + /// + /// Unrealizes the currently realized object. + /// + private void Unrealize(int? sourceIndexToSkip = null) { // If there is no ID2D1Effect object, there is nothing left to do if (this.d2D1Effect.Get() is null) @@ -176,7 +192,22 @@ unsafe partial class PixelShaderEffect this.cacheOutput = this.d2D1Effect.Get()->GetCachedProperty(); this.d2D1BufferPrecision = this.d2D1Effect.Get()->GetPrecisionProperty(); - // TODO: read back D2D sources from the effect + // Loop over all effect inputs and update the cache back as well + for (int i = 0; i < 16; i++) + { + // If this index has been explicitly requested to be skipped, just dispose the source reference. + // This is the case when the effect is being unrealized, and callers will set this value on their own. + if (i == sourceIndexToSkip) + { + Sources.Storage[i].Dispose(); + } + else + { + // Otherwise, just get the input, which will automatically update the cached values. The + // returned IGraphicsEffectSource managed wrapper is not used here and is safe to ignore. + _ = GetD2DInput(i); + } + } // Finally release the effect as well this.d2D1Effect.Dispose(); diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.Sources.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.Sources.cs new file mode 100644 index 00000000..6eb2d18b --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.Sources.cs @@ -0,0 +1,211 @@ +using System.Runtime.InteropServices; +using ABI.Microsoft.Graphics.Canvas; +using ComputeSharp.D2D1.Extensions; +using ComputeSharp.D2D1.Helpers; +using ComputeSharp.D2D1.Uwp.Buffers; +using ComputeSharp.D2D1.Uwp.Extensions; +using ComputeSharp.Interop; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using Windows.Graphics.Effects; +using static ABI.Microsoft.Graphics.Canvas.WIN2D_GET_D2D_IMAGE_FLAGS; +using Win32 = TerraFX.Interop.Windows.Windows; + +namespace ComputeSharp.D2D1.Uwp; + +/// +unsafe partial class PixelShaderEffect +{ + /// + /// Gets the marshalled value for . + /// + /// The index of the source to get or set. + /// The marshalled value for . + private IGraphicsEffectSource? GetSource(int index) + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + return this.d2D1Effect.Get() switch + { + not null => GetD2DInput(index), + _ => Sources.Storage[index].GetWrapper() + }; + } + } + + /// + /// Sets the marshalled value for . + /// + /// The value to set for . + /// The index of the source to get or set. + private void SetSource(IGraphicsEffectSource? value, int index) + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); + + lock (this.lockObject) + { + ref SourceReference source = ref Sources.Storage[index]; + + if (this.d2D1Effect.Get() is not null) + { + const WIN2D_GET_D2D_IMAGE_FLAGS flags = + WIN2D_GET_D2D_IMAGE_FLAGS_MINIMAL_REALIZATION | + WIN2D_GET_D2D_IMAGE_FLAGS_ALLOW_NULL_EFFECT_INPUTS | + WIN2D_GET_D2D_IMAGE_FLAGS_UNREALIZE_ON_FAILURE; + + // The WIN2D_GET_D2D_IMAGE_FLAGS_UNREALIZE_ON_FAILURE flag is passed, so we just let the effect + // unrealize in case of failure and take no other action (including throwing) if that happens. + _ = SetD2DInput(index, value, flags, targetDpi: 0.0f, d2D1DeviceContext: null); + } + else + { + source.SetWrapper(value); + } + } + } + + /// This method assumes a lock is taken and the effect is already realized. + /// + private IGraphicsEffectSource? GetD2DInput(int index) + { + using ComPtr d2D1Image = default; + + // Get the ID2D1Image input from the effect + this.d2D1Effect.Get()->GetInput( + index: (uint)index, + input: d2D1Image.GetAddressOf()); + + ref SourceReference sourceReference = ref Sources.Storage[index]; + + // Check whether the input had a DPI compensation effect added to it, and skip it if so + if (sourceReference.HasDpiCompensationEffect) + { + // Since a realized effect is the only source of authority for the effect state, we also + // need to check that the actual source is in fact the same that was previous set by the + // managed wrapper. If it is, we get the input and return that (ie. the underlying image). + // If not, we just return it directly and reset the locally stored DPI compensation effect. + if (d2D1Image.Get()->IsSameInstance(sourceReference.GetDpiCompensationEffect())) + { + sourceReference.GetDpiCompensationEffect()->GetInput(0, d2D1Image.ReleaseAndGetAddressOf()); + } + else + { + sourceReference.SetDpiCompensationEffect(null); + } + } + + // Get or create a wrapper for the input image + return sourceReference.GetOrCreateWrapper(null, d2D1Image.Get()); + } + + /// The index of the source to get or set. + /// The value to set for . + /// The flags for . + /// The target DPI for the realized image, if present. + /// The input object to use, if present. + /// Whether the input was set successfully or not. + /// This method assumes a lock is taken and the effect is already realized. + /// + private bool SetD2DInput( + int index, + IGraphicsEffectSource? value, + WIN2D_GET_D2D_IMAGE_FLAGS flags, + float targetDpi, + ID2D1DeviceContext* d2D1DeviceContext) + { + using ComPtr d2D1Image = default; + + float realizedDpi = 0; + + if (value is not null) + { + using ComPtr canvasImageUnknown = default; + + // Get the underlying IUnknown object for the input source + canvasImageUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(value)); + + using ComPtr canvasImageInterop = default; + + // Try to get the ICanvasImageInterop interface from the input source + HRESULT hresult = canvasImageUnknown.CopyTo(canvasImageInterop.GetAddressOf()); + + if (!Win32.SUCCEEDED(hresult)) + { + // Only potentially handle E_NOINTERFACE, always throw in other cases + if (hresult != E.E_NOINTERFACE) + { + Marshal.ThrowExceptionForHR(hresult); + } + + // If unrealization isn't requested for failures, just throw + if ((flags & WIN2D_GET_D2D_IMAGE_FLAGS_UNREALIZE_ON_FAILURE) == WIN2D_GET_D2D_IMAGE_FLAGS_NONE) + { + ThrowHelper.ThrowArgumentException(nameof(value), "The effect source is not valid (it must implement ICanvasImageInterop)."); + } + + Unrealize(value, index); + + return false; + } + + using ComPtr sourceCanvasDevice = default; + + // Get the canvas device the source is realized on, if any + canvasImageInterop.Get()->GetDevice(sourceCanvasDevice.GetAddressOf()).Assert(); + + // If a device was retrieved, it must be the same as the input one. If the source has no device, + // that is fine, as it just means that its underlying D2D image has not been realized yet. + if (sourceCanvasDevice.Get() is not null && !this.canvasDevice.Get()->IsSameInstance(sourceCanvasDevice.Get())) + { + if ((flags & WIN2D_GET_D2D_IMAGE_FLAGS_UNREALIZE_ON_FAILURE) == WIN2D_GET_D2D_IMAGE_FLAGS_NONE) + { + ThrowHelper.ThrowArgumentException(nameof(value), "The effect source is realized on a different canvas device."); + } + + Unrealize(value, index); + + return false; + } + + // Try to realize the image from the input source (this will recurse through the effect graph) + hresult = canvasImageInterop.Get()->GetD2DImage( + device: this.canvasDevice.Get(), + deviceContext: d2D1DeviceContext, + flags: flags, + targetDpi: targetDpi, + realizeDpi: &realizedDpi, + ppImage: d2D1Image.GetAddressOf()); + + // Unless requested, a failure to retrieve the image should just bubble up the HRESULT in an exception + if ((flags & WIN2D_GET_D2D_IMAGE_FLAGS_UNREALIZE_ON_FAILURE) == WIN2D_GET_D2D_IMAGE_FLAGS_NONE) + { + hresult.Assert(); + } + + // If no realized image is available, unrealize the effect + if (d2D1Image.Get() is null) + { + Unrealize(value, index); + + return false; + } + } + else if ((flags & WIN2D_GET_D2D_IMAGE_FLAGS_ALLOW_NULL_EFFECT_INPUTS) == WIN2D_GET_D2D_IMAGE_FLAGS_NONE) + { + // If the source is null and this is not explicitly allowed, the invocation is not valid + ThrowHelper.ThrowArgumentNullException(nameof(value), "The effect source cannot be null."); + } + + // Save the managed wrapper and realized image + Sources.Storage[index].SetWrapperAndResource(value, d2D1Image.Get()); + + // TODO: handle DPI compensation + + // Set the actual effect input + this.d2D1Effect.Get()->SetInput(index: (uint)index, input: d2D1Image.Get()); + + return true; + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs index 3b1f8569..eb9d81d0 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs @@ -1,12 +1,8 @@ -using ABI.Microsoft.Graphics.Canvas; using ComputeSharp.D2D1.Interop; -using ComputeSharp.D2D1.Uwp.Buffers; using ComputeSharp.D2D1.Uwp.Extensions; using ComputeSharp.Interop; using Microsoft.Graphics.Canvas; using TerraFX.Interop.DirectX; -using Windows.Graphics.Effects; -using static ABI.Microsoft.Graphics.Canvas.WIN2D_GET_D2D_IMAGE_FLAGS; namespace ComputeSharp.D2D1.Uwp; @@ -93,67 +89,6 @@ unsafe partial class PixelShaderEffect } } - /// - /// Gets the marshalled value for . - /// - /// The index of the source to get or set. - /// The marshalled value for . - private IGraphicsEffectSource? GetSource(int index) - { - using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); - - lock (this.lockObject) - { - ref SourceReference source = ref Sources.Storage[index]; - - return this.d2D1Effect.Get() switch - { - not null => this.d2D1Effect.Get()->GetSource(this.canvasDevice.Get(), ref source, index), - _ => source.GetWrapper() - }; - } - } - - /// - /// Sets the marshalled value for . - /// - /// The value to set for . - /// The index of the source to get or set. - private void SetSource(IGraphicsEffectSource? value, int index) - { - using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); - - lock (this.lockObject) - { - ref SourceReference source = ref Sources.Storage[index]; - - if (this.d2D1Effect.Get() is not null) - { - const WIN2D_GET_D2D_IMAGE_FLAGS sourceFlags = - WIN2D_GET_D2D_IMAGE_FLAGS_MINIMAL_REALIZATION | - WIN2D_GET_D2D_IMAGE_FLAGS_ALLOW_NULL_EFFECT_INPUTS | - WIN2D_GET_D2D_IMAGE_FLAGS_UNREALIZE_ON_FAILURE; - - // Try to set the source, and unrealize if the operation failed - if (!this.d2D1Effect.Get()->TrySetSource( - canvasDevice: this.canvasDevice.Get(), - deviceContext: null, - flags: sourceFlags, - targetDpi: 0, - value: value, - source: ref source, - index: index)) - { - Unrealize(); - } - } - else - { - source.SetWrapper(value); - } - } - } - /// /// Gets the marshalled value for . /// From 4423e0d0153a21e0649587419a201c1b3ec549f2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 8 Dec 2022 15:24:04 +0100 Subject: [PATCH 37/59] Implement RefreshInputs method --- .../Buffers/SourceReference.cs | 19 ++++++ ...ixelShaderEffect{T}.ICanvasImageInterop.cs | 63 +++++++++++++++++-- 2 files changed, 77 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.D2D1.Uwp/Buffers/SourceReference.cs b/src/ComputeSharp.D2D1.Uwp/Buffers/SourceReference.cs index 25764282..09096450 100644 --- a/src/ComputeSharp.D2D1.Uwp/Buffers/SourceReference.cs +++ b/src/ComputeSharp.D2D1.Uwp/Buffers/SourceReference.cs @@ -154,6 +154,25 @@ internal unsafe struct SourceReference : IDisposable return this.graphicsEffectSourceWrapper; } + /// + /// Updates the underlying resource, if needed. + /// This is used after a potential re-realization of a lazily bound effect. + /// + /// The input object. + /// Whether the resource has changed or not. + public bool UpdateResource(ID2D1Image* d2D1Image) + { + if (d2D1Image->IsSameInstance(this.d2D1ImageSource.Get())) + { + return false; + } + + this.d2D1ImageSource.Dispose(); + this.d2D1ImageSource = new ComPtr(d2D1Image); + + return true; + } + /// public void Dispose() { diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index 957d6c4a..3f29f9b5 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -1,7 +1,9 @@ using System; +using System.Runtime.InteropServices; using System.Threading; using ABI.Microsoft.Graphics.Canvas; using ComputeSharp.D2D1.Extensions; +using ComputeSharp.D2D1.Helpers; using ComputeSharp.D2D1.Interop; using ComputeSharp.D2D1.Interop.Effects; using ComputeSharp.D2D1.Uwp.Extensions; @@ -283,10 +285,6 @@ unsafe partial class PixelShaderEffect D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(this.d2D1Effect.Get(), resourceTextureManager, i); } } - - // TODO: port base CanvasEffect::Realize logic - - // TODO: transfer properties (eg. D2D1ResourceTextureManager-s) } /// @@ -297,6 +295,61 @@ unsafe partial class PixelShaderEffect /// The instance in use. private void RefreshInputs(WIN2D_GET_D2D_IMAGE_FLAGS flags, float targetDpi, ID2D1DeviceContext* deviceContext) { - // TODO + for (int i = 0; i < 16; i++) + { + // Retrieve the managed wrapper for the current source + IGraphicsEffectSource? source = GetD2DInput(i); + + if (source is null) + { + // If the source is null and that is not valid here (eg. when drawing), just throw + if ((flags & WIN2D_GET_D2D_IMAGE_FLAGS_ALLOW_NULL_EFFECT_INPUTS) == WIN2D_GET_D2D_IMAGE_FLAGS_NONE) + { + ThrowHelper.ThrowInvalidOperationException("The effect has one or more sources set to null, and null effect inputs are not valid at this time."); + } + } + else + { + using ComPtr canvasImageInteropUnknown = default; + using ComPtr canvasImageInterop = default; + + // Get the underlying IUnknown object for the current source + canvasImageInteropUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(source)); + + // Convert to ICanvasImageInterop (this must always succeed, and throws if it doesn't) + canvasImageInteropUnknown.CopyTo(canvasImageInterop.GetAddressOf()).Assert(); + + using ComPtr d2D1Image = default; + + float realizedDpi; + + // Invoke GetD2DImage on the underlying object (either a built-in effect or a custom one) + HRESULT hresult = canvasImageInterop.Get()->GetD2DImage( + device: this.canvasDevice.Get(), + deviceContext: deviceContext, + flags: flags, + targetDpi: targetDpi, + realizeDpi: &realizedDpi, + ppImage: d2D1Image.GetAddressOf()); + + // To match the behavior of ICanvasImageInternal::GetD2DImage in case of failure, check if the flags being used did have the flag + // WIN2D_GET_D2D_IMAGE_FLAGS_UNREALIZE_ON_FAILURE set. If not, and the call failed, then we explicitly throw from the returned HRESULT. + if ((flags & WIN2D_GET_D2D_IMAGE_FLAGS_UNREALIZE_ON_FAILURE) == WIN2D_GET_D2D_IMAGE_FLAGS_NONE) + { + Marshal.ThrowExceptionForHR(hresult); + } + + bool isDifferentResource = Sources.Storage[i].UpdateResource(d2D1Image.Get()); + bool isDifferentDpi = false; + + // TODO: handle DPI compensation + + // If the source or the DPI setting has changed, also update the D2D effect graph + if (isDifferentResource || isDifferentDpi) + { + this.d2D1Effect.Get()->SetInput(index: (uint)i, input: d2D1Image.Get()); + } + } + } } } \ No newline at end of file From ab998c622851a3c49e2aa4dedfb3282ae2989edf Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 8 Dec 2022 16:56:35 +0100 Subject: [PATCH 38/59] Make ICanvasImage methods implicitly implemented --- .../PixelShaderEffect{T}.ICanvasImage.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImage.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImage.cs index 62f2c3d9..0b31ffe3 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImage.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImage.cs @@ -14,13 +14,13 @@ namespace ComputeSharp.D2D1.Uwp; unsafe partial class PixelShaderEffect { /// - Rect ICanvasImage.GetBounds(ICanvasResourceCreator resourceCreator) + public Rect GetBounds(ICanvasResourceCreator resourceCreator) { return GetBounds(resourceCreator, null); } /// - Rect ICanvasImage.GetBounds(ICanvasResourceCreator resourceCreator, Matrix3x2 transform) + public Rect GetBounds(ICanvasResourceCreator resourceCreator, Matrix3x2 transform) { return GetBounds(resourceCreator, &transform); } From 49ecac2169fd83199c43dc49bb927ea4f6a1a711 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 8 Dec 2022 17:46:48 +0100 Subject: [PATCH 39/59] Add bounds checks for sources and resource texture managers --- Directory.Build.props | 7 ++ ...eArrayResourceTextureDescriptionsLoader.cs | 53 +++++++++++++ ...itmaskResourceTextureDescriptionsLoader.cs | 43 ++++++++++ ...ixelShaderEffect{T}.ICanvasImageInterop.cs | 13 +-- ...erties.ResourceTextureManagerCollection.cs | 79 ++++++++++++++++++- ...PixelShaderEffect{T}.Properties.Sources.cs | 36 ++++++++- 6 files changed, 221 insertions(+), 10 deletions(-) create mode 100644 src/ComputeSharp.D2D1.Uwp/Loaders/D2D1ImmutableArrayResourceTextureDescriptionsLoader.cs create mode 100644 src/ComputeSharp.D2D1.Uwp/Loaders/D2D1IndexBitmaskResourceTextureDescriptionsLoader.cs diff --git a/Directory.Build.props b/Directory.Build.props index 11df4cd6..a648d365 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -40,6 +40,13 @@ See: https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1060. --> $(NoWarn);CA1060 + + + $(NoWarn);CS8500 diff --git a/src/ComputeSharp.D2D1.Uwp/Loaders/D2D1ImmutableArrayResourceTextureDescriptionsLoader.cs b/src/ComputeSharp.D2D1.Uwp/Loaders/D2D1ImmutableArrayResourceTextureDescriptionsLoader.cs new file mode 100644 index 00000000..4399ec7c --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/Loaders/D2D1ImmutableArrayResourceTextureDescriptionsLoader.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Immutable; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.Interop; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.Shaders.Loaders; + +/// +/// A resource texture index array loader for D2D1 pixel shaders. +/// +internal struct D2D1ImmutableArrayResourceTextureDescriptionsLoader : ID2D1ResourceTextureDescriptionsLoader +{ + /// + /// The array of indices for resource textures for the current effect. + /// + private ImmutableArray indices; + + /// + /// Gets the resulting array of indices for resource textures for the current effect. + /// + /// An array of indices for resource textures for the current effect. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ImmutableArray GetResultingIndices() + { + return this.indices; + } + + /// + unsafe void ID2D1ResourceTextureDescriptionsLoader.LoadResourceTextureDescriptions(ReadOnlySpan data) + { + if (data.IsEmpty) + { + this.indices = ImmutableArray.Empty; + } + else + { + ReadOnlySpan descriptions = MemoryMarshal.Cast(data); + + int[] indices = new int[descriptions.Length]; + + for (int i = 0; i < descriptions.Length; i++) + { + indices[i] = descriptions[i].Index; + } + + this.indices = *(ImmutableArray*)&indices; + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/Loaders/D2D1IndexBitmaskResourceTextureDescriptionsLoader.cs b/src/ComputeSharp.D2D1.Uwp/Loaders/D2D1IndexBitmaskResourceTextureDescriptionsLoader.cs new file mode 100644 index 00000000..3ceecfe4 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/Loaders/D2D1IndexBitmaskResourceTextureDescriptionsLoader.cs @@ -0,0 +1,43 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.Interop; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.Shaders.Loaders; + +/// +/// A resource texture index bitmask loader for D2D1 pixel shaders. +/// +internal struct D2D1IndexBitmaskResourceTextureDescriptionsLoader : ID2D1ResourceTextureDescriptionsLoader +{ + /// + /// The bitmask of indices for resource textures in the target shader. + /// + private int indexBitmask; + + /// + /// Gets the resulting bitmask of indices for resource textures in the target shader. + /// + /// A bitmask of indices for resource textures in the target shader. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int GetResultingIndexBitmask() + { + return this.indexBitmask; + } + + /// + void ID2D1ResourceTextureDescriptionsLoader.LoadResourceTextureDescriptions(ReadOnlySpan data) + { + int indexBitmask = 0; + + foreach (ref readonly D2D1ResourceTextureDescription description in MemoryMarshal.Cast(data)) + { + indexBitmask |= 1 << description.Index; + } + + this.indexBitmask = indexBitmask; + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index 3f29f9b5..b8157ebf 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -195,7 +195,7 @@ unsafe partial class PixelShaderEffect this.d2D1BufferPrecision = this.d2D1Effect.Get()->GetPrecisionProperty(); // Loop over all effect inputs and update the cache back as well - for (int i = 0; i < 16; i++) + for (int i = 0; i < SourceCollection.Count; i++) { // If this index has been explicitly requested to be skipped, just dispose the source reference. // This is the case when the effect is being unrealized, and callers will set this value on their own. @@ -277,12 +277,13 @@ unsafe partial class PixelShaderEffect this.d2D1Effect.Get()->SetPrecisionProperty(this.d2D1BufferPrecision); } - // Set all available resource texture managers (only set those that are not null, as they're all null by default anyway) - for (int i = 0; i < 16; i++) + // Set all available resource texture managers (only set those that are not null, as they're all null by default anyway). + // The loop only goes over the indices of valid slots for resource textures for the current effect, and ignores the others. + foreach (int index in ResourceTextureManagerCollection.Indices) { - if (ResourceTextureManagers.Storage[i] is D2D1ResourceTextureManager resourceTextureManager) + if (ResourceTextureManagers.Storage[index] is D2D1ResourceTextureManager resourceTextureManager) { - D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(this.d2D1Effect.Get(), resourceTextureManager, i); + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(this.d2D1Effect.Get(), resourceTextureManager, index); } } } @@ -295,7 +296,7 @@ unsafe partial class PixelShaderEffect /// The instance in use. private void RefreshInputs(WIN2D_GET_D2D_IMAGE_FLAGS flags, float targetDpi, ID2D1DeviceContext* deviceContext) { - for (int i = 0; i < 16; i++) + for (int i = 0; i < SourceCollection.Count; i++) { // Retrieve the managed wrapper for the current source IGraphicsEffectSource? source = GetD2DInput(i); diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs index e214a282..f0d90bd3 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs @@ -1,8 +1,14 @@ using System; +using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using ComputeSharp.D2D1.Helpers; using ComputeSharp.D2D1.Interop; +using ComputeSharp.D2D1.Shaders.Loaders; using ComputeSharp.D2D1.Uwp.Buffers; +#pragma warning disable CS0618 + namespace ComputeSharp.D2D1.Uwp; /// @@ -13,6 +19,11 @@ partial class PixelShaderEffect /// public sealed class ResourceTextureManagerCollection { + /// + /// The bitmask of valid indices for resource texture managers in the current shader type. + /// + private static readonly int IndexBitmask = GetIndexBitmask(); + /// /// The fixed buffer of instances. /// @@ -27,6 +38,11 @@ partial class PixelShaderEffect Owner = owner; } + /// + /// Gets the collection of valid resource texture indices for the current effect. + /// + internal static ImmutableArray Indices { get; } = GetIndices(); + /// /// Gets or sets the object at a specified index. /// @@ -37,8 +53,23 @@ partial class PixelShaderEffect [DisallowNull] public D2D1ResourceTextureManager? this[int index] { - get => Owner.GetResourceTextureManager(index); - set => Owner.SetResourceTextureManager(value, index); + get + { + ValidateIndex(index); + + return Owner.GetResourceTextureManager(index); + } + set + { + if (value is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(value), "Input resource texture managers cannot be null."); + } + + ValidateIndex(index); + + Owner.SetResourceTextureManager(value, index); + } } /// @@ -50,5 +81,49 @@ partial class PixelShaderEffect /// Gets a reference to the value containing the available -s. /// internal ref ResourceTextureManagerBuffer Storage => ref this.fixedBuffer; + + /// + /// Validates the input index for . + /// + /// The index to validate. + /// Thrown if is out of range. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ValidateIndex(int index) + { + if ((uint)index >= 16 || (IndexBitmask & (1 << index)) == 0) + { + ThrowHelper.ThrowArgumentOutOfRangeException(nameof(index), "The input index is not a valid resource texture manager index for the current effect."); + } + } + + /// + /// Gets the bitmask of indices for resource textures in the target shader. + /// + /// The bitmask of indices for resource textures in the target shader. + private static int GetIndexBitmask() + { + D2D1IndexBitmaskResourceTextureDescriptionsLoader bitmaskLoader = default; + + Unsafe.SkipInit(out T shader); + + shader.LoadResourceTextureDescriptions(ref bitmaskLoader); + + return bitmaskLoader.GetResultingIndexBitmask(); + } + + /// + /// Gets the collection of valid indices for the current effect. + /// + /// The collection of valid indices for the current effect. + private static ImmutableArray GetIndices() + { + D2D1ImmutableArrayResourceTextureDescriptionsLoader indicesLoader = default; + + Unsafe.SkipInit(out T shader); + + shader.LoadResourceTextureDescriptions(ref indicesLoader); + + return indicesLoader.GetResultingIndices(); + } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs index b9e0afca..19ccd9c0 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs @@ -1,4 +1,7 @@ using System; +using System.Runtime.CompilerServices; +using ComputeSharp.D2D1.Helpers; +using ComputeSharp.D2D1.Interop; using ComputeSharp.D2D1.Uwp.Buffers; using Windows.Graphics.Effects; @@ -26,6 +29,11 @@ partial class PixelShaderEffect Owner = owner; } + /// + /// Gets the actual input count for the current effect. + /// + internal static int Count { get; } = D2D1PixelShader.GetInputCount(); + /// /// Gets or sets the source at a specified index. /// @@ -34,8 +42,18 @@ partial class PixelShaderEffect /// Thrown if is not a valid index for the current effect. public IGraphicsEffectSource? this[int index] { - get => Owner.GetSource(index); - set => Owner.SetSource(value, index); + get + { + ValidateIndex(index); + + return Owner.GetSource(index); + } + set + { + ValidateIndex(index); + + Owner.SetSource(value, index); + } } /// @@ -47,5 +65,19 @@ partial class PixelShaderEffect /// Gets a reference to the value containing the available -s. /// internal ref GraphicsEffectSourceBuffer Storage => ref this.fixedBuffer; + + /// + /// Validates the input index for . + /// + /// The index to validate. + /// Thrown if is out of range. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ValidateIndex(int index) + { + if ((uint)index >= Count) + { + ThrowHelper.ThrowArgumentOutOfRangeException(nameof(index), "The input index is not a valid source index for the current effect."); + } + } } } \ No newline at end of file From 5c59b021c8879308a543206c34a3288f8b529517 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 8 Dec 2022 19:34:16 +0100 Subject: [PATCH 40/59] Add effect registration check for E_NOTFOUND --- .../PixelShaderEffect{T}.ICanvasImageInterop.cs | 4 +++- src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/E.cs | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index b8157ebf..27a4b599 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -243,7 +243,9 @@ unsafe partial class PixelShaderEffect // Check if creation failed due to the effect not being registered. In that case, register // it and then try again. This is much faster than check whether the effect is registered // manually every time, by enumerating all registered effects for the target device context. - if (hresult == D2DERR.D2DERR_EFFECT_IS_NOT_REGISTERED) + // An unregistered effect can also sometimes return E_NOTFOUND, although it's not documented. + if (hresult == D2DERR.D2DERR_EFFECT_IS_NOT_REGISTERED || + hresult == E.E_NOTFOUND) { // Register the effect with the factory (pass the same D2D1 draw transform mapper factory that was used before) D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory1.Get(), out _); diff --git a/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/E.cs b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/E.cs index 1fef41f8..27cd177d 100644 --- a/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/E.cs +++ b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/E.cs @@ -7,6 +7,9 @@ namespace TerraFX.Interop.Windows; internal static class E { + [NativeTypeName("#define E_NOTFOUND HRESULT_FROM_WIN32(ERROR_NOT_FOUND)")] + public const int E_NOTFOUND = -2147023728; + [NativeTypeName("#define E_NOT_VALID_STATE HRESULT_FROM_WIN32(ERROR_INVALID_STATE)")] public const int E_NOT_VALID_STATE = -2147019873; From 941488a647f827c10efecb795472822ca0b67acb Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 8 Dec 2022 20:38:50 +0100 Subject: [PATCH 41/59] Forward effect sources upon realization --- ...ixelShaderEffect{T}.ICanvasImageInterop.cs | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index 27a4b599..1d9a64b5 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -127,7 +127,12 @@ unsafe partial class PixelShaderEffect // Create the effect, if it doesn't exist already if (this.d2D1Effect.Get() is null) { - Realize(flags, targetDpi, deviceContext); + if (!Realize(flags, targetDpi, deviceContext)) + { + *ppImage = null; + + return E.E_FAIL; + } } else if (!flags.HasFlag(WIN2D_GET_D2D_IMAGE_FLAGS_MINIMAL_REALIZATION)) { @@ -221,7 +226,8 @@ unsafe partial class PixelShaderEffect /// The current flags in use. /// The target DPI in use. /// The instance in use. - private void Realize(WIN2D_GET_D2D_IMAGE_FLAGS flags, float targetDpi, ID2D1DeviceContext* deviceContext) + /// Whether the effect was realized correctly. + private bool Realize(WIN2D_GET_D2D_IMAGE_FLAGS flags, float targetDpi, ID2D1DeviceContext* deviceContext) { using ComPtr d2D1Factory = default; @@ -279,6 +285,20 @@ unsafe partial class PixelShaderEffect this.d2D1Effect.Get()->SetPrecisionProperty(this.d2D1BufferPrecision); } + // Forward all available sources (the effect is being created now, so no need to validate the underlying resources) + for (int i = 0; i < SourceCollection.Count; i++) + { + if (!SetD2DInput( + index: i, + value: Sources.Storage[0].GetWrapper(), + flags: flags, + targetDpi: targetDpi, + d2D1DeviceContext: deviceContext)) + { + return false; + } + } + // Set all available resource texture managers (only set those that are not null, as they're all null by default anyway). // The loop only goes over the indices of valid slots for resource textures for the current effect, and ignores the others. foreach (int index in ResourceTextureManagerCollection.Indices) @@ -288,6 +308,8 @@ unsafe partial class PixelShaderEffect D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(this.d2D1Effect.Get(), resourceTextureManager, index); } } + + return true; } /// From d8bdd8961799ff4da4f339a064ab877fac649a86 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 9 Dec 2022 02:03:13 +0100 Subject: [PATCH 42/59] Port CanvasEffect::ApplyDpiCompensation logic --- ...ixelShaderEffect{T}.ICanvasImageInterop.cs | 9 +- ...derEffect{T}.Properties.Interop.Sources.cs | 136 +++++++++++++++++- .../DirectX/um/d2d1effects/CLSID.cs | 24 ++++ .../um/d2d1effects/D2D1_BORDER_MODE.cs | 13 ++ ...D2D1_DPICOMPENSATION_INTERPOLATION_MODE.cs | 17 +++ .../d2d1effects/D2D1_DPICOMPENSATION_PROP.cs | 14 ++ .../DirectX/um/dcommon/D2D_VECTOR_2F.cs | 12 ++ .../TerraFX.Interop.Windows.D2D1.projitems | 4 + 8 files changed, 226 insertions(+), 3 deletions(-) create mode 100644 src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/D2D1_BORDER_MODE.cs create mode 100644 src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/D2D1_DPICOMPENSATION_INTERPOLATION_MODE.cs create mode 100644 src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/D2D1_DPICOMPENSATION_PROP.cs create mode 100644 src/TerraFX.Interop.Windows.D2D1/DirectX/um/dcommon/D2D_VECTOR_2F.cs diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index 1d9a64b5..1510d1ed 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -365,9 +365,14 @@ unsafe partial class PixelShaderEffect } bool isDifferentResource = Sources.Storage[i].UpdateResource(d2D1Image.Get()); - bool isDifferentDpi = false; - // TODO: handle DPI compensation + bool isDifferentDpi = ApplyDpiCompensation( + index: i, + d2D1Image: ref *&d2D1Image, + inputDpi: realizedDpi, + flags: flags, + targetDpi: targetDpi, + d2D1DeviceContext: deviceContext); // If the source or the DPI setting has changed, also update the D2D effect graph if (isDifferentResource || isDifferentDpi) diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.Sources.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.Sources.cs index 6eb2d18b..16d5dbb8 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.Sources.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.Sources.cs @@ -1,3 +1,5 @@ +using System; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ABI.Microsoft.Graphics.Canvas; using ComputeSharp.D2D1.Extensions; @@ -9,6 +11,10 @@ using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using Windows.Graphics.Effects; using static ABI.Microsoft.Graphics.Canvas.WIN2D_GET_D2D_IMAGE_FLAGS; +using static TerraFX.Interop.DirectX.D2D1_BORDER_MODE; +using static TerraFX.Interop.DirectX.D2D1_DPICOMPENSATION_INTERPOLATION_MODE; +using static TerraFX.Interop.DirectX.D2D1_DPICOMPENSATION_PROP; +using static TerraFX.Interop.DirectX.D2D1_PROPERTY_TYPE; using Win32 = TerraFX.Interop.Windows.Windows; namespace ComputeSharp.D2D1.Uwp; @@ -201,11 +207,139 @@ unsafe partial class PixelShaderEffect // Save the managed wrapper and realized image Sources.Storage[index].SetWrapperAndResource(value, d2D1Image.Get()); - // TODO: handle DPI compensation + // Handle DPI compensation (the return is ignored here as whether DPI compensation was applied doesn't matter) + _ = ApplyDpiCompensation( + index: index, + d2D1Image: ref *&d2D1Image, + inputDpi: realizedDpi, + flags: flags, + targetDpi: targetDpi, + d2D1DeviceContext: d2D1DeviceContext); // Set the actual effect input this.d2D1Effect.Get()->SetInput(index: (uint)index, input: d2D1Image.Get()); return true; } + + /// + /// Applies a DPI compensation effect onto a realized image, if needed. + /// + /// The index of the source being processed. + /// A reference to the realized source (this might be replaced if DPI compensation is added). + /// The input DPU for . + /// The flags for . + /// The target DPI for the realized image, if present. + /// The input object to use, if present. + /// Whether the DPI configuration has changed. + private bool ApplyDpiCompensation( + int index, + ref ComPtr d2D1Image, + float inputDpi, + WIN2D_GET_D2D_IMAGE_FLAGS flags, + float targetDpi, + ID2D1DeviceContext* d2D1DeviceContext) + { + ref SourceReference sourceReference = ref Sources.Storage[index]; + + bool isDpiCompensationNeeded; + + // Detemine whether DPI compensation is needed (direct port of Win2D's CanvasEffect::ApplyDpiCompensation) + if ((flags & WIN2D_GET_D2D_IMAGE_FLAGS_MINIMAL_REALIZATION) != WIN2D_GET_D2D_IMAGE_FLAGS_NONE) + { + // In minimal mode, we don't yet know the target DPI. For instance this occurs when setting an + // effect as the source of an image brush. We'll fix up later when the brush is drawn to a device + // context, at which point the real DPI is known. Since we don't yet know whether to include + // compensation, we just preserve the existing state. This avoids repeated recreation during + // set-draw-set-draw sequences. + isDpiCompensationNeeded = sourceReference.HasDpiCompensationEffect && (inputDpi != 0); + } + else + { + bool neverCompensate = (flags & WIN2D_GET_D2D_IMAGE_FLAGS_NEVER_INSERT_DPI_COMPENSATION) != WIN2D_GET_D2D_IMAGE_FLAGS_NONE; + bool alwaysCompensate = (flags & WIN2D_GET_D2D_IMAGE_FLAGS_ALWAYS_INSERT_DPI_COMPENSATION) != WIN2D_GET_D2D_IMAGE_FLAGS_NONE; + + // We need DPI compensation if: + // - The input has a fixed DPI + // - We were not told never to include it + // - Either we were told to always include it, or the input DPI is different from the target + isDpiCompensationNeeded = (inputDpi != 0) && !neverCompensate && (alwaysCompensate || (inputDpi != targetDpi)); + + // Early out if we are already in the right state + if (isDpiCompensationNeeded == sourceReference.HasDpiCompensationEffect) + { + return false; + } + } + + // Apply the determined DPI compensation configuration + if (isDpiCompensationNeeded) + { + using ComPtr d2D1EffectDpiCompensation = default; + + // Create an ID2D1Effect for the DPI compensation, if there isn't one already + if (!sourceReference.HasDpiCompensationEffect) + { + // We need to create a DPI compensation effect, so a device context must be available + if (d2D1DeviceContext is null) + { + Marshal.ThrowExceptionForHR(E.E_POINTER); + } + + // Create the DPI compensation effect + d2D1DeviceContext->CreateEffect( + effectId: (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_D2D1DpiCompensation)), + effect: d2D1EffectDpiCompensation.GetAddressOf()).Assert(); + + D2D1_BORDER_MODE d2D1BorderMode = D2D1_BORDER_MODE_HARD; + D2D1_DPICOMPENSATION_INTERPOLATION_MODE d2D1DpiCompensationInterpolationMode = D2D1_DPICOMPENSATION_INTERPOLATION_MODE_LINEAR; + + // Set the border mode to hard + d2D1EffectDpiCompensation.Get()->SetValue( + index: (uint)D2D1_DPICOMPENSATION_PROP_BORDER_MODE, + type: D2D1_PROPERTY_TYPE_UNKNOWN, + data: (byte*)&d2D1BorderMode, + dataSize: sizeof(D2D1_BORDER_MODE)).Assert(); + + // Set the interpolation mode to linear + d2D1EffectDpiCompensation.Get()->SetValue( + index: (uint)D2D1_DPICOMPENSATION_PROP_INTERPOLATION_MODE, + type: D2D1_PROPERTY_TYPE_UNKNOWN, + data: (byte*)&d2D1DpiCompensationInterpolationMode, + dataSize: sizeof(D2D1_DPICOMPENSATION_INTERPOLATION_MODE)).Assert(); + + // Store the DPI effect for later use + sourceReference.SetDpiCompensationEffect(d2D1EffectDpiCompensation.Get()); + } + else + { + // Just reuse the existing DPI effect otherwise + d2D1EffectDpiCompensation.Attach(new ComPtr(sourceReference.GetDpiCompensationEffect()).Get()); + } + + // Set the input image as source for the DPI compensation effect + sourceReference.GetDpiCompensationEffect()->SetInput(index: (uint)index, input: d2D1Image.Get()); + + D2D_VECTOR_2F d2DVectorDpi; + d2DVectorDpi.x = inputDpi; + d2DVectorDpi.y = inputDpi; + + // Set the DPI setting + sourceReference.GetDpiCompensationEffect()->SetValue( + index: (uint)D2D1_DPICOMPENSATION_PROP_INPUT_DPI, + type: D2D1_PROPERTY_TYPE_UNKNOWN, + data: (byte*)&d2DVectorDpi, + dataSize: (uint)sizeof(D2D_VECTOR_2F)).Assert(); + + // Substitute the input image with the DPI compensation effect + d2D1EffectDpiCompensation.CopyTo(ref d2D1Image).Assert(); + } + else + { + // Ensure the existing effect is released, if present + sourceReference.SetDpiCompensationEffect(null); + } + + return true; + } } \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/CLSID.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/CLSID.cs index dbaba616..bd310a66 100644 --- a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/CLSID.cs +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/CLSID.cs @@ -34,4 +34,28 @@ internal static partial class CLSID return ref Unsafe.As(ref MemoryMarshal.GetReference(data)); } } + + [NativeTypeName("const GUID")] + public static ref readonly Guid CLSID_D2D1DpiCompensation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + ReadOnlySpan data = new byte[] { + 0xC7, 0xC5, 0x26, 0x6C, + 0xE0, 0x34, + 0xFC, 0x46, + 0x9C, + 0xFD, + 0xE5, + 0x82, + 0x37, + 0x06, + 0xE2, + 0x28 + }; + + return ref Unsafe.As(ref MemoryMarshal.GetReference(data)); + } + } } \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/D2D1_BORDER_MODE.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/D2D1_BORDER_MODE.cs new file mode 100644 index 00000000..372c5be9 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/D2D1_BORDER_MODE.cs @@ -0,0 +1,13 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effects.h in the Windows SDK for Windows 10.0.22621.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.DirectX; + +internal enum D2D1_BORDER_MODE : uint +{ + D2D1_BORDER_MODE_SOFT = 0, + D2D1_BORDER_MODE_HARD = 1, + D2D1_BORDER_MODE_FORCE_DWORD = 0xffffffff, +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/D2D1_DPICOMPENSATION_INTERPOLATION_MODE.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/D2D1_DPICOMPENSATION_INTERPOLATION_MODE.cs new file mode 100644 index 00000000..6897b0d0 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/D2D1_DPICOMPENSATION_INTERPOLATION_MODE.cs @@ -0,0 +1,17 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effects.h in the Windows SDK for Windows 10.0.22621.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.DirectX; + +internal enum D2D1_DPICOMPENSATION_INTERPOLATION_MODE : uint +{ + D2D1_DPICOMPENSATION_INTERPOLATION_MODE_NEAREST_NEIGHBOR = 0, + D2D1_DPICOMPENSATION_INTERPOLATION_MODE_LINEAR = 1, + D2D1_DPICOMPENSATION_INTERPOLATION_MODE_CUBIC = 2, + D2D1_DPICOMPENSATION_INTERPOLATION_MODE_MULTI_SAMPLE_LINEAR = 3, + D2D1_DPICOMPENSATION_INTERPOLATION_MODE_ANISOTROPIC = 4, + D2D1_DPICOMPENSATION_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC = 5, + D2D1_DPICOMPENSATION_INTERPOLATION_MODE_FORCE_DWORD = 0xffffffff, +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/D2D1_DPICOMPENSATION_PROP.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/D2D1_DPICOMPENSATION_PROP.cs new file mode 100644 index 00000000..7825110e --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/D2D1_DPICOMPENSATION_PROP.cs @@ -0,0 +1,14 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effects.h in the Windows SDK for Windows 10.0.22621.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.DirectX; + +internal enum D2D1_DPICOMPENSATION_PROP : uint +{ + D2D1_DPICOMPENSATION_PROP_INTERPOLATION_MODE = 0, + D2D1_DPICOMPENSATION_PROP_BORDER_MODE = 1, + D2D1_DPICOMPENSATION_PROP_INPUT_DPI = 2, + D2D1_DPICOMPENSATION_PROP_FORCE_DWORD = 0xffffffff, +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/dcommon/D2D_VECTOR_2F.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/dcommon/D2D_VECTOR_2F.cs new file mode 100644 index 00000000..e52724d5 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/dcommon/D2D_VECTOR_2F.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 um/dcommon.h in the Windows SDK for Windows 10.0.22621.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.DirectX; + +internal partial struct D2D_VECTOR_2F +{ + public float x; + public float y; +} \ 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 977bcb66..478f8ba5 100644 --- a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems +++ b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems @@ -27,6 +27,9 @@ + + + @@ -53,6 +56,7 @@ + From 6f42a3039ff7adc528b3e7696a050f272bb24572 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Dec 2022 02:32:03 +0100 Subject: [PATCH 43/59] Add ICanvasFactoryNative binding type --- .../ICanvasFactoryNative.cs | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs new file mode 100644 index 00000000..0e1f8430 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs @@ -0,0 +1,67 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649, IDE1006 + +namespace ABI.Microsoft.Graphics.Canvas; + +/// +/// The activation factory for . +/// +[Guid("695C440D-04B3-4EDD-BFD9-63E51E9F7202")] +[NativeTypeName("class ICanvasFactoryNative : public IInspectable")] +[NativeInheritance("IInspectable")] +internal unsafe struct ICanvasFactoryNative +{ + public void** lpVtbl; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(0)] + public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[0])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(1)] + [return: NativeTypeName("ULONG")] + public uint AddRef() + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[1])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this)); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(2)] + [return: NativeTypeName("ULONG")] + public uint Release() + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[2])((ICanvasResourceWrapperNative*)Unsafe.AsPointer(ref this)); + } + + /// + /// Gets or creates an IInspectable Win2D wrapper for a given native D2D resource. + /// + /// The input canvas device (as a marshalled ). + /// The input native resource to create a wrapper for. + /// The realization DPIs for + /// The resulting wrapper for . + /// The for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(6)] + [return: NativeTypeName("ULONG")] + public HRESULT GetOrCreate(ICanvasDevice* device, IUnknown* resource, float dpi, [NativeTypeName("IInspectable**")] void** wrapper) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[6])( + (ICanvasFactoryNative*)Unsafe.AsPointer(ref this), + device, + resource, + dpi, + wrapper); + } +} \ No newline at end of file From 2611e9b1d112d123f0da64ccabe4f1be47606b5a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Dec 2022 02:36:17 +0100 Subject: [PATCH 44/59] Add missing WinRT bindings --- .../TerraFX.Interop.Windows.D2D1.projitems | 4 ++++ .../WinRT/winrt/hstring/HSTRING_HEADER.cs | 17 +++++++++++++++++ .../WinRT/winrt/roapi/WinRT.cs | 16 ++++++++++++++++ .../WinRT/winrt/winstring/WinRT.cs | 15 +++++++++++++++ .../Windows/other/helper-types/HSTRING.cs | 13 +++++++++++++ 5 files changed, 65 insertions(+) create mode 100644 src/TerraFX.Interop.Windows.D2D1/WinRT/winrt/hstring/HSTRING_HEADER.cs create mode 100644 src/TerraFX.Interop.Windows.D2D1/WinRT/winrt/roapi/WinRT.cs create mode 100644 src/TerraFX.Interop.Windows.D2D1/WinRT/winrt/winstring/WinRT.cs create mode 100644 src/TerraFX.Interop.Windows.D2D1/Windows/other/helper-types/HSTRING.cs 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 478f8ba5..cfa82c7b 100644 --- a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems +++ b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems @@ -57,6 +57,7 @@ + @@ -73,5 +74,8 @@ + + + \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/WinRT/winrt/hstring/HSTRING_HEADER.cs b/src/TerraFX.Interop.Windows.D2D1/WinRT/winrt/hstring/HSTRING_HEADER.cs new file mode 100644 index 00000000..c22767c3 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/WinRT/winrt/hstring/HSTRING_HEADER.cs @@ -0,0 +1,17 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from winrt/hstring.h in the Windows SDK for Windows 10.0.22621.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.WinRT; + +internal partial struct HSTRING_HEADER +{ + [NativeTypeName("union (anonymous union at C:/Program Files (x86)/Windows Kits/10/Include/10.0.22621.0/winrt/hstring.h:80:5)")] + public _Reserved_e__Union Reserved; + + public unsafe partial struct _Reserved_e__Union + { + internal fixed byte Reserved1[24]; + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/WinRT/winrt/roapi/WinRT.cs b/src/TerraFX.Interop.Windows.D2D1/WinRT/winrt/roapi/WinRT.cs new file mode 100644 index 00000000..0e955b67 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/WinRT/winrt/roapi/WinRT.cs @@ -0,0 +1,16 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from winrt/roapi.h in the Windows SDK for Windows 10.0.22621.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +namespace TerraFX.Interop.WinRT; + +internal static unsafe partial class WinRT +{ + [DllImport("combase", ExactSpelling = true)] + public static extern HRESULT RoGetActivationFactory(HSTRING activatableClassId, [NativeTypeName("const IID &")] Guid* iid, void** factory); +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/WinRT/winrt/winstring/WinRT.cs b/src/TerraFX.Interop.Windows.D2D1/WinRT/winrt/winstring/WinRT.cs new file mode 100644 index 00000000..ef4c8562 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/WinRT/winrt/winstring/WinRT.cs @@ -0,0 +1,15 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from winrt/winstring.h in the Windows SDK for Windows 10.0.22621.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +namespace TerraFX.Interop.WinRT; + +internal static unsafe partial class WinRT +{ + [DllImport("combase", ExactSpelling = true)] + public static extern HRESULT WindowsCreateStringReference([NativeTypeName("PCWSTR")] ushort* sourceString, [NativeTypeName("UINT32")] uint length, HSTRING_HEADER* hstringHeader, HSTRING* @string); +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/Windows/other/helper-types/HSTRING.cs b/src/TerraFX.Interop.Windows.D2D1/Windows/other/helper-types/HSTRING.cs new file mode 100644 index 00000000..5cc0abeb --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/Windows/other/helper-types/HSTRING.cs @@ -0,0 +1,13 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +namespace TerraFX.Interop.WinRT; + +internal readonly unsafe partial struct HSTRING +{ + public readonly void* Value; + + public HSTRING(void* value) + { + Value = value; + } +} \ No newline at end of file From 4954bec5f41b92dc17dcd9251caf484795c384bc Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Dec 2022 02:58:02 +0100 Subject: [PATCH 45/59] Implement Win2D's ResourceManager::GetOrCreate logic --- .../Buffers/SourceReference.cs | 9 ++- .../Helpers/ResourceManager.cs | 68 +++++++++++++++++++ ...derEffect{T}.Properties.Interop.Sources.cs | 2 +- 3 files changed, 75 insertions(+), 4 deletions(-) create mode 100644 src/ComputeSharp.D2D1.Uwp/Helpers/ResourceManager.cs diff --git a/src/ComputeSharp.D2D1.Uwp/Buffers/SourceReference.cs b/src/ComputeSharp.D2D1.Uwp/Buffers/SourceReference.cs index 09096450..b128c63a 100644 --- a/src/ComputeSharp.D2D1.Uwp/Buffers/SourceReference.cs +++ b/src/ComputeSharp.D2D1.Uwp/Buffers/SourceReference.cs @@ -2,6 +2,7 @@ using System; using System.Runtime.CompilerServices; using ABI.Microsoft.Graphics.Canvas; using ComputeSharp.D2D1.Uwp.Extensions; +using ComputeSharp.D2D1.Uwp.Helpers; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using Windows.Graphics.Effects; @@ -140,12 +141,14 @@ internal unsafe struct SourceReference : IDisposable // If that's not the case, create a new wrapper if the input image is not null if (d2D1Image is not null) { - // m_wrapper = ResourceManager::GetOrCreate(device, resource); - throw new NotImplementedException(); + this.graphicsEffectSourceWrapper = ResourceManager.GetOrCreate( + device: canvasDevice, + resource: (IUnknown*)d2D1Image, + dpi: 0); } else { - this.d2D1ImageSource.Dispose(); + this.graphicsEffectSourceWrapper = null; } this.d2D1ImageSource = new ComPtr(d2D1Image); diff --git a/src/ComputeSharp.D2D1.Uwp/Helpers/ResourceManager.cs b/src/ComputeSharp.D2D1.Uwp/Helpers/ResourceManager.cs new file mode 100644 index 00000000..1d650574 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/Helpers/ResourceManager.cs @@ -0,0 +1,68 @@ +using System; +using System.Runtime.InteropServices; +using ABI.Microsoft.Graphics.Canvas; +using ComputeSharp.D2D1.Extensions; +using TerraFX.Interop.Windows; +using TerraFX.Interop.WinRT; +using Windows.Graphics.Effects; + +namespace ComputeSharp.D2D1.Uwp.Helpers; + +/// +/// A helper type to replicate Win2D's ResourceManager type. +/// +/// +/// This type provides an entry point to use the Win2D activation factory. +/// +internal static class ResourceManager +{ + /// + /// Gets or creates an instance for a native resource. + /// + /// The input canvas device (as a marshalled ). + /// The input native resource to create a wrapper for. + /// The realization DPIs for + /// The resulting wrapper instance. + /// Thrown if the managed wrapper could not be retrieved. + public static unsafe IGraphicsEffectSource GetOrCreate(ICanvasDevice* device, IUnknown* resource, float dpi) + { + const string activatableClassId = "Microsoft.Graphics.Canvas.CanvasDevice"; + + fixed (char* pActivatableClassId = activatableClassId) + { + HSTRING_HEADER hStringHeaderActivatableClassId; + HSTRING hStringActivatableClass; + + // Create a fast-pass HSTRING for "Microsoft.Graphics.Canvas.CanvasDevice" + WinRT.WindowsCreateStringReference( + sourceString: (ushort*)pActivatableClassId, + length: (uint)activatableClassId.Length, + hstringHeader: &hStringHeaderActivatableClassId, + @string: &hStringActivatableClass).Assert(); + + Guid canvasFactoryNativeId = typeof(ICanvasFactoryNative).GUID; + + using ComPtr canvasFactoryNative = default; + + // Get the activation factory for CanvasDevice + WinRT.RoGetActivationFactory( + activatableClassId: hStringActivatableClass, + iid: &canvasFactoryNativeId, + factory: canvasFactoryNative.GetVoidAddressOf()).Assert(); + + using ComPtr wrapperUnknown = default; + + // Get or create a WinRT wrapper for the resource + canvasFactoryNative.Get()->GetOrCreate( + device: device, + resource: resource, + dpi: dpi, + wrapper: wrapperUnknown.GetVoidAddressOf()).Assert(); + + // Get the runtime-provided RCW for the resulting WinRT wrapper + object wrapper = Marshal.GetObjectForIUnknown((IntPtr)wrapperUnknown.Get()); + + return (IGraphicsEffectSource)wrapper; + } + } +} diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.Sources.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.Sources.cs index 16d5dbb8..3d44e0f3 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.Sources.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.Sources.cs @@ -103,7 +103,7 @@ unsafe partial class PixelShaderEffect } // Get or create a wrapper for the input image - return sourceReference.GetOrCreateWrapper(null, d2D1Image.Get()); + return sourceReference.GetOrCreateWrapper(this.canvasDevice.Get(), d2D1Image.Get()); } /// The index of the source to get or set. From 0855eca96779ca3dbf1ec0741645b80d19c263f7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Dec 2022 05:31:52 +0100 Subject: [PATCH 46/59] Dispose native sources when effect is disposed --- .../PixelShaderEffect{T}.ReferenceTracking.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs index 9ff4da45..e891f878 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs @@ -42,5 +42,13 @@ partial class PixelShaderEffect this.canvasDevice.Dispose(); this.d2D1RealizationDevice.Dispose(); this.d2D1Effect.Dispose(); + + // Also release all native resources for the used sources. + // The transform mapper and resource texture managers don't + // need to be disposed, as those could be shared between effects. + for (int i = 0; i < SourceCollection.Count; i++) + { + Sources.Storage[i].Dispose(); + } } } \ No newline at end of file From d28366f7653ecc5918346ae8527ab26c794cb30b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Dec 2022 19:21:50 +0100 Subject: [PATCH 47/59] Rename PixelShaderEffect.Value property to ConstantBuffer --- .../PixelShaderEffect{T}.ICanvasImageInterop.cs | 4 ++-- .../PixelShaderEffect{T}.Properties.Interop.cs | 8 ++++---- .../PixelShaderEffect{T}.Properties.cs | 2 +- src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index 1510d1ed..e25ea0f3 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -194,7 +194,7 @@ unsafe partial class PixelShaderEffect // Note: the resource texture managers are deliberately not read back, as the only supported way to set // those is directly from the current effect instance. As such, they'd all either be the same instances // that are already stored locally, or trying to retrieve them would just throw an exception. - this.value = this.d2D1Effect.Get()->GetConstantBuffer(); + this.constantBuffer = this.d2D1Effect.Get()->GetConstantBuffer(); this.transformMapper = this.d2D1Effect.Get()->GetTransformMapper(); this.cacheOutput = this.d2D1Effect.Get()->GetCachedProperty(); this.d2D1BufferPrecision = this.d2D1Effect.Get()->GetPrecisionProperty(); @@ -265,7 +265,7 @@ unsafe partial class PixelShaderEffect } // Set the constant buffer for the effect - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(this.d2D1Effect.Get(), in this.value); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(this.d2D1Effect.Get(), in this.constantBuffer); // If there is a transform mapper, set it in the effect if (this.transformMapper is not null) diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs index eb9d81d0..0e5c3bd3 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.cs @@ -22,15 +22,15 @@ unsafe partial class PixelShaderEffect return this.d2D1Effect.Get() switch { not null => this.d2D1Effect.Get()->GetConstantBuffer(), - _ => this.value + _ => this.constantBuffer }; } } /// - /// Sets the marshalled value for . + /// Sets the marshalled value for . /// - /// The value to set for . + /// The value to set for . private void SetConstantBuffer(in T value) { using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); @@ -45,7 +45,7 @@ unsafe partial class PixelShaderEffect else { // Otherwise, just store the value locally - this.value = value; + this.constantBuffer = value; } } } diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs index 74954eda..05098a6a 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs @@ -11,7 +11,7 @@ partial class PixelShaderEffect /// /// Gets or sets the current value in use. /// - public T Value + public T ConstantBuffer { get => GetConstantBuffer(); set => SetConstantBuffer(in value); diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs index 24264553..dd4d9c0a 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs @@ -45,9 +45,9 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan private ComPtr d2D1Effect; /// - /// The backing field for . + /// The backing field for . /// - private T value; + private T constantBuffer; /// /// The backing field for . From ad400fbd3bf3266f3fdc5a118fe03c3299b4eac1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Dec 2022 20:23:10 +0100 Subject: [PATCH 48/59] Fix DPI compensation path when no device context is available --- .../Extensions/ICanvasDeviceExtensions.cs | 21 +++++++++++++++++++ ...derEffect{T}.Properties.Interop.Sources.cs | 14 ++++++++++--- .../um/d2d1_1/D2D1_DEVICE_CONTEXT_OPTIONS.cs | 16 ++++++++++++++ .../DirectX/um/d2d1_2/ID2D1Device1.cs | 7 +++++++ .../TerraFX.Interop.Windows.D2D1.projitems | 1 + 5 files changed, 56 insertions(+), 3 deletions(-) create mode 100644 src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_DEVICE_CONTEXT_OPTIONS.cs diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/ICanvasDeviceExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/ICanvasDeviceExtensions.cs index d73d7534..94857be8 100644 --- a/src/ComputeSharp.D2D1.Uwp/Extensions/ICanvasDeviceExtensions.cs +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/ICanvasDeviceExtensions.cs @@ -35,4 +35,25 @@ internal static unsafe class ICanvasDeviceExtensions return hresult; } + + /// + /// Creates a new from an input . + /// + /// The input object. + /// The resulting object. + /// The for the operation. + public static HRESULT CreateD2DDeviceContext(this ref ICanvasDevice canvasDevice, ID2D1DeviceContext** d2D1DeviceContext) + { + using ComPtr d2D1Device1 = default; + + // Get the underlying ID2D1Device1 object + canvasDevice.GetD2DDevice(d2D1Device1.GetAddressOf()).Assert(); + + // Create the new device context + HRESULT hresult = d2D1Device1.Get()->CreateDeviceContext( + options: D2D1_DEVICE_CONTEXT_OPTIONS.D2D1_DEVICE_CONTEXT_OPTIONS_NONE, + deviceContext: d2D1DeviceContext); + + return hresult; + } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.Sources.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.Sources.cs index 3d44e0f3..c4ef1365 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.Sources.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Interop.Sources.cs @@ -280,14 +280,22 @@ unsafe partial class PixelShaderEffect // Create an ID2D1Effect for the DPI compensation, if there isn't one already if (!sourceReference.HasDpiCompensationEffect) { - // We need to create a DPI compensation effect, so a device context must be available + using ComPtr d2D1DeviceContextEffective = default; + + // We need to create a DPI compensation effect, so a device context must be available. + // If there is no input device context, just create a new one from the realization device. if (d2D1DeviceContext is null) { - Marshal.ThrowExceptionForHR(E.E_POINTER); + this.canvasDevice.Get()->CreateD2DDeviceContext(d2D1DeviceContextEffective.GetAddressOf()).Assert(); + } + else + { + // Otherwise, just use the input device context + *&d2D1DeviceContextEffective = new ComPtr(d2D1DeviceContext); } // Create the DPI compensation effect - d2D1DeviceContext->CreateEffect( + d2D1DeviceContextEffective.Get()->CreateEffect( effectId: (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_D2D1DpiCompensation)), effect: d2D1EffectDpiCompensation.GetAddressOf()).Assert(); diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_DEVICE_CONTEXT_OPTIONS.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_DEVICE_CONTEXT_OPTIONS.cs new file mode 100644 index 00000000..bd22e599 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_DEVICE_CONTEXT_OPTIONS.cs @@ -0,0 +1,16 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1_1.h in the Windows SDK for Windows 10.0.22621.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; + +namespace TerraFX.Interop.DirectX; + +[Flags] +internal enum D2D1_DEVICE_CONTEXT_OPTIONS : uint +{ + D2D1_DEVICE_CONTEXT_OPTIONS_NONE = 0, + D2D1_DEVICE_CONTEXT_OPTIONS_ENABLE_MULTITHREADED_OPTIMIZATIONS = 1, + D2D1_DEVICE_CONTEXT_OPTIONS_FORCE_DWORD = 0xffffffff, +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_2/ID2D1Device1.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_2/ID2D1Device1.cs index 193e8b8c..1a374296 100644 --- a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_2/ID2D1Device1.cs +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_2/ID2D1Device1.cs @@ -49,4 +49,11 @@ internal unsafe partial struct ID2D1Device1 { ((delegate* unmanaged[Stdcall])(lpVtbl[3]))((ID2D1Device1*)Unsafe.AsPointer(ref this), factory); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(4)] + public HRESULT CreateDeviceContext(D2D1_DEVICE_CONTEXT_OPTIONS options, ID2D1DeviceContext** deviceContext) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[4]))((ID2D1Device1*)Unsafe.AsPointer(ref this), options, deviceContext); + } } \ 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 cfa82c7b..51cb9906 100644 --- a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems +++ b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems @@ -35,6 +35,7 @@ + From 4043ba2bf94918a30f6325ff4a30af1aaa3c8e31 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Dec 2022 20:33:55 +0100 Subject: [PATCH 49/59] Add partial ICanvasEffect support to PixelShaderEffect --- .../PixelShaderEffect{T}.ICanvasEffect.cs | 44 +++++++++++++++++++ .../PixelShaderEffect{T}.Properties.cs | 12 +++-- .../PixelShaderEffect{T}.cs | 5 ++- 3 files changed, 52 insertions(+), 9 deletions(-) create mode 100644 src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasEffect.cs diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasEffect.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasEffect.cs new file mode 100644 index 00000000..752418cc --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasEffect.cs @@ -0,0 +1,44 @@ +using System; +using Microsoft.Graphics.Canvas; +using Microsoft.Graphics.Canvas.Effects; +using Windows.Foundation; + +namespace ComputeSharp.D2D1.Uwp; + +/// +partial class PixelShaderEffect +{ + /// + void ICanvasEffect.InvalidateSourceRectangle(ICanvasResourceCreatorWithDpi resourceCreator, uint sourceIndex, Rect invalidRectangle) + { + throw new NotSupportedException("ICanvasEffect.InvalidateSourceRectangle is not currently supported."); + } + + /// + Rect[] ICanvasEffect.GetInvalidRectangles(ICanvasResourceCreatorWithDpi resourceCreator) + { + throw new NotSupportedException("ICanvasEffect.GetInvalidRectangles is not currently supported."); + } + + /// + Rect ICanvasEffect.GetRequiredSourceRectangle( + ICanvasResourceCreatorWithDpi resourceCreator, + Rect outputRectangle, + ICanvasEffect sourceEffect, + uint sourceIndex, + Rect sourceBounds) + { + throw new NotSupportedException("ICanvasEffect.GetRequiredSourceRectangle is not currently supported."); + } + + /// + Rect[] ICanvasEffect.GetRequiredSourceRectangles( + ICanvasResourceCreatorWithDpi resourceCreator, + Rect outputRectangle, + ICanvasEffect[] sourceEffects, + uint[] sourceIndices, + Rect[] sourceBounds) + { + throw new NotSupportedException("ICanvasEffect.GetRequiredSourceRectangles is not currently supported."); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs index 05098a6a..71882ab1 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.cs @@ -28,25 +28,23 @@ partial class PixelShaderEffect set => SetTransformMapper(value); } - /// - /// Gets or sets a value indicating whether to enable caching the output from drawing this effect. - /// + /// public bool CacheOutput { get => GetCacheOutput(); set => SetCacheOutput(value); } - /// - /// Gets or sets the precision to use for intermediate buffers when drawing this effect. - /// - /// If , the default precision for effects will be used. + /// public CanvasBufferPrecision? BufferPrecision { get => GetBufferPrecision(); set => SetBufferPrecision(value); } + /// + public string? Name { get; set; } + /// /// Gets the object associated with the current instance. /// diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs index dd4d9c0a..7c3c389c 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs @@ -2,16 +2,17 @@ using ABI.Microsoft.Graphics.Canvas; using ComputeSharp.D2D1.Interop; using ComputeSharp.Interop; using Microsoft.Graphics.Canvas; +using Microsoft.Graphics.Canvas.Effects; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; namespace ComputeSharp.D2D1.Uwp; /// -/// A custom implementation powered by a supplied shader type. +/// A custom implementation powered by a supplied shader type. /// /// The type of shader to use to render frames. -public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICanvasImage, ICanvasImageInterop.Interface +public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICanvasEffect, ICanvasImageInterop.Interface where T : unmanaged, ID2D1PixelShader { /// From 33dbfba3a66a622b3dcce7d8738ed4ef48069979 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Dec 2022 23:44:13 +0100 Subject: [PATCH 50/59] Add initial IFixedCountList abstraction --- .../Buffers/FixedCountList{T}.cs | 106 ++++++++++++++++++ .../Buffers/IFixedCountList{T}.cs | 17 +++ 2 files changed, 123 insertions(+) create mode 100644 src/ComputeSharp.D2D1.Uwp/Buffers/FixedCountList{T}.cs create mode 100644 src/ComputeSharp.D2D1.Uwp/Buffers/IFixedCountList{T}.cs diff --git a/src/ComputeSharp.D2D1.Uwp/Buffers/FixedCountList{T}.cs b/src/ComputeSharp.D2D1.Uwp/Buffers/FixedCountList{T}.cs new file mode 100644 index 00000000..44204a5f --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/Buffers/FixedCountList{T}.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using ComputeSharp.D2D1.Helpers; + +namespace ComputeSharp.D2D1.Uwp.Buffers; + +/// +/// Shared helpers for all types implementing . +/// +/// The type of elements in the list. +internal static class FixedCountList +{ + /// + /// Copies the entire instance to a target array range. + /// + /// The input instance. + /// The array to copy elements to. + /// The initial index within . + public static void CopyTo(IFixedCountList list, T[] array, int index) + { + if (array is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(array), "The input array cannot be null."); + } + + Span span = array.AsSpan(index); + + if (list.Count > span.Length) + { + ThrowHelper.ThrowArgumentException(nameof(array), "The destination array range is smaller than the number of source items."); + } + + for (int i = 0; i < list.Count; i++) + { + span[i] = list[i]; + } + } + + /// + /// Copies the entire instance to a target array range. + /// + /// The input instance. + /// The array to copy elements to. + /// The initial index within . + public static void CopyTo(IFixedCountList list, Array array, int index) + { + if (array is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(array), "The input array cannot be null."); + } + + if ((uint)index >= array.Length) + { + ThrowHelper.ThrowArgumentOutOfRangeException(nameof(index), "The starting array index is out of range."); + } + + int remainingLength = array.Length - index; + + if (list.Count > remainingLength) + { + ThrowHelper.ThrowArgumentException(nameof(array), "The destination array range is smaller than the number of source items."); + } + + for (int i = 0; i < list.Count; i++) + { + array.SetValue(list[i], i); + } + } + + /// + /// Creates an for an input instance. + /// + /// The input instance. + /// An instance for . + public static IEnumerator GetEnumerator(IFixedCountList list) + { + for (int i = 0; i < list.Count; i++) + { + yield return list[i]; + } + } + + /// + /// Searches for the specified object and returns the zero-based index of the first occurrence + /// within the range of elements in a given instance. + /// + /// The input instance. + /// + /// The object to locate in . The value can be for reference types. + /// + /// + /// The zero-based index of the first occurrence of item within , otherwise -1. + /// + public static int IndexOf(IFixedCountList list, T value) + { + for (int i = 0; i < list.Count; i++) + { + if (EqualityComparer.Default.Equals(list[i], value)) + { + return i; + } + } + + return -1; + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/Buffers/IFixedCountList{T}.cs b/src/ComputeSharp.D2D1.Uwp/Buffers/IFixedCountList{T}.cs new file mode 100644 index 00000000..73ebb200 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/Buffers/IFixedCountList{T}.cs @@ -0,0 +1,17 @@ +using System.Collections; +using System.Collections.Generic; + +namespace ComputeSharp.D2D1.Uwp.Buffers; + +/// +/// An interface for a list with a fixed collection. +/// +/// The type of elements in the list. +interface IFixedCountList +{ + /// + int Count { get; } + + /// + T this[int index] { get; set; } +} \ No newline at end of file From ec2e1e15f0a005f7ded51a44d6ee22f42a26ee84 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Dec 2022 23:47:38 +0100 Subject: [PATCH 51/59] Add collection interfaces to PixelShaderEffect.SourceCollection --- ...ixelShaderEffect{T}.ICanvasImageInterop.cs | 6 +- ...PixelShaderEffect{T}.Properties.Sources.cs | 153 ++++++++++++++++-- .../PixelShaderEffect{T}.ReferenceTracking.cs | 2 +- 3 files changed, 145 insertions(+), 16 deletions(-) diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index e25ea0f3..c9056ade 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -200,7 +200,7 @@ unsafe partial class PixelShaderEffect this.d2D1BufferPrecision = this.d2D1Effect.Get()->GetPrecisionProperty(); // Loop over all effect inputs and update the cache back as well - for (int i = 0; i < SourceCollection.Count; i++) + for (int i = 0; i < Sources.Count; i++) { // If this index has been explicitly requested to be skipped, just dispose the source reference. // This is the case when the effect is being unrealized, and callers will set this value on their own. @@ -286,7 +286,7 @@ unsafe partial class PixelShaderEffect } // Forward all available sources (the effect is being created now, so no need to validate the underlying resources) - for (int i = 0; i < SourceCollection.Count; i++) + for (int i = 0; i < Sources.Count; i++) { if (!SetD2DInput( index: i, @@ -320,7 +320,7 @@ unsafe partial class PixelShaderEffect /// The instance in use. private void RefreshInputs(WIN2D_GET_D2D_IMAGE_FLAGS flags, float targetDpi, ID2D1DeviceContext* deviceContext) { - for (int i = 0; i < SourceCollection.Count; i++) + for (int i = 0; i < Sources.Count; i++) { // Retrieve the managed wrapper for the current source IGraphicsEffectSource? source = GetD2DInput(i); diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs index 19ccd9c0..83b54ca1 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs @@ -1,4 +1,6 @@ using System; +using System.Collections; +using System.Collections.Generic; using System.Runtime.CompilerServices; using ComputeSharp.D2D1.Helpers; using ComputeSharp.D2D1.Interop; @@ -13,7 +15,7 @@ partial class PixelShaderEffect /// /// Represents the collection of sources in a instance. /// - public sealed class SourceCollection + public sealed class SourceCollection : IList, IReadOnlyList, IList, IFixedCountList { /// /// The fixed buffer of instances. @@ -29,17 +31,14 @@ partial class PixelShaderEffect Owner = owner; } - /// - /// Gets the actual input count for the current effect. - /// - internal static int Count { get; } = D2D1PixelShader.GetInputCount(); + /// + public int Count + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => D2D1PixelShader.GetInputCount(); + } - /// - /// Gets or sets the source at a specified index. - /// - /// The index of the source to get or set. - /// The source at the specified index. - /// Thrown if is not a valid index for the current effect. + /// public IGraphicsEffectSource? this[int index] { get @@ -56,6 +55,13 @@ partial class PixelShaderEffect } } + /// + object? IList.this[int index] + { + get => this[index]; + set => this[index] = (IGraphicsEffectSource?)value; + } + /// /// The owning instance. /// @@ -66,6 +72,129 @@ partial class PixelShaderEffect /// internal ref GraphicsEffectSourceBuffer Storage => ref this.fixedBuffer; + /// + bool ICollection.IsReadOnly => false; + + /// + bool IList.IsReadOnly => false; + + /// + bool IList.IsFixedSize => true; + + /// + bool ICollection.IsSynchronized => true; + + /// + object ICollection.SyncRoot => throw new NotSupportedException("ICollection.SyncRoot is not supported for SourceCollection."); + + /// + void ICollection.Add(IGraphicsEffectSource? item) + { + throw new NotSupportedException("ICollection.Add is not supported for SourceCollection."); + } + + /// + int IList.Add(object value) + { + throw new NotSupportedException("IList.Add is not supported for SourceCollection."); + } + + /// + void ICollection.Clear() + { + throw new NotSupportedException("ICollection.Clear is not supported for SourceCollection."); + } + + /// + void IList.Clear() + { + throw new NotSupportedException("IList.Clear is not supported for SourceCollection."); + } + + /// + bool ICollection.Contains(IGraphicsEffectSource? item) + { + return FixedCountList.IndexOf(this, item) != -1; + } + + /// + bool IList.Contains(object value) + { + return FixedCountList.IndexOf(this, (IGraphicsEffectSource?)value) != -1; + } + + /// + void ICollection.CopyTo(IGraphicsEffectSource?[] array, int arrayIndex) + { + FixedCountList.CopyTo(this, array, arrayIndex); + } + + /// + void ICollection.CopyTo(Array array, int index) + { + FixedCountList.CopyTo(this, array, index); + } + + /// + IEnumerator IEnumerable.GetEnumerator() + { + return FixedCountList.GetEnumerator(this); + } + + /// + IEnumerator IEnumerable.GetEnumerator() + { + return FixedCountList.GetEnumerator(this); + } + + /// + int IList.IndexOf(IGraphicsEffectSource? item) + { + return FixedCountList.IndexOf(this, item); + } + + /// + int IList.IndexOf(object value) + { + return FixedCountList.IndexOf(this, (IGraphicsEffectSource?)value); + } + + /// + void IList.Insert(int index, IGraphicsEffectSource? item) + { + throw new NotSupportedException("IList.Insert is not supported for SourceCollection."); + } + + /// + void IList.Insert(int index, object value) + { + throw new NotSupportedException("IList.Insert is not supported for SourceCollection."); + } + + /// + bool ICollection.Remove(IGraphicsEffectSource? item) + { + throw new NotSupportedException("ICollection.Remove is not supported for SourceCollection."); + } + + /// + void IList.Remove(object value) + { + throw new NotSupportedException("IList.Remove is not supported for SourceCollection."); + } + + /// + void IList.RemoveAt(int index) + { + throw new NotSupportedException("IList.RemoveAt is not supported for SourceCollection."); + } + + /// + void IList.RemoveAt(int index) + { + throw new NotSupportedException("IList.RemoveAt is not supported for SourceCollection."); + } + /// /// Validates the input index for . /// @@ -74,7 +203,7 @@ partial class PixelShaderEffect [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void ValidateIndex(int index) { - if ((uint)index >= Count) + if ((uint)index >= D2D1PixelShader.GetInputCount()) { ThrowHelper.ThrowArgumentOutOfRangeException(nameof(index), "The input index is not a valid source index for the current effect."); } diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs index e891f878..08548bb1 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs @@ -46,7 +46,7 @@ partial class PixelShaderEffect // Also release all native resources for the used sources. // The transform mapper and resource texture managers don't // need to be disposed, as those could be shared between effects. - for (int i = 0; i < SourceCollection.Count; i++) + for (int i = 0; i < Sources.Count; i++) { Sources.Storage[i].Dispose(); } From 7cf711cf59a88720b3d87129c305d35b914b9d17 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Dec 2022 23:57:53 +0100 Subject: [PATCH 52/59] Add support for dynamic indices to IFixedCountList --- .../Buffers/FixedCountList{T}.cs | 12 +++---- .../Buffers/IFixedCountList{T}.cs | 8 +++-- ...PixelShaderEffect{T}.Properties.Sources.cs | 32 +++++++++++++++++++ 3 files changed, 43 insertions(+), 9 deletions(-) diff --git a/src/ComputeSharp.D2D1.Uwp/Buffers/FixedCountList{T}.cs b/src/ComputeSharp.D2D1.Uwp/Buffers/FixedCountList{T}.cs index 44204a5f..19026aca 100644 --- a/src/ComputeSharp.D2D1.Uwp/Buffers/FixedCountList{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/Buffers/FixedCountList{T}.cs @@ -25,12 +25,12 @@ internal static class FixedCountList Span span = array.AsSpan(index); - if (list.Count > span.Length) + if (list.Indices.Length > span.Length) { ThrowHelper.ThrowArgumentException(nameof(array), "The destination array range is smaller than the number of source items."); } - for (int i = 0; i < list.Count; i++) + foreach (int i in list.Indices) { span[i] = list[i]; } @@ -56,12 +56,12 @@ internal static class FixedCountList int remainingLength = array.Length - index; - if (list.Count > remainingLength) + if (list.Indices.Length > remainingLength) { ThrowHelper.ThrowArgumentException(nameof(array), "The destination array range is smaller than the number of source items."); } - for (int i = 0; i < list.Count; i++) + foreach (int i in list.Indices) { array.SetValue(list[i], i); } @@ -74,7 +74,7 @@ internal static class FixedCountList /// An instance for . public static IEnumerator GetEnumerator(IFixedCountList list) { - for (int i = 0; i < list.Count; i++) + foreach (int i in list.Indices) { yield return list[i]; } @@ -93,7 +93,7 @@ internal static class FixedCountList /// public static int IndexOf(IFixedCountList list, T value) { - for (int i = 0; i < list.Count; i++) + foreach (int i in list.Indices) { if (EqualityComparer.Default.Equals(list[i], value)) { diff --git a/src/ComputeSharp.D2D1.Uwp/Buffers/IFixedCountList{T}.cs b/src/ComputeSharp.D2D1.Uwp/Buffers/IFixedCountList{T}.cs index 73ebb200..175cb0a1 100644 --- a/src/ComputeSharp.D2D1.Uwp/Buffers/IFixedCountList{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/Buffers/IFixedCountList{T}.cs @@ -1,5 +1,5 @@ -using System.Collections; using System.Collections.Generic; +using System.Collections.Immutable; namespace ComputeSharp.D2D1.Uwp.Buffers; @@ -9,8 +9,10 @@ namespace ComputeSharp.D2D1.Uwp.Buffers; /// The type of elements in the list. interface IFixedCountList { - /// - int Count { get; } + /// + /// Gets the collection of valid indices for the current effect. + /// + ImmutableArray Indices { get; } /// T this[int index] { get; set; } diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs index 83b54ca1..c2fb27de 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Collections.Immutable; using System.Runtime.CompilerServices; using ComputeSharp.D2D1.Helpers; using ComputeSharp.D2D1.Interop; @@ -17,6 +18,11 @@ partial class PixelShaderEffect /// public sealed class SourceCollection : IList, IReadOnlyList, IList, IFixedCountList { + /// + /// The collection of valid resource texture indices for the current effect. + /// + private static readonly ImmutableArray Indices = GetIndices(); + /// /// The fixed buffer of instances. /// @@ -72,6 +78,9 @@ partial class PixelShaderEffect /// internal ref GraphicsEffectSourceBuffer Storage => ref this.fixedBuffer; + /// + ImmutableArray IFixedCountList.Indices => Indices; + /// bool ICollection.IsReadOnly => false; @@ -208,5 +217,28 @@ partial class PixelShaderEffect ThrowHelper.ThrowArgumentOutOfRangeException(nameof(index), "The input index is not a valid source index for the current effect."); } } + + /// + /// Gets the collection of valid indices for the current effect. + /// + /// The collection of valid indices for the current effect. + private static unsafe ImmutableArray GetIndices() + { + int inputCount = D2D1PixelShader.GetInputCount(); + + if (inputCount == 0) + { + return ImmutableArray.Empty; + } + + int[] indices = new int[inputCount]; + + for (int i = 0; i < indices.Length; i++) + { + indices[i] = i; + } + + return *(ImmutableArray*)&indices; + } } } \ No newline at end of file From 63799054c1071d83ac66424ab7ac88259fff396d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Dec 2022 00:12:37 +0100 Subject: [PATCH 53/59] Add collection interfaces to PixelShaderEffect.ResourceTextureManagerCollection --- ...erties.ResourceTextureManagerCollection.cs | 150 +++++++++++++++++- 1 file changed, 144 insertions(+), 6 deletions(-) diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs index f0d90bd3..f210f0f8 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs @@ -1,4 +1,6 @@ using System; +using System.Collections; +using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; @@ -7,7 +9,7 @@ using ComputeSharp.D2D1.Interop; using ComputeSharp.D2D1.Shaders.Loaders; using ComputeSharp.D2D1.Uwp.Buffers; -#pragma warning disable CS0618 +#pragma warning disable CS0618, CS8767 namespace ComputeSharp.D2D1.Uwp; @@ -17,7 +19,7 @@ partial class PixelShaderEffect /// /// Represents the collection of objects in a instance. /// - public sealed class ResourceTextureManagerCollection + public sealed class ResourceTextureManagerCollection : IList, IReadOnlyList, IList, IFixedCountList { /// /// The bitmask of valid indices for resource texture managers in the current shader type. @@ -38,10 +40,8 @@ partial class PixelShaderEffect Owner = owner; } - /// - /// Gets the collection of valid resource texture indices for the current effect. - /// - internal static ImmutableArray Indices { get; } = GetIndices(); + /// + public int Count => Indices.Length; /// /// Gets or sets the object at a specified index. @@ -72,6 +72,18 @@ partial class PixelShaderEffect } } + /// + object? IList.this[int index] + { + get => this[index]; + set => this[index] = (D2D1ResourceTextureManager?)value!; + } + + /// + /// Gets the collection of valid resource texture indices for the current effect. + /// + internal static ImmutableArray Indices { get; } = GetIndices(); + /// /// The owning instance. /// @@ -82,6 +94,132 @@ partial class PixelShaderEffect /// internal ref ResourceTextureManagerBuffer Storage => ref this.fixedBuffer; + /// + ImmutableArray IFixedCountList.Indices => Indices; + + /// + bool ICollection.IsReadOnly => false; + + /// + bool IList.IsReadOnly => false; + + /// + bool IList.IsFixedSize => true; + + /// + bool ICollection.IsSynchronized => true; + + /// + object ICollection.SyncRoot => throw new NotSupportedException("ICollection.SyncRoot is not supported for ResourceTextureManagerCollection."); + + /// + void ICollection.Add(D2D1ResourceTextureManager? item) + { + throw new NotSupportedException("ICollection.Add is not supported for ResourceTextureManagerCollection."); + } + + /// + int IList.Add(object value) + { + throw new NotSupportedException("IList.Add is not supported for ResourceTextureManagerCollection."); + } + + /// + void ICollection.Clear() + { + throw new NotSupportedException("ICollection.Clear is not supported for ResourceTextureManagerCollection."); + } + + /// + void IList.Clear() + { + throw new NotSupportedException("IList.Clear is not supported for ResourceTextureManagerCollection."); + } + + /// + bool ICollection.Contains(D2D1ResourceTextureManager? item) + { + return FixedCountList.IndexOf(this, item) != -1; + } + + /// + bool IList.Contains(object value) + { + return FixedCountList.IndexOf(this, (D2D1ResourceTextureManager?)value) != -1; + } + + /// + void ICollection.CopyTo(D2D1ResourceTextureManager?[] array, int arrayIndex) + { + FixedCountList.CopyTo(this, array, arrayIndex); + } + + /// + void ICollection.CopyTo(Array array, int index) + { + FixedCountList.CopyTo(this, array, index); + } + + /// + IEnumerator IEnumerable.GetEnumerator() + { + return FixedCountList.GetEnumerator(this); + } + + /// + IEnumerator IEnumerable.GetEnumerator() + { + return FixedCountList.GetEnumerator(this); + } + + /// + int IList.IndexOf(D2D1ResourceTextureManager? item) + { + return FixedCountList.IndexOf(this, item); + } + + /// + int IList.IndexOf(object value) + { + return FixedCountList.IndexOf(this, (D2D1ResourceTextureManager?)value); + } + + /// + void IList.Insert(int index, D2D1ResourceTextureManager? item) + { + throw new NotSupportedException("IList.Insert is not supported for ResourceTextureManagerCollection."); + } + + /// + void IList.Insert(int index, object value) + { + throw new NotSupportedException("IList.Insert is not supported for ResourceTextureManagerCollection."); + } + + /// + bool ICollection.Remove(D2D1ResourceTextureManager? item) + { + throw new NotSupportedException("ICollection.Remove is not supported for ResourceTextureManagerCollection."); + } + + /// + void IList.Remove(object value) + { + throw new NotSupportedException("IList.Remove is not supported for ResourceTextureManagerCollection."); + } + + /// + void IList.RemoveAt(int index) + { + throw new NotSupportedException("IList.RemoveAt is not supported for ResourceTextureManagerCollection."); + } + + /// + void IList.RemoveAt(int index) + { + throw new NotSupportedException("IList.RemoveAt is not supported for ResourceTextureManagerCollection."); + } + /// /// Validates the input index for . /// From 233cd847decb0edf51836780226eae5a29d3dfd2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Dec 2022 00:13:29 +0100 Subject: [PATCH 54/59] Minor code refactoring --- .../{Buffers => Collections}/FixedCountList{T}.cs | 2 +- .../{Buffers => Collections}/IFixedCountList{T}.cs | 2 +- ...aderEffect{T}.Properties.ResourceTextureManagerCollection.cs | 1 + .../PixelShaderEffect{T}.Properties.Sources.cs | 1 + 4 files changed, 4 insertions(+), 2 deletions(-) rename src/ComputeSharp.D2D1.Uwp/{Buffers => Collections}/FixedCountList{T}.cs (98%) rename src/ComputeSharp.D2D1.Uwp/{Buffers => Collections}/IFixedCountList{T}.cs (91%) diff --git a/src/ComputeSharp.D2D1.Uwp/Buffers/FixedCountList{T}.cs b/src/ComputeSharp.D2D1.Uwp/Collections/FixedCountList{T}.cs similarity index 98% rename from src/ComputeSharp.D2D1.Uwp/Buffers/FixedCountList{T}.cs rename to src/ComputeSharp.D2D1.Uwp/Collections/FixedCountList{T}.cs index 19026aca..1695dd81 100644 --- a/src/ComputeSharp.D2D1.Uwp/Buffers/FixedCountList{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/Collections/FixedCountList{T}.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using ComputeSharp.D2D1.Helpers; -namespace ComputeSharp.D2D1.Uwp.Buffers; +namespace ComputeSharp.D2D1.Uwp.Collections; /// /// Shared helpers for all types implementing . diff --git a/src/ComputeSharp.D2D1.Uwp/Buffers/IFixedCountList{T}.cs b/src/ComputeSharp.D2D1.Uwp/Collections/IFixedCountList{T}.cs similarity index 91% rename from src/ComputeSharp.D2D1.Uwp/Buffers/IFixedCountList{T}.cs rename to src/ComputeSharp.D2D1.Uwp/Collections/IFixedCountList{T}.cs index 175cb0a1..2cc4b735 100644 --- a/src/ComputeSharp.D2D1.Uwp/Buffers/IFixedCountList{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/Collections/IFixedCountList{T}.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Collections.Immutable; -namespace ComputeSharp.D2D1.Uwp.Buffers; +namespace ComputeSharp.D2D1.Uwp.Collections; /// /// An interface for a list with a fixed collection. diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs index f210f0f8..9e3f9c4e 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs @@ -8,6 +8,7 @@ using ComputeSharp.D2D1.Helpers; using ComputeSharp.D2D1.Interop; using ComputeSharp.D2D1.Shaders.Loaders; using ComputeSharp.D2D1.Uwp.Buffers; +using ComputeSharp.D2D1.Uwp.Collections; #pragma warning disable CS0618, CS8767 diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs index c2fb27de..2746b9c4 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.Properties.Sources.cs @@ -6,6 +6,7 @@ using System.Runtime.CompilerServices; using ComputeSharp.D2D1.Helpers; using ComputeSharp.D2D1.Interop; using ComputeSharp.D2D1.Uwp.Buffers; +using ComputeSharp.D2D1.Uwp.Collections; using Windows.Graphics.Effects; namespace ComputeSharp.D2D1.Uwp; From 222737e479ec3262ca5916030691c5e002ee2175 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Dec 2022 00:30:14 +0100 Subject: [PATCH 55/59] Add ComputeSharp.D2D1.Uwp package to CI script --- .github/workflows/dotnet.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index d33abc62..9ee7743b 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -50,8 +50,10 @@ jobs: run: dotnet build src\ComputeSharp.Pix.Package\ComputeSharp.Pix.Package.msbuildproj -c Release - name: Build ComputeSharp.Uwp package run: msbuild src\ComputeSharp.Uwp\ComputeSharp.Uwp.csproj -t:restore,build,pack /p:Configuration=Release + - name: Build ComputeSharp.D2D1.Uwp package + run: msbuild src\ComputeSharp.D2D1.Uwp\ComputeSharp.D2D1.Uwp.csproj -t:restore,build,pack /p:Configuration=Release - # Packing needs to be done separately and with no previous build target for this to work correctly + # WinUI 3 packaging needs to be done separately and with no previous build target for it to work correctly - name: Build ComputeSharp.WinUI project run: > msbuild src\ComputeSharp.WinUI\ComputeSharp.WinUI.csproj -t:restore /p:Configuration=Release; From b37e735e06b0d313e5356afd0fa539e9c44a6f72 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Dec 2022 22:26:17 +0100 Subject: [PATCH 56/59] Fix a memory leak with the realization ICanvasDevice object --- .../Extensions/IUnknownExtensions.cs | 18 ++++++++++++++++-- ...PixelShaderEffect{T}.ICanvasImageInterop.cs | 7 +------ 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs index 8b1e1b0c..11610412 100644 --- a/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs @@ -8,7 +8,7 @@ namespace ComputeSharp.D2D1.Uwp.Extensions; /// /// Helper methods for working with the type. /// -internal static class IUnknownExtensions +internal static unsafe class IUnknownExtensions { /// /// Checks whether two values have the same underlying COM object. @@ -18,7 +18,7 @@ internal static class IUnknownExtensions /// The first object to compare. /// The second object to compare. /// Whether and point to the same COM object. - public static unsafe bool IsSameInstance(this ref T left, U* right) + public static bool IsSameInstance(this ref T left, U* right) where T : unmanaged // IUnknown where U : unmanaged // IUnknown { @@ -40,4 +40,18 @@ internal static class IUnknownExtensions return leftUnknown.Get() == rightUnknown.Get(); } + + /// + /// Copies the source object onto a target destination. + /// + /// The type of object being copied. + /// The source object. + /// The destination location. + public static void CopyTo(this ref T source, ref ComPtr destination) + where T : unmanaged // IUnknown + { + destination.Dispose(); + + destination = new ComPtr((T*)Unsafe.AsPointer(ref source)); + } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index c9056ade..8e3ab29e 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -12,7 +12,6 @@ using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using Windows.Graphics.Effects; using static ABI.Microsoft.Graphics.Canvas.WIN2D_GET_D2D_IMAGE_FLAGS; -using Win32 = TerraFX.Interop.Windows.Windows; namespace ComputeSharp.D2D1.Uwp; @@ -117,11 +116,7 @@ unsafe partial class PixelShaderEffect // Store the input realization device and canvas device for future uses d2D1Device1.CopyTo(ref this.d2D1RealizationDevice).Assert(); - - fixed (ICanvasDevice** canvasDevice = this.canvasDevice) - { - device->QueryInterface(Win32.__uuidof(), (void**)canvasDevice).Assert(); - } + device->CopyTo(ref this.canvasDevice); } // Create the effect, if it doesn't exist already From 832ac59bcf7e9d18aefecefe7fcda90e1498849e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 12 Dec 2022 20:30:50 +0100 Subject: [PATCH 57/59] Add extra AddRef call to protect against AVs in edge case --- .../Extensions/IUnknownExtensions.cs | 13 ++++++++++--- .../PixelShaderEffect{T}.ICanvasImageInterop.cs | 2 +- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs index 11610412..f3847d30 100644 --- a/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs @@ -47,11 +47,18 @@ internal static unsafe class IUnknownExtensions /// The type of object being copied. /// The source object. /// The destination location. - public static void CopyTo(this ref T source, ref ComPtr destination) + /// The for the operation (always ). + public static HRESULT CopyTo(this ref T source, ref ComPtr destination) where T : unmanaged // IUnknown { - destination.Dispose(); + // Note: this explicitly needs a temporary copy to avoid issues in case source and destination were + // pointers to the same object (which can be the case even if the two pointers are not identical). + // To double check, a full check through an IUnknown* cast would be needed, but to avoid the extra + // QueryInterface call on both objects, we can just always do one AddRef call which avoids issues in + // all cases as well. The situation we need to avoid is that without a temporary copy, releasing the + // target object might actually destroy the object, causing the following AddRef call to AV. + using ComPtr temporary = new((T*)Unsafe.AsPointer(ref source)); - destination = new ComPtr((T*)Unsafe.AsPointer(ref source)); + return temporary.CopyTo(ref destination); } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index 8e3ab29e..61688e34 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -116,7 +116,7 @@ unsafe partial class PixelShaderEffect // Store the input realization device and canvas device for future uses d2D1Device1.CopyTo(ref this.d2D1RealizationDevice).Assert(); - device->CopyTo(ref this.canvasDevice); + device->CopyTo(ref this.canvasDevice).Assert(); } // Create the effect, if it doesn't exist already From 470a64f2338b8019d7812d724c3aa9e793f3acf6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 14 Dec 2022 13:27:01 +0100 Subject: [PATCH 58/59] Fix incorrect source indices when realizing D2D effects --- .../PixelShaderEffect{T}.ICanvasImageInterop.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index 61688e34..048b8c97 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -285,7 +285,7 @@ unsafe partial class PixelShaderEffect { if (!SetD2DInput( index: i, - value: Sources.Storage[0].GetWrapper(), + value: Sources.Storage[i].GetWrapper(), flags: flags, targetDpi: targetDpi, d2D1DeviceContext: deviceContext)) From 25134c7cc39cb12df9751633c62b7c9709a3e428 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 23 Dec 2022 22:37:49 +0100 Subject: [PATCH 59/59] Bump Win2D to 1.27.0-preview1 --- src/ComputeSharp.D2D1.Uwp/ComputeSharp.D2D1.Uwp.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ComputeSharp.D2D1.Uwp/ComputeSharp.D2D1.Uwp.csproj b/src/ComputeSharp.D2D1.Uwp/ComputeSharp.D2D1.Uwp.csproj index 6f4838da..d095b616 100644 --- a/src/ComputeSharp.D2D1.Uwp/ComputeSharp.D2D1.Uwp.csproj +++ b/src/ComputeSharp.D2D1.Uwp/ComputeSharp.D2D1.Uwp.csproj @@ -37,7 +37,7 @@ - +