Initial implementation port of ICanvasImageInterop from Win2D

このコミットが含まれているのは:
Sergio Pedri committed 2022-12-22 10:56:03 -08:00
1 親 7a51426988
コミット 139ad8ed62
9ファイル変更
+347 -44

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

+2 -2
ファイルの表示
@@ -21,7 +21,7 @@ internal unsafe interface ICanvasImageInterop
/// <returns>The <see cref="HRESULT"/> for the operation.</returns>
[PreserveSig]
[return: NativeTypeName("HRESULT")]
int GetDevice([NativeTypeName("ICanvasDevice**")] IUnknown** device);
int GetDevice(ICanvasDevice** device);
/// <summary>
/// Gets an <see cref="ID2D1Image"/> from an <see cref="ICanvasImageInterop"/> 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,
+38
ファイルの表示
@@ -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;
/// <summary>
/// A <see langword="class"/> with extensions for the <see cref="ICanvasDevice"/> type.
/// </summary>
internal static unsafe class ICanvasDeviceExtensions
{
/// <summary>
/// Gets the underlying <see cref="ID2D1Device1"/> object from an <see cref="ICanvasDevice"/> object.
/// </summary>
/// <param name="canvasDevice">The input <see cref="ICanvasDevice"/> object.</param>
/// <param name="d2D1Device1">The underlying <see cref="ID2D1Device1"/> object for <paramref name="canvasDevice"/>.</param>
/// <returns>The <see cref="HRESULT"/> for the operation.</returns>
public static HRESULT GetD2DDevice(this ref ICanvasDevice canvasDevice, ID2D1Device1** d2D1Device1)
{
using ComPtr<ICanvasResourceWrapperNative> canvasDeviceResourceWrapperNative = default;
// Get the ICanvasResourceWrapperNative wrapper around the input device
canvasDevice.QueryInterface(
riid: Win32.__uuidof<ICanvasResourceWrapperNative>(),
ppvObject: (void**)canvasDeviceResourceWrapperNative.GetAddressOf()).Assert();
// Get the underlying ID2D1Device1 instance in use
HRESULT hresult = canvasDeviceResourceWrapperNative.Get()->GetNativeResource(
device: null,
dpi: 0,
iid: Win32.__uuidof<ID2D1Device1>(),
resource: (void**)d2D1Device1);
return hresult;
}
}
+60
ファイルの表示
@@ -0,0 +1,60 @@
using ComputeSharp.D2D1.Extensions;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
namespace ComputeSharp.D2D1.Uwp.Extensions;
/// <summary>
/// A <see langword="class"/> with extensions for the <see cref="ID2D1DeviceContext"/> type.
/// </summary>
internal static unsafe class ID2D1DeviceContextExtensions
{
/// <summary>
/// Checks whether a given <see cref="ID2D1DeviceContext"/> has an <see cref="ID2D1CommandList"/> as render target.
/// </summary>
/// <param name="deviceContext">The input <see cref="ID2D1DeviceContext"/> instance to check.</param>
/// <returns>Whether the target of <paramref name="deviceContext"/> is an <see cref="ID2D1CommandList"/>.</returns>
public static bool HasCommandListTarget(this ref ID2D1DeviceContext deviceContext)
{
using ComPtr<ID2D1Image> 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<ID2D1CommandList> 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;
}
/// <summary>
/// Reads the DPI value from a target <see cref="ID2D1DeviceContext"/> object.
/// </summary>
/// <param name="deviceContext">The input <see cref="ID2D1DeviceContext"/> instance.</param>
/// <returns>The DPIs from <paramref name="deviceContext"/>.</returns>
public static float GetDpi(this ref ID2D1DeviceContext deviceContext)
{
float dpiX;
float dpiY;
deviceContext.GetDpi(&dpiX, &dpiY);
return dpiX;
}
}
+3 -1
ファイルの表示
@@ -47,6 +47,8 @@ partial class PixelShaderEffect<T>
/// <inheritdoc/>
void IReferenceTrackedObject.DangerousOnDispose()
{
// TODO
this.canvasDevice.Dispose();
this.d2D1RealizationDevice.Dispose();
this.d2D1Effect.Dispose();
}
}
+209 -41
ファイルの表示
@@ -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 <see cref="ICanvasImage"/> implementation powered by a supplied shader type.
/// </summary>
/// <typeparam name="T">The type of shader to use to render frames.</typeparam>
public sealed class PixelShaderEffect<T> : ICanvasImage, ICanvasImageInterop
public sealed partial class PixelShaderEffect<T> : IReferenceTrackedObject, ICanvasImage, ICanvasImageInterop
where T : unmanaged, ID2D1PixelShader
{
/// <summary>
/// The <see cref="ReferenceTracker"/> value for the current instance.
/// </summary>
private ReferenceTracker referenceTracker;
/// <summary>
/// Lock object used to synchronize calls to <see cref="ICanvasImageInterop"/> APIs.
/// </summary>
private readonly object lockObject = new();
/// <summary>
/// Flag to track whether a given call is recursively invoked by <see cref="ICanvasImageInterop.GetD2DImage"/>, to avoid graph cycles.
/// </summary>
private volatile int isInsideGetD2DImage;
/// <summary>
/// The current device the effect is realized on, if one is available (this is the underlying COM object for <see cref="CanvasDevice"/>).
/// </summary>
private ComPtr<ICanvasDevice> canvasDevice;
/// <summary>
/// The underlying D2D1 device the effect is realized on, if one is available (this is the D2D device backing <see cref="canvasDevice"/>).
/// </summary>
private ComPtr<ID2D1Device1> d2D1RealizationDevice;
/// <summary>
/// The current realized <see cref="ID2D1Effect"/>, if one is available.
/// </summary>
private ComPtr<ID2D1Effect> d2D1Effect;
/// <summary>
/// The current <typeparamref name="T"/> value in use.
/// </summary>
public T Value;
private ComPtr<ID2D1Effect> effect;
/// <inheritdoc/>
public void Dispose()
{
}
/// <inheritdoc/>
Rect ICanvasImage.GetBounds(ICanvasResourceCreator resourceCreator)
{
throw new NotImplementedException();
throw new NotSupportedException();
}
/// <inheritdoc/>
Rect ICanvasImage.GetBounds(ICanvasResourceCreator resourceCreator, Matrix3x2 transform)
{
throw new NotImplementedException();
throw new NotSupportedException();
}
/// <inheritdoc/>
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);
}
}
/// <inheritdoc/>
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<ID2D1Factory> 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<ID2D1Factory1> d2D1Factory1 = default;
// ReadDpiFromDeviceContext has been processed, so it can be removed now
flags &= ~CanvasImageGetD2DImageFlags.ReadDpiFromDeviceContext;
}
d2D1Factory.CopyTo(d2D1Factory1.GetAddressOf()).Assert();
using ComPtr<ID2D1Device1> d2D1Device1 = default;
D2D1PixelShaderEffect.RegisterForD2D1Factory1<T>(d2D1Factory1.Get(), out _);
// Get the underlying ID2D1Device1 instance in use
device->GetD2DDevice(d2D1Device1.GetAddressOf()).Assert();
using ComPtr<ID2D1Effect> 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<T>(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<ICanvasDevice>(), (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;
}
}
/// <summary>
/// Unrealizes the currently realized <see cref="ID2D1Effect"/> object.
/// </summary>
private unsafe void Unrealize()
{
// If there is no ID2D1Effect object, there is nothing left to do
if (this.d2D1Effect.Get() is null)
{
return;
}
// TODO
}
/// <summary>
/// Realizes the underlying <see cref="ID2D1Effect"/> for this object.
/// </summary>
/// <param name="flags">The current flags in use.</param>
/// <param name="targetDpi">The target DPI in use.</param>
/// <param name="deviceContext">The <see cref="ID2D1DeviceContext"/> instance in use.</param>
private unsafe void Realize(CanvasImageGetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext)
{
using ComPtr<ID2D1Factory> d2D1Factory = default;
// Get the underlying ID2D1Factory from the input context, so we can register and create the effect
deviceContext->GetFactory(d2D1Factory.GetAddressOf());
using ComPtr<ID2D1Factory1> 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<T>(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<T>(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());
}
/// <summary>
/// Updates the draw state for the currently realized effect.
/// </summary>
/// <param name="flags">The current flags in use.</param>
/// <param name="targetDpi">The target DPI in use.</param>
/// <param name="deviceContext">The <see cref="ID2D1DeviceContext"/> instance in use.</param>
private unsafe void RefreshInputs(CanvasImageGetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext)
{
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.d2D1Effect.Get());
// TODO
}
}
+17
ファイルの表示
@@ -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;
}
+14
ファイルの表示
@@ -26,10 +26,24 @@ internal unsafe partial struct ID2D1DeviceContext
((delegate* unmanaged[Stdcall]<ID2D1DeviceContext*, ID2D1Factory**, void>)(lpVtbl[3]))((ID2D1DeviceContext*)Unsafe.AsPointer(ref this), factory);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(52)]
public void GetDpi(float* dpiX, float* dpiY)
{
((delegate* unmanaged[Stdcall]<ID2D1DeviceContext*, float*, float*, void>)(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]<ID2D1DeviceContext*, Guid*, ID2D1Effect**, int>)(lpVtbl[63]))((ID2D1DeviceContext*)Unsafe.AsPointer(ref this), effectId, effect);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(75)]
public void GetTarget(ID2D1Image** image)
{
((delegate* unmanaged[Stdcall]<ID2D1DeviceContext*, ID2D1Image**, void>)(lpVtbl[75]))((ID2D1DeviceContext*)Unsafe.AsPointer(ref this), image);
}
}
+1
ファイルの表示
@@ -33,6 +33,7 @@
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d2d1_1\D2D1_CHANNEL_DEPTH.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d2d1_1\D2D1_BUFFER_PRECISION.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d2d1_1\D2D1_PROPERTY_TYPE.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d2d1_1\ID2D1CommandList.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d2d1_1\ID2D1DeviceContext.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d2d1_1\ID2D1Effect.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DirectX\um\d2d1_1\ID2D1Factory1.cs" />
+3
ファイルの表示
@@ -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));
}