diff --git a/src/ComputeSharp.Core/Polyfills/ArgumentOutOfRangeExceptionExtensions.cs b/src/ComputeSharp.Core/Polyfills/ArgumentOutOfRangeExceptionExtensions.cs
index 0e617bdf..1533c5cc 100644
--- a/src/ComputeSharp.Core/Polyfills/ArgumentOutOfRangeExceptionExtensions.cs
+++ b/src/ComputeSharp.Core/Polyfills/ArgumentOutOfRangeExceptionExtensions.cs
@@ -69,6 +69,22 @@ internal static class ArgumentOutOfRangeExceptionExtensions
}
}
+ ///
+ /// Throws an if is greater than or equal to .
+ ///
+ /// Dummy value to invoke the extension upon (always pass .
+ /// The argument to validate as less or equal than .
+ /// The value to compare with .
+ /// The name of the parameter with which corresponds.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void ThrowIfGreaterThanOrEqual(this ArgumentOutOfRangeException? _, int value, int other, [CallerArgumentExpression(nameof(value))] string? parameterName = null)
+ {
+ if (value >= other)
+ {
+ Throw(parameterName, value);
+ }
+ }
+
///
/// Throws an if is less than .
///
@@ -118,6 +134,22 @@ internal static class ArgumentOutOfRangeExceptionExtensions
}
}
+ ///
+ /// Throws an if is not equal to a given other value.
+ ///
+ /// Dummy value to invoke the extension upon (always pass .
+ /// The argument to validate.
+ /// The value to compare against.
+ /// The name of the parameter with which corresponds.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void ThrowIfNotEqual(this ArgumentOutOfRangeException? _, int value, int other, [CallerArgumentExpression(nameof(value))] string? parameterName = null)
+ {
+ if (value != other)
+ {
+ Throw(parameterName, value);
+ }
+ }
+
///
/// Throws an if is not in the specified range.
///
diff --git a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasEffectFactoryNative.cs b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasEffectFactoryNative.cs
index a894c2f2..0fcc7e0e 100644
--- a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasEffectFactoryNative.cs
+++ b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasEffectFactoryNative.cs
@@ -2,7 +2,7 @@ using System;
using System.Runtime.CompilerServices;
using ABI.Microsoft.Graphics.Canvas;
using ComputeSharp.D2D1.Extensions;
-using ComputeSharp.D2D1.Interop.Effects;
+using ComputeSharp.D2D1.Interop;
#if WINDOWS_UWP
using ComputeSharp.D2D1.Uwp.Extensions;
using ComputeSharp.D2D1.Uwp.Helpers;
@@ -74,7 +74,7 @@ unsafe partial class PixelShaderEffect
if (!this.isEffectFactoryRegistered)
{
ResourceManager.RegisterEffectFactory(
- effectId: PixelShaderEffect.For.Instance.Id,
+ effectId: D2D1PixelShaderEffect.GetEffectId(),
factory: new EffectFactory());
this.isEffectFactoryRegistered = true;
diff --git a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasImageInterop.cs
index 796bd28a..f63e388e 100644
--- a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasImageInterop.cs
+++ b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasImageInterop.cs
@@ -4,7 +4,6 @@ using System.Threading;
using ABI.Microsoft.Graphics.Canvas;
using ComputeSharp.D2D1.Extensions;
using ComputeSharp.D2D1.Interop;
-using ComputeSharp.D2D1.Interop.Effects;
#if WINDOWS_UWP
using ComputeSharp.D2D1.Uwp.Extensions;
using ComputeSharp.D2D1.Uwp.Helpers;
@@ -262,7 +261,7 @@ unsafe partial class PixelShaderEffect
{
fixed (ID2D1Effect** d2D1Effect = this.d2D1Effect)
{
- Guid effectId = PixelShaderEffect.For.Instance.Id;
+ Guid effectId = D2D1PixelShaderEffect.GetEffectId();
using ComPtr d2D1DeviceContextEffective = default;
using ComPtr d2D1DeviceContextLease = default;
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs
index 46941807..7e9dcbfb 100644
--- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs
@@ -188,7 +188,7 @@ public static unsafe class D2D1PixelShaderEffect
d2D1PropertyBinding[D2D1PixelShaderEffectProperty.ResourceTextureManager14].setFunction = PixelShaderEffect.SetResourceTextureManager14;
d2D1PropertyBinding[D2D1PixelShaderEffectProperty.ResourceTextureManager15].setFunction = PixelShaderEffect.SetResourceTextureManager15;
- fixed (Guid* pGuid = &PixelShaderEffect.For.Instance.Id)
+ fixed (Guid* pGuid = &GetEffectId())
{
// Register the effect
((ID2D1Factory1*)d2D1Factory1)->RegisterEffectFromString(
@@ -196,10 +196,10 @@ public static unsafe class D2D1PixelShaderEffect
propertyXml: (ushort*)pXml,
bindings: d2D1PropertyBinding,
bindingsCount: (uint)(D2D1PixelShaderEffectProperty.NumberOfAlwaysAvailableProperties + D2D1PixelShader.GetResourceTextureCount()),
- effectFactory: PixelShaderEffect.For.Instance.Factory).Assert();
+ effectFactory: PixelShaderEffect.Globals.Instance.Factory).Assert();
}
- effectId = PixelShaderEffect.For.Instance.Id;
+ effectId = GetEffectId();
}
}
@@ -250,8 +250,8 @@ public static unsafe class D2D1PixelShaderEffect
writer.Write(D2D1EffectRegistrationData.V1.BlobId);
// Effect id and number of inputs
- writer.Write(PixelShaderEffect.For.Instance.Id);
- writer.Write(PixelShaderEffect.For.Instance.InputCount);
+ writer.Write(GetEffectId());
+ writer.Write(D2D1PixelShader.GetInputCount());
// Retrieve the effect XML and include it into the registration blob
using (D2D1EffectXmlFactory.EffectXml effectXml = D2D1EffectXmlFactory.GetXmlBuffer())
@@ -388,14 +388,14 @@ public static unsafe class D2D1PixelShaderEffect
}
// Effect factory
- writer.Write((nint)PixelShaderEffect.For.Instance.Factory);
+ writer.Write((nint)PixelShaderEffect.Globals.Instance.Factory);
byte[] registrationBlob = writer.WrittenSpan.ToArray();
writer.Dispose();
// Extract the effect id (the same that was encoded in the registration blob)
- effectId = PixelShaderEffect.For.Instance.Id;
+ effectId = GetEffectId();
return registrationBlob;
}
@@ -419,7 +419,7 @@ public static unsafe class D2D1PixelShaderEffect
default(ArgumentNullException).ThrowIfNull(d2D1DeviceContext);
default(ArgumentNullException).ThrowIfNull(d2D1Effect);
- fixed (Guid* pGuid = &PixelShaderEffect.For.Instance.Id)
+ fixed (Guid* pGuid = &GetEffectId())
{
((ID2D1DeviceContext*)d2D1DeviceContext)->CreateEffect(
effectId: pGuid,
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs
deleted file mode 100644
index d9eba121..00000000
--- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs
+++ /dev/null
@@ -1,273 +0,0 @@
-using System;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using ComputeSharp.D2D1.Descriptors;
-using TerraFX.Interop.DirectX;
-using TerraFX.Interop.Windows;
-#if !NET6_0_OR_GREATER
-using RuntimeHelpers = ComputeSharp.NetStandard.RuntimeHelpers;
-#endif
-
-namespace ComputeSharp.D2D1.Interop.Effects;
-
-///
-/// A simple and implementation for a given pixel shader.
-///
-internal unsafe partial struct PixelShaderEffect
-{
- ///
- /// A wrapper for an effect factory.
- ///
- /// The resulting effect factory.
- /// The HRESULT for the operation.
- [UnmanagedFunctionPointer(CallingConvention.StdCall)]
- private delegate int FactoryDelegate(IUnknown** effectImpl);
-
- ///
- /// A generic pixel shader implementation.
- ///
- /// The type of shader.
- public sealed class For
- where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor
- {
- ///
- /// The wrapper for the shader factory.
- ///
- private readonly FactoryDelegate effectFactory;
-
- ///
- /// The for the shader.
- ///
- ///
- /// This field could have used to reduce some verbosity where it is
- /// being used to pass its address to a native API, but the attribute is incompatible with collectible assemblies.
- /// Because of that, it can't be used, as this project is explicitly meant to support plugin-like scenarios.
- ///
- private readonly Guid shaderId;
-
- ///
- /// The size of the constant buffer for the shader.
- ///
- private readonly int constantBufferSize;
-
- ///
- /// The number of inputs for the shader.
- ///
- private readonly int inputCount;
-
- ///
- /// The buffer with the types of inputs for the shader.
- ///
- private readonly D2D1PixelShaderInputType* inputTypes;
-
- ///
- /// The number of available input descriptions.
- ///
- private readonly int inputDescriptionCount;
-
- ///
- /// The buffer with the available input descriptions for the shader.
- ///
- private readonly D2D1InputDescription* inputDescriptions;
-
- ///
- /// The pixel options for the shader.
- ///
- private readonly D2D1PixelOptions pixelOptions;
-
- ///
- /// The shader bytecode.
- ///
- private readonly byte* bytecode;
-
- ///
- /// The size of .
- ///
- private readonly int bytecodeSize;
-
- ///
- /// The buffer precision for the resulting output buffer.
- ///
- private readonly D2D1BufferPrecision bufferPrecision;
-
- ///
- /// The channel depth for the resulting output buffer.
- ///
- private readonly D2D1ChannelDepth channelDepth;
-
- ///
- /// The number of available resource texture descriptions.
- ///
- private readonly int resourceTextureDescriptionCount;
-
- ///
- /// The buffer with the available resource texture descriptions for the shader.
- ///
- private readonly D2D1ResourceTextureDescription* resourceTextureDescriptions;
-
- ///
- /// Creates a new instance with the specified parameters.
- ///
- /// The wrapper for the shader factory.
- /// The for the shader.
- /// The size of the constant buffer for the shader.
- /// The number of inputs for the shader.
- /// The buffer with the types of inputs for the shader.
- /// The number of available input descriptions.
- /// The buffer with the available input descriptions for the shader.
- /// The pixel options for the shader.
- /// The shader bytecode.
- /// The size of .
- /// The buffer precision for the resulting output buffer.
- /// The channel depth for the resulting output buffer.
- /// The number of available resource texture descriptions.
- /// The buffer with the available resource texture descriptions for the shader.
- private For(
- FactoryDelegate effectFactory,
- Guid shaderId,
- int constantBufferSize,
- int inputCount,
- D2D1PixelShaderInputType* inputTypes,
- int inputDescriptionCount,
- D2D1InputDescription* inputDescriptions,
- D2D1PixelOptions pixelOptions,
- byte* bytecode,
- int bytecodeSize,
- D2D1BufferPrecision bufferPrecision,
- D2D1ChannelDepth channelDepth,
- int resourceTextureDescriptionCount,
- D2D1ResourceTextureDescription* resourceTextureDescriptions)
- {
- this.effectFactory = effectFactory;
- this.shaderId = shaderId;
- this.constantBufferSize = constantBufferSize;
- this.inputCount = inputCount;
- this.inputTypes = inputTypes;
- this.inputDescriptionCount = inputDescriptionCount;
- this.inputDescriptions = inputDescriptions;
- this.pixelOptions = pixelOptions;
- this.bytecode = bytecode;
- this.bytecodeSize = bytecodeSize;
- this.bufferPrecision = bufferPrecision;
- this.channelDepth = channelDepth;
- this.resourceTextureDescriptionCount = resourceTextureDescriptionCount;
- this.resourceTextureDescriptions = resourceTextureDescriptions;
- }
-
- ///
- /// Gets the shared instance.
- ///
- public static For Instance { get; } = CreateInstance();
-
- ///
- /// Creates a new instance.
- ///
- /// The initialized instance.
- private static For CreateInstance()
- {
- // Load all shader properties
- Guid shaderId = D2D1PixelShaderEffect.GetEffectId();
- int constantBufferSize = D2D1PixelShader.GetConstantBufferSize();
- D2D1BufferPrecision bufferPrecision = D2D1PixelShader.GetOutputBufferPrecision();
- D2D1ChannelDepth channelDepth = D2D1PixelShader.GetOutputBufferChannelDepth();
- D2D1PixelOptions pixelOptions = D2D1PixelShader.GetPixelOptions();
-
- // Prepare the inputs info
- int inputCount = D2D1PixelShader.GetInputCount();
- D2D1PixelShaderInputType* inputTypes = (D2D1PixelShaderInputType*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), sizeof(D2D1PixelShaderInputType) * inputCount);
-
- D2D1PixelShader.GetInputTypes().Span.CopyTo(new Span(inputTypes, inputCount));
-
- // Prepare the input descriptions
- ReadOnlyMemory inputDescriptionsInfo = D2D1PixelShader.GetInputDescriptions();
- int inputDescriptionCount = inputDescriptionsInfo.Length;
- D2D1InputDescription* inputDescriptions = (D2D1InputDescription*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), sizeof(D2D1InputDescription) * inputDescriptionCount);
-
- inputDescriptionsInfo.Span.CopyTo(new Span(inputDescriptions, inputDescriptionCount));
-
- // Prepare the resource texture descriptions
- ReadOnlyMemory resourceTextureDescriptionsInfo = D2D1PixelShader.GetResourceTextureDescriptions();
- int resourceTextureDescriptionCount = resourceTextureDescriptionsInfo.Length;
- D2D1ResourceTextureDescription* resourceTextureDescriptions = (D2D1ResourceTextureDescription*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), sizeof(D2D1ResourceTextureDescription) * resourceTextureDescriptionCount);
-
- resourceTextureDescriptionsInfo.Span.CopyTo(new Span(resourceTextureDescriptions, resourceTextureDescriptionCount));
-
- // Copy the bytecode to the target buffer
- ReadOnlyMemory bytecodeInfo = D2D1PixelShader.LoadBytecode();
- int bytecodeSize = bytecodeInfo.Length;
- byte* bytecode = (byte*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), bytecodeSize);
-
- bytecodeInfo.Span.CopyTo(new Span(bytecode, bytecodeSize));
-
- // Initialize the shared instance with the computed state
- return new(
- CreateEffect,
- shaderId,
- constantBufferSize,
- inputCount,
- inputTypes,
- inputDescriptionCount,
- inputDescriptions,
- pixelOptions,
- bytecode,
- bytecodeSize,
- bufferPrecision,
- channelDepth,
- resourceTextureDescriptionCount,
- resourceTextureDescriptions);
- }
-
- ///
- /// Gets a reference to the id of the effect.
- ///
- public ref readonly Guid Id
- {
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- get => ref this.shaderId;
- }
-
- ///
- /// Gets the factory for the current effect.
- ///
-#if NET6_0_OR_GREATER
- public delegate* unmanaged[Stdcall] Factory
-#else
- public void* Factory
-#endif
- {
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
-#if NET6_0_OR_GREATER
- get => (delegate* unmanaged[Stdcall])Marshal.GetFunctionPointerForDelegate(this.effectFactory);
-#else
- get => (void*)Marshal.GetFunctionPointerForDelegate(this.effectFactory);
-#endif
- }
-
- ///
- /// Gets the number of inputs for the effect.
- ///
- public int InputCount => this.inputCount;
-
- ///
- private static int CreateEffect(IUnknown** effectImpl)
- {
- For instance = Instance;
-
- return PixelShaderEffect.Factory(
- instance.shaderId,
- instance.constantBufferSize,
- instance.inputCount,
- instance.inputTypes,
- instance.inputDescriptionCount,
- instance.inputDescriptions,
- instance.pixelOptions,
- instance.bytecode,
- instance.bytecodeSize,
- instance.bufferPrecision,
- instance.channelDepth,
- instance.resourceTextureDescriptionCount,
- instance.resourceTextureDescriptions,
- effectImpl);
- }
- }
-}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Globals{T}.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Globals{T}.cs
new file mode 100644
index 00000000..bc728ef2
--- /dev/null
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Globals{T}.cs
@@ -0,0 +1,170 @@
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using ComputeSharp.D2D1.Descriptors;
+using TerraFX.Interop.DirectX;
+using TerraFX.Interop.Windows;
+
+namespace ComputeSharp.D2D1.Interop.Effects;
+
+///
+/// A simple and implementation for a given pixel shader.
+///
+internal unsafe partial struct PixelShaderEffect
+{
+ ///
+ /// A wrapper for an effect factory.
+ ///
+ /// The resulting effect factory.
+ /// The HRESULT for the operation.
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)]
+ public delegate int FactoryDelegate(IUnknown** effectImpl);
+
+ ///
+ /// A base type with global values for pixel shader effects.
+ ///
+ public abstract class Globals
+ {
+ ///
+ /// Gets the wrapper for the shader factory.
+ ///
+ private readonly FactoryDelegate effectFactory;
+
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The wrapper for the shader factory.
+ protected Globals(FactoryDelegate effectFactory)
+ {
+ this.effectFactory = effectFactory;
+ }
+
+ ///
+ public abstract ref readonly Guid EffectId { get; }
+
+ ///
+ public abstract int ConstantBufferSize { get; }
+
+ ///
+ public abstract int InputCount { get; }
+
+ ///
+ public abstract int ResourceTextureCount { get; }
+
+ ///
+ public abstract ReadOnlyMemory InputTypes { get; }
+
+ ///
+ public abstract ReadOnlyMemory InputDescriptions { get; }
+
+ ///
+ public abstract ReadOnlyMemory ResourceTextureDescriptions { get; }
+
+ ///
+ public abstract D2D1PixelOptions PixelOptions { get; }
+
+ ///
+ public abstract D2D1BufferPrecision BufferPrecision { get; }
+
+ ///
+ public abstract D2D1ChannelDepth ChannelDepth { get; }
+
+ ///
+ public abstract ReadOnlyMemory HlslBytecode { get; }
+
+ ///
+ /// Gets the factory for the current effect.
+ ///
+#if NET6_0_OR_GREATER
+ public delegate* unmanaged[Stdcall] Factory
+#else
+ public void* Factory
+#endif
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+#if NET6_0_OR_GREATER
+ get => (delegate* unmanaged[Stdcall])Marshal.GetFunctionPointerForDelegate(this.effectFactory);
+#else
+ get => (void*)Marshal.GetFunctionPointerForDelegate(this.effectFactory);
+#endif
+ }
+ }
+
+ ///
+ /// A generic pixel shader implementation.
+ ///
+ /// The type of shader.
+ public sealed class Globals : Globals
+ where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor
+ {
+ ///
+ /// The HLSL bytecode (either precompiled, or the currently available one after compilation).
+ ///
+ private ReadOnlyMemory hlslBytecode;
+
+ ///
+ /// Creates a new instance for shaders of type .
+ ///
+ private Globals()
+ : base(CreateEffect)
+ {
+ }
+
+ ///
+ /// Gets the shared instance to use.
+ ///
+ public static Globals Instance { get; } = new();
+
+ ///
+ public override ref readonly Guid EffectId => ref D2D1PixelShaderEffect.GetEffectId();
+
+ ///
+ public override int ConstantBufferSize => D2D1PixelShader.GetConstantBufferSize();
+
+ ///
+ public override int InputCount => D2D1PixelShader.GetInputCount();
+
+ ///
+ public override int ResourceTextureCount => D2D1PixelShader.GetResourceTextureCount();
+
+ ///
+ public override ReadOnlyMemory InputTypes => D2D1PixelShader.GetInputTypes();
+
+ ///
+ public override ReadOnlyMemory InputDescriptions => D2D1PixelShader.GetInputDescriptions();
+
+ ///
+ public override ReadOnlyMemory ResourceTextureDescriptions => D2D1PixelShader.GetResourceTextureDescriptions();
+
+ ///
+ public override D2D1PixelOptions PixelOptions => D2D1PixelShader.GetPixelOptions();
+
+ ///
+ public override D2D1BufferPrecision BufferPrecision => D2D1PixelShader.GetOutputBufferPrecision();
+
+ ///
+ public override D2D1ChannelDepth ChannelDepth => D2D1PixelShader.GetOutputBufferChannelDepth();
+
+ ///
+ public override ReadOnlyMemory HlslBytecode
+ {
+ get
+ {
+ // Fast path if we already have some bytecode (either precompiled, or already compiled)
+ if (this.hlslBytecode is ReadOnlyMemory { Length: > 0 } hlslBytecode)
+ {
+ return hlslBytecode;
+ }
+
+ // If not, lazily compile the bytecode when requested
+ return this.hlslBytecode = D2D1PixelShader.LoadBytecode();
+ }
+ }
+
+ ///
+ private static int CreateEffect(IUnknown** effectImpl)
+ {
+ return PixelShaderEffect.Factory(Instance, effectImpl);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs
index 21ebdd53..94367676 100644
--- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs
@@ -110,7 +110,16 @@ partial struct PixelShaderEffect
{
@this = (PixelShaderEffect*)&((void**)@this)[-1];
- return (uint)@this->inputCount;
+ try
+ {
+ return (uint)@this->GetGlobals().InputCount;
+ }
+ catch
+ {
+ // GetInputCount doesn't respect COM, so it does not return an HRESULT.
+ // The only thing we can do in this case is just to return 0 instead.
+ return 0;
+ }
}
///
@@ -119,45 +128,46 @@ partial struct PixelShaderEffect
{
@this = (PixelShaderEffect*)&((void**)@this)[-1];
- if (inputRectsCount != @this->inputCount)
+ try
{
- return E.E_INVALIDARG;
- }
+ default(ArgumentOutOfRangeException).ThrowIfNotEqual((int)inputRectsCount, @this->GetGlobals().InputCount, nameof(inputRectsCount));
- if (@this->d2D1TransformMapper is not null)
- {
- // Forward to the current ID2D1TransformMapper instance
- HRESULT hresult = @this->d2D1TransformMapper->MapOutputRectToInputRects(outputRect, inputRects, inputRectsCount);
-
- if (!Windows.SUCCEEDED(hresult))
+ if (@this->d2D1TransformMapper is not null)
{
- return hresult;
+ // Forward to the current ID2D1TransformMapper instance
+ @this->d2D1TransformMapper->MapOutputRectToInputRects(outputRect, inputRects, inputRectsCount).Assert();
}
- }
- else
- {
- // If no custom transform is used, apply the default mapping. In this case, the loop will
- // automatically handle cases where no inputs are defined. If inputs are present instead,
- // the default mapping will set the input rect for a simple input to be the same as the
- // output rect, and the input rect for a complex rect to be infinite. In both cases, D2D
- // will handle clipping the inputs to the actual output rect area, if needed.
- for (uint i = 0; i < inputRectsCount; i++)
+ else
{
- switch (@this->inputTypes[i])
+ ReadOnlySpan inputTypes = @this->GetGlobals().InputTypes.Span;
+
+ // If no custom transform is used, apply the default mapping. In this case, the loop will
+ // automatically handle cases where no inputs are defined. If inputs are present instead,
+ // the default mapping will set the input rect for a simple input to be the same as the
+ // output rect, and the input rect for a complex rect to be infinite. In both cases, D2D
+ // will handle clipping the inputs to the actual output rect area, if needed.
+ for (uint i = 0; i < inputRectsCount; i++)
{
- case D2D1PixelShaderInputType.Simple:
- inputRects[i] = *outputRect;
- break;
- case D2D1PixelShaderInputType.Complex:
- inputRects[i].MakeD2D1Infinite();
- break;
- default:
- return E.E_FAIL;
+ switch (inputTypes[(int)i])
+ {
+ case D2D1PixelShaderInputType.Simple:
+ inputRects[i] = *outputRect;
+ break;
+ case D2D1PixelShaderInputType.Complex:
+ inputRects[i].MakeD2D1Infinite();
+ break;
+ default:
+ return E.E_FAIL;
+ }
}
}
- }
- return S.S_OK;
+ return S.S_OK;
+ }
+ catch (Exception e)
+ {
+ return Marshal.GetHRForException(e);
+ }
}
///
@@ -166,91 +176,90 @@ partial struct PixelShaderEffect
{
@this = (PixelShaderEffect*)&((void**)@this)[-1];
- if (inputRectCount != @this->inputCount)
+ try
{
- return E.E_INVALIDARG;
- }
+ default(ArgumentOutOfRangeException).ThrowIfNotEqual((int)inputRectCount, @this->GetGlobals().InputCount, nameof(inputRectCount));
- if (@this->d2D1TransformMapper is not null)
- {
- using ComPtr d2D1DrawInfoUpdateContext = default;
-
- // Create an ID2D1DrawInfoUpdateContext instance
- HRESULT hresult = D2D1DrawInfoUpdateContextImpl.Factory(
- drawInfoUpdateContext: d2D1DrawInfoUpdateContext.GetAddressOf(),
- constantBuffer: @this->constantBuffer,
- constantBufferSize: @this->constantBufferSize,
- d2D1DrawInfo: @this->d2D1DrawInfo);
-
- if (!Windows.SUCCEEDED(hresult))
+ if (@this->d2D1TransformMapper is not null)
{
- return hresult;
+ using ComPtr d2D1DrawInfoUpdateContext = default;
+
+ // Create an ID2D1DrawInfoUpdateContext instance
+ D2D1DrawInfoUpdateContextImpl.Factory(
+ drawInfoUpdateContext: d2D1DrawInfoUpdateContext.GetAddressOf(),
+ constantBuffer: @this->constantBuffer,
+ constantBufferSize: @this->GetGlobals().ConstantBufferSize,
+ d2D1DrawInfo: @this->d2D1DrawInfo).Assert();
+
+ // Forward the call to the input ID2D1TransformMapper instance
+ HRESULT hresult = @this->d2D1TransformMapper->MapInputRectsToOutputRect(
+ updateContext: (ID2D1DrawInfoUpdateContext*)d2D1DrawInfoUpdateContext.Get(),
+ inputRects: inputRects,
+ inputOpaqueSubRects: inputOpaqueSubRects,
+ inputRectCount: inputRectCount,
+ outputRect: outputRect,
+ outputOpaqueSubRect: outputOpaqueSubRect);
+
+ // Regardless of the operation result, always invalidate the context
+ d2D1DrawInfoUpdateContext.Get()->Close().Assert();
+
+ // Now we can validate that the call was in fact successful
+ hresult.Assert();
}
-
- // Forward the call to the input ID2D1TransformMapper instance
- hresult = @this->d2D1TransformMapper->MapInputRectsToOutputRect(
- updateContext: (ID2D1DrawInfoUpdateContext*)d2D1DrawInfoUpdateContext.Get(),
- inputRects: inputRects,
- inputOpaqueSubRects: inputOpaqueSubRects,
- inputRectCount: inputRectCount,
- outputRect: outputRect,
- outputOpaqueSubRect: outputOpaqueSubRect);
-
- // Regardless of the operation result, always invalidate the context
- _ = d2D1DrawInfoUpdateContext.Get()->Close();
-
- if (!Windows.SUCCEEDED(hresult))
- {
- return hresult;
- }
- }
- else if (inputRectCount == 0)
- {
- // If there are no inputs, make the output rectangle infinite. This is useful
- // to make output-only effects work fine by default, without needing a custom
- // transform. In this case, the target area will be the output node anyway.
- outputRect->MakeD2D1Infinite();
-
- *outputOpaqueSubRect = default;
- }
- else
- {
- // If at least one input is present and no custom mapper is available, apply the default
- // mapping. In this case, the output rect should be the union of the input rects for all
- // the simple shader inputs, or infinite if there are no simple inputs. The input rects
- // for complex inputs, if present, are not needed in this scenario, so they're ignored.
- RECT unionOfSimpleRects = default;
- bool isUnionOfSimpleRectsEmpty = true;
-
- for (uint i = 0; i < inputRectCount; i++)
- {
- if (@this->inputTypes[i] == D2D1PixelShaderInputType.Simple)
- {
- if (isUnionOfSimpleRectsEmpty)
- {
- unionOfSimpleRects = inputRects[i];
- isUnionOfSimpleRectsEmpty = false;
- }
- else
- {
- unionOfSimpleRects = unionOfSimpleRects.Union(inputRects[i]);
- }
- }
- }
-
- if (isUnionOfSimpleRectsEmpty)
+ else if (inputRectCount == 0)
{
+ // If there are no inputs, make the output rectangle infinite. This is useful
+ // to make output-only effects work fine by default, without needing a custom
+ // transform. In this case, the target area will be the output node anyway.
outputRect->MakeD2D1Infinite();
+
+ *outputOpaqueSubRect = default;
}
else
{
- *outputRect = unionOfSimpleRects;
+ ReadOnlySpan inputTypes = @this->GetGlobals().InputTypes.Span;
+
+ // If at least one input is present and no custom mapper is available, apply the default
+ // mapping. In this case, the output rect should be the union of the input rects for all
+ // the simple shader inputs, or infinite if there are no simple inputs. The input rects
+ // for complex inputs, if present, are not needed in this scenario, so they're ignored.
+ RECT unionOfSimpleRects = default;
+ bool isUnionOfSimpleRectsEmpty = true;
+
+ for (uint i = 0; i < inputRectCount; i++)
+ {
+ if (inputTypes[(int)i] == D2D1PixelShaderInputType.Simple)
+ {
+ if (isUnionOfSimpleRectsEmpty)
+ {
+ unionOfSimpleRects = inputRects[i];
+ isUnionOfSimpleRectsEmpty = false;
+ }
+ else
+ {
+ unionOfSimpleRects = unionOfSimpleRects.Union(inputRects[i]);
+ }
+ }
+ }
+
+ if (isUnionOfSimpleRectsEmpty)
+ {
+ outputRect->MakeD2D1Infinite();
+ }
+ else
+ {
+ *outputRect = unionOfSimpleRects;
+ }
+
+ *outputOpaqueSubRect = default;
}
- *outputOpaqueSubRect = default;
+ return S.S_OK;
+ }
+ catch (Exception e)
+ {
+ return Marshal.GetHRForException(e);
}
-
- return S.S_OK;
}
///
@@ -259,39 +268,38 @@ partial struct PixelShaderEffect
{
@this = (PixelShaderEffect*)&((void**)@this)[-1];
- if (inputIndex >= (uint)@this->inputCount)
+ try
{
- return E.E_INVALIDARG;
- }
+ default(ArgumentOutOfRangeException).ThrowIfGreaterThanOrEqual((int)inputIndex, @this->GetGlobals().InputCount, nameof(inputIndex));
- if (@this->d2D1TransformMapper is not null)
- {
- // Forward to the current ID2D1TransformMapper instance
- HRESULT hresult = @this->d2D1TransformMapper->MapInvalidRect(inputIndex, invalidInputRect, invalidOutputRect);
-
- if (!Windows.SUCCEEDED(hresult))
+ if (@this->d2D1TransformMapper is not null)
{
- return hresult;
+ // Forward to the current ID2D1TransformMapper instance
+ @this->d2D1TransformMapper->MapInvalidRect(inputIndex, invalidInputRect, invalidOutputRect).Assert();
}
- }
- else
- {
- // The default mapping in this scenario just needs to set the invalid output rect for simple inputs to
- // be the invalid input rect, and to set the invalid output rect for complex inputs to an infinite rect.
- switch (@this->inputTypes[inputIndex])
+ else
{
- case D2D1PixelShaderInputType.Simple:
- *invalidOutputRect = invalidInputRect;
- break;
- case D2D1PixelShaderInputType.Complex:
- invalidOutputRect->MakeD2D1Infinite();
- break;
- default:
- return E.E_FAIL;
+ // The default mapping in this scenario just needs to set the invalid output rect for simple inputs to
+ // be the invalid input rect, and to set the invalid output rect for complex inputs to an infinite rect.
+ switch (@this->GetGlobals().InputTypes.Span[(int)inputIndex])
+ {
+ case D2D1PixelShaderInputType.Simple:
+ *invalidOutputRect = invalidInputRect;
+ break;
+ case D2D1PixelShaderInputType.Complex:
+ invalidOutputRect->MakeD2D1Infinite();
+ break;
+ default:
+ return E.E_FAIL;
+ }
}
- }
- return S.S_OK;
+ return S.S_OK;
+ }
+ catch (Exception e)
+ {
+ return Marshal.GetHRForException(e);
+ }
}
///
@@ -300,60 +308,45 @@ partial struct PixelShaderEffect
{
@this = (PixelShaderEffect*)&((void**)@this)[-1];
- // Free the previous ID2D1DrawInfo object, if present
- if (@this->d2D1DrawInfo is not null)
+ try
{
- _ = @this->d2D1DrawInfo->Release();
- }
+ // Store the new ID2D1DrawInfo object
+ ComPtr.CopyTo(drawInfo, ref @this->d2D1DrawInfo);
- // Store the new ID2D1DrawInfo object
- _ = drawInfo->AddRef();
+ Guid shaderId = @this->GetGlobals().EffectId;
+ D2D1PixelOptions pixelOptions = @this->GetGlobals().PixelOptions;
- @this->d2D1DrawInfo = drawInfo;
+ // Set the pixel shader for the effect
+ drawInfo->SetPixelShader(&shaderId, (D2D1_PIXEL_OPTIONS)pixelOptions).Assert();
- // Set the pixel shader for the effect
- HRESULT hresult = drawInfo->SetPixelShader(&@this->shaderId, (D2D1_PIXEL_OPTIONS)@this->pixelOptions);
-
- if (hresult != S.S_OK)
- {
- return hresult;
- }
-
- // If any input descriptions are present, set them
- if (@this->inputDescriptionCount > 0)
- {
- for (int i = 0; i < @this->inputDescriptionCount; i++)
+ // If any input descriptions are present, set them
+ foreach (ref readonly D2D1InputDescription inputDescription in @this->GetGlobals().InputDescriptions.Span)
{
- ref D2D1InputDescription inputDescription = ref @this->inputDescriptions[i];
-
D2D1_INPUT_DESCRIPTION d2D1InputDescription;
d2D1InputDescription.filter = (D2D1_FILTER)inputDescription.Filter;
d2D1InputDescription.levelOfDetailCount = (uint)inputDescription.LevelOfDetailCount;
- hresult = drawInfo->SetInputDescription((uint)inputDescription.Index, d2D1InputDescription);
-
- if (hresult != S.S_OK)
- {
- return hresult;
- }
+ drawInfo->SetInputDescription((uint)inputDescription.Index, d2D1InputDescription).Assert();
}
- }
- // If a custom buffer precision or channel depth is requested, set it
- if (@this->bufferPrecision != D2D1BufferPrecision.Unknown ||
- @this->channelDepth != D2D1ChannelDepth.Default)
- {
- hresult = drawInfo->SetOutputBuffer(
- (D2D1_BUFFER_PRECISION)@this->bufferPrecision,
- (D2D1_CHANNEL_DEPTH)@this->channelDepth);
+ D2D1BufferPrecision bufferPrecision = @this->GetGlobals().BufferPrecision;
+ D2D1ChannelDepth channelDepth = @this->GetGlobals().ChannelDepth;
- if (hresult != S.S_OK)
+ // If a custom buffer precision or channel depth is requested, set it
+ if (bufferPrecision != D2D1BufferPrecision.Unknown ||
+ channelDepth != D2D1ChannelDepth.Default)
{
- return hresult;
+ drawInfo->SetOutputBuffer(
+ (D2D1_BUFFER_PRECISION)bufferPrecision,
+ (D2D1_CHANNEL_DEPTH)channelDepth).Assert();
}
- }
- return S.S_OK;
+ return S.S_OK;
+ }
+ catch (Exception e)
+ {
+ return Marshal.GetHRForException(e);
+ }
}
}
}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs
index 2450925e..18c454be 100644
--- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs
@@ -1,5 +1,6 @@
using System;
using System.Runtime.InteropServices;
+using ComputeSharp.D2D1.Extensions;
using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers;
using ComputeSharp.D2D1.Shaders.Interop.Extensions;
using TerraFX.Interop.DirectX;
@@ -86,115 +87,106 @@ internal unsafe partial struct PixelShaderEffect
[UnmanagedCallersOnly]
public static int Initialize(PixelShaderEffect* @this, ID2D1EffectContext* effectContext, ID2D1TransformGraph* transformGraph)
{
- int hresult = effectContext->LoadPixelShader(
- shaderId: &@this->shaderId,
- shaderBuffer: @this->bytecode,
- shaderBufferCount: (uint)@this->bytecodeSize);
-
- // If E_INVALIDARG was returned, try to check whether double precision support was requested when not available. This
- // is only done to provide a more helpful error message to callers. If no error was returned, the behavior is the same.
- // If any error is detected while trying to check for shader support, ignore the value and propagate the current HRESULT.
- if (hresult == E.E_INVALIDARG && effectContext->IsShaderSupported(@this->bytecode, @this->bytecodeSize) == S.S_FALSE)
+ try
{
- hresult = D2DERR.D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES;
- }
+ ReadOnlySpan bytecode = @this->GetGlobals().HlslBytecode.Span;
- // If loading the bytecode succeeded, set the transform node
- if (Windows.SUCCEEDED(hresult))
- {
- hresult = transformGraph->SetSingleTransformNode((ID2D1TransformNode*)&@this->lpVtblForID2D1DrawTransform);
- }
-
- // If the transform node was set, also store the effect context
- if (Windows.SUCCEEDED(hresult))
- {
- // Free the previous ID2D1EffectContext object, if present
- if (@this->d2D1EffectContext is not null)
+ fixed (Guid* pShaderId = &@this->GetGlobals().EffectId)
+ fixed (byte* pBytecode = bytecode)
{
- _ = @this->d2D1EffectContext->Release();
+ HRESULT hresult = effectContext->LoadPixelShader(
+ shaderId: pShaderId,
+ shaderBuffer: pBytecode,
+ shaderBufferCount: (uint)bytecode.Length);
+
+ // If E_INVALIDARG was returned, try to check whether double precision support was requested when not available. This
+ // is only done to provide a more helpful error message to callers. If no error was returned, the behavior is the same.
+ // If any error is detected while trying to check for shader support, ignore the value and propagate the current HRESULT.
+ if (hresult == E.E_INVALIDARG && effectContext->IsShaderSupported(pBytecode, bytecode.Length) == S.S_FALSE)
+ {
+ hresult = D2DERR.D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES;
+ }
+
+ // Finally, assert that we did load the pixel shader correctly
+ hresult.Assert();
}
+ // If loading the bytecode succeeded, set the transform node
+ transformGraph->SetSingleTransformNode((ID2D1TransformNode*)&@this->lpVtblForID2D1DrawTransform).Assert();
+
// Store the new ID2D1EffectContext object
- _ = effectContext->AddRef();
+ ComPtr.CopyTo(effectContext, ref @this->d2D1EffectContext);
- @this->d2D1EffectContext = effectContext;
+ return S.S_OK;
+ }
+ catch (Exception e)
+ {
+ return Marshal.GetHRForException(e);
}
-
- return hresult;
}
///
[UnmanagedCallersOnly]
public static int PrepareForRender(PixelShaderEffect* @this, D2D1_CHANGE_TYPE changeType)
{
- int hresult = S.S_OK;
-
- // Validate the constant buffer
- if (@this->constantBufferSize > 0 &&
- @this->constantBuffer is null)
+ try
{
- return E.E_NOT_VALID_STATE;
- }
+ // Validate the constant buffer. We either must have a stateless shader, in which case
+ // the constant buffer might either be null or empty (both cases are allowed), or we
+ // must have a shader with some state and a constant buffer being set. In that case
+ // the code setting the constant buffer will have already validated its length.
+ if (@this->GetGlobals().ConstantBufferSize > 0 &&
+ @this->constantBuffer is null)
+ {
+ return E.E_NOT_VALID_STATE;
+ }
- // First, set the constant buffer, if available
- if (@this->constantBuffer is not null)
- {
- hresult = @this->d2D1DrawInfo->SetPixelShaderConstantBuffer(
- buffer: @this->constantBuffer,
- bufferCount: (uint)@this->constantBufferSize);
- }
+ // First, set the constant buffer, if available
+ if (@this->constantBuffer is not null)
+ {
+ @this->d2D1DrawInfo->SetPixelShaderConstantBuffer(
+ buffer: @this->constantBuffer,
+ bufferCount: (uint)@this->GetGlobals().ConstantBufferSize).Assert();
+ }
- if (Windows.SUCCEEDED(hresult))
- {
- for (int i = 0; i < @this->resourceTextureDescriptionCount; i++)
+ ReadOnlySpan resourceTextureDescriptions = @this->GetGlobals().ResourceTextureDescriptions.Span;
+
+ for (int i = 0; i < resourceTextureDescriptions.Length; i++)
{
using ComPtr resourceTextureManager = @this->resourceTextureManagerBuffer[i];
// If the current resource texture manager is not set, we cannot render, as there's an unbound resource texture
if (resourceTextureManager.Get() is null)
{
- hresult = E.E_NOT_VALID_STATE;
-
- break;
+ return E.E_NOT_VALID_STATE;
}
using ComPtr resourceTextureManagerInternal = default;
- // Get the ID2D1ResourceTextureManagerInternal object
- hresult = resourceTextureManager.CopyTo(resourceTextureManagerInternal.GetAddressOf());
-
- // This cast should always succeed, as when an input resource texture managers is set it's
- // also checked for ID2D1ResourceTextureManagerInternal, but still validate for good measure.
- if (!Windows.SUCCEEDED(hresult))
- {
- break;
- }
+ // Get the ID2D1ResourceTextureManagerInternal object. This cast should always succeed, as when
+ // an input resource texture managers is set it's also checked for ID2D1ResourceTextureManagerInternal,
+ // but still validate for good measure.
+ resourceTextureManager.CopyTo(resourceTextureManagerInternal.GetAddressOf()).Assert();
using ComPtr d2D1ResourceTexture = default;
// Try to get the ID2D1ResourceTexture from the manager
- hresult = resourceTextureManagerInternal.Get()->GetResourceTexture(d2D1ResourceTexture.GetAddressOf());
+ resourceTextureManagerInternal.Get()->GetResourceTexture(d2D1ResourceTexture.GetAddressOf()).Assert();
- if (!Windows.SUCCEEDED(hresult))
- {
- break;
- }
-
- ref readonly D2D1ResourceTextureDescription resourceTextureDescription = ref @this->resourceTextureDescriptions[i];
+ ref readonly D2D1ResourceTextureDescription resourceTextureDescription = ref resourceTextureDescriptions[i];
// Set the ID2D1ResourceTexture object to the current index in the ID2D1DrawInfo object in use
- hresult = @this->d2D1DrawInfo->SetResourceTexture(
+ @this->d2D1DrawInfo->SetResourceTexture(
textureIndex: (uint)resourceTextureDescription.Index,
- resourceTexture: d2D1ResourceTexture.Get());
-
- if (!Windows.SUCCEEDED(hresult))
- {
- break;
- }
+ resourceTexture: d2D1ResourceTexture.Get()).Assert();
}
- }
- return hresult;
+ return S.S_OK;
+ }
+ catch (Exception e)
+ {
+ return Marshal.GetHRForException(e);
+ }
}
///
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs
index 3eff1fa7..6e124bd3 100644
--- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs
@@ -1,6 +1,7 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
+using ComputeSharp.D2D1.Extensions;
using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers;
using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
using TerraFX.Interop.DirectX;
@@ -115,46 +116,51 @@ unsafe partial struct PixelShaderEffect
{
PixelShaderEffect* @this = (PixelShaderEffect*)effect;
- // This is a call likely from ID2D1Effect::GetValueSize, to query the property size
- if (data is null &&
- dataSize == 0 &&
- actualSize is not null)
+ try
{
- *actualSize = (uint)@this->constantBufferSize;
+ // This is a call likely from ID2D1Effect::GetValueSize, to query the property size.
+ // In that case we explicitly allow these inputs, and return the size of the buffer.
+ if (data is null &&
+ dataSize == 0 &&
+ actualSize is not null)
+ {
+ *actualSize = (uint)@this->GetGlobals().ConstantBufferSize;
- return S.S_FALSE;
+ return S.S_FALSE;
+ }
+
+ default(ArgumentNullException).ThrowIfNull(data);
+
+ if (dataSize < @this->GetGlobals().ConstantBufferSize)
+ {
+ return E.E_NOT_SUFFICIENT_BUFFER;
+ }
+
+ if (@this->constantBuffer is null)
+ {
+ return E.E_NOT_VALID_STATE;
+ }
+
+ uint writtenBytes = 0;
+
+ if (@this->GetGlobals().ConstantBufferSize > 0)
+ {
+ Buffer.MemoryCopy(@this->constantBuffer, data, dataSize, @this->GetGlobals().ConstantBufferSize);
+
+ writtenBytes = (uint)@this->GetGlobals().ConstantBufferSize;
+ }
+
+ if (actualSize is not null)
+ {
+ *actualSize = writtenBytes;
+ }
+
+ return S.S_OK;
}
-
- if (data is null)
+ catch (Exception e)
{
- return E.E_POINTER;
+ return Marshal.GetHRForException(e);
}
-
- if (dataSize < @this->constantBufferSize)
- {
- return E.E_NOT_SUFFICIENT_BUFFER;
- }
-
- if (@this->constantBuffer is null)
- {
- return E.E_NOT_VALID_STATE;
- }
-
- uint writtenBytes = 0;
-
- if (@this->constantBufferSize > 0)
- {
- Buffer.MemoryCopy(@this->constantBuffer, data, dataSize, @this->constantBufferSize);
-
- writtenBytes = (uint)@this->constantBufferSize;
- }
-
- if (actualSize is not null)
- {
- *actualSize = writtenBytes;
- }
-
- return S.S_OK;
}
///
@@ -163,31 +169,31 @@ unsafe partial struct PixelShaderEffect
{
PixelShaderEffect* @this = (PixelShaderEffect*)effect;
- if (data is null)
+ try
{
- return E.E_POINTER;
- }
+ default(ArgumentNullException).ThrowIfNull(data);
+ default(ArgumentOutOfRangeException).ThrowIfNotEqual((int)dataSize, @this->GetGlobals().ConstantBufferSize, nameof(dataSize));
- if (dataSize != (uint)@this->constantBufferSize)
+ // Reuse the existing buffer if there is one, otherwise allocate a new one
+ if (@this->constantBuffer is not null)
+ {
+ Buffer.MemoryCopy(data, @this->constantBuffer, dataSize, dataSize);
+ }
+ else
+ {
+ void* buffer = NativeMemory.Alloc(dataSize);
+
+ Buffer.MemoryCopy(data, buffer, dataSize, dataSize);
+
+ @this->constantBuffer = (byte*)buffer;
+ }
+
+ return S.S_OK;
+ }
+ catch (Exception e)
{
- return E.E_INVALIDARG;
+ return Marshal.GetHRForException(e);
}
-
- // Reuse the existing buffer if there is one, otherwise allocate a new one
- if (@this->constantBuffer is not null)
- {
- Buffer.MemoryCopy(data, @this->constantBuffer, dataSize, dataSize);
- }
- else
- {
- void* buffer = NativeMemory.Alloc(dataSize);
-
- Buffer.MemoryCopy(data, buffer, dataSize, dataSize);
-
- @this->constantBuffer = (byte*)buffer;
- }
-
- return S.S_OK;
}
///
@@ -196,36 +202,31 @@ unsafe partial struct PixelShaderEffect
{
PixelShaderEffect* @this = (PixelShaderEffect*)effect;
- if (data is null)
+ try
{
- return E.E_POINTER;
- }
+ default(ArgumentNullException).ThrowIfNull(data);
+ default(ArgumentOutOfRangeException).ThrowIfLessThan((int)dataSize, sizeof(void*), nameof(dataSize));
- if (dataSize < sizeof(void*))
- {
- return E.E_INVALIDARG;
- }
-
- if (@this->d2D1TransformMapper is null)
- {
- *(void**)data = null;
- }
- else
- {
- HRESULT hresult = ((IUnknown*)@this->d2D1TransformMapper)->QueryInterface(Windows.__uuidof(), (void**)data);
-
- if (!Windows.SUCCEEDED(hresult))
+ if (@this->d2D1TransformMapper is null)
{
- return hresult;
+ *(void**)data = null;
+ }
+ else
+ {
+ ((IUnknown*)@this->d2D1TransformMapper)->QueryInterface(Windows.__uuidof(), (void**)data).Assert();
}
- }
- if (actualSize is not null)
+ if (actualSize is not null)
+ {
+ *actualSize = (uint)sizeof(void*);
+ }
+
+ return S.S_OK;
+ }
+ catch (Exception e)
{
- *actualSize = (uint)sizeof(void*);
+ return Marshal.GetHRForException(e);
}
-
- return S.S_OK;
}
///
@@ -234,44 +235,33 @@ unsafe partial struct PixelShaderEffect
{
PixelShaderEffect* @this = (PixelShaderEffect*)effect;
- if (data is null)
+ try
{
- return E.E_POINTER;
+ default(ArgumentNullException).ThrowIfNull(data);
+ default(ArgumentOutOfRangeException).ThrowIfLessThan((int)dataSize, sizeof(void*), nameof(dataSize));
+
+ void* value = *(void**)data;
+
+ default(ArgumentNullException).ThrowIfNull(value);
+
+ using ComPtr unknown = (IUnknown*)value;
+ using ComPtr transformMapper = default;
+
+ // Check that the input object implements ID2D1TransformMapper
+ unknown.CopyTo(transformMapper.GetAddressOf()).Assert();
+
+ // If there's already an existing manager, release it
+ ComPtr.Release(@this->d2D1TransformMapper);
+
+ // Store the transform mapper manager into the effect
+ @this->d2D1TransformMapper = transformMapper.Detach();
+
+ return S.S_OK;
}
-
- void* value = *(void**)data;
-
- if (value is null)
+ catch (Exception e)
{
- return E.E_POINTER;
+ return Marshal.GetHRForException(e);
}
-
- if (dataSize != (uint)sizeof(void*))
- {
- return E.E_INVALIDARG;
- }
-
- using ComPtr unknown = (IUnknown*)value;
- using ComPtr transformMapper = default;
-
- // Check that the input object implements ID2D1TransformMapper
- int result = unknown.CopyTo(transformMapper.GetAddressOf());
-
- if (result != S.S_OK)
- {
- return result;
- }
-
- // If there's already an existing manager, release it
- if (@this->d2D1TransformMapper is not null)
- {
- _ = ((IUnknown*)@this->d2D1TransformMapper)->Release();
- }
-
- // Store the transform mapper manager into the effect
- @this->d2D1TransformMapper = transformMapper.Detach();
-
- return S.S_OK;
}
///
@@ -284,36 +274,27 @@ unsafe partial struct PixelShaderEffect
/// The for the operation.
private int GetResourceTextureManagerAtIndex(int index, byte* data, uint dataSize, uint* actualSize)
{
- if (index >= this.resourceTextureDescriptionCount)
+ try
{
- return E.E_INVALIDARG;
- }
+ default(ArgumentNullException).ThrowIfNull(data);
+ default(ArgumentOutOfRangeException).ThrowIfLessThan((int)dataSize, sizeof(void*), nameof(dataSize));
+ default(ArgumentOutOfRangeException).ThrowIfGreaterThanOrEqual(index, GetGlobals().ResourceTextureCount);
- if (data is null)
+ using ComPtr resourceTextureManager = this.resourceTextureManagerBuffer[index];
+
+ resourceTextureManager.CopyTo((ID2D1ResourceTextureManager**)data).Assert();
+
+ if (actualSize is not null)
+ {
+ *actualSize = (uint)sizeof(void*);
+ }
+
+ return S.S_OK;
+ }
+ catch (Exception e)
{
- return E.E_POINTER;
+ return Marshal.GetHRForException(e);
}
-
- if (dataSize < sizeof(void*))
- {
- return E.E_INVALIDARG;
- }
-
- using ComPtr resourceTextureManager = this.resourceTextureManagerBuffer[index];
-
- HRESULT hresult = resourceTextureManager.CopyTo((ID2D1ResourceTextureManager**)data);
-
- if (!Windows.SUCCEEDED(hresult))
- {
- return hresult;
- }
-
- if (actualSize is not null)
- {
- *actualSize = (uint)sizeof(void*);
- }
-
- return S.S_OK;
}
///
@@ -325,78 +306,53 @@ unsafe partial struct PixelShaderEffect
/// The for the operation.
private int SetResourceTextureManagerAtIndex(int index, byte* data, uint dataSize)
{
- if (index >= this.resourceTextureDescriptionCount)
+ try
{
- return E.E_INVALIDARG;
- }
+ default(ArgumentNullException).ThrowIfNull(data);
+ default(ArgumentOutOfRangeException).ThrowIfLessThan((int)dataSize, sizeof(void*), nameof(dataSize));
+ default(ArgumentOutOfRangeException).ThrowIfGreaterThanOrEqual(index, GetGlobals().ResourceTextureCount);
- if (data is null)
- {
- return E.E_POINTER;
- }
+ void* value = *(void**)data;
- void* value = *(void**)data;
+ default(ArgumentNullException).ThrowIfNull(value);
- if (value is null)
- {
- return E.E_POINTER;
- }
+ using ComPtr unknown = (IUnknown*)value;
+ using ComPtr resourceTextureManager = default;
- if (dataSize != (uint)sizeof(void*))
- {
- return E.E_INVALIDARG;
- }
+ // Check that the input object implements ID2D1ResourceTextureManager
+ unknown.CopyTo(resourceTextureManager.GetAddressOf()).Assert();
- using ComPtr unknown = (IUnknown*)value;
- using ComPtr resourceTextureManager = default;
+ using ComPtr resourceTextureManagerInternal = default;
- // Check that the input object implements ID2D1ResourceTextureManager
- int result = unknown.CopyTo(resourceTextureManager.GetAddressOf());
+ // Then, also check that it implements ID2D1ResourceTextureManagerInternal
+ unknown.CopyTo(resourceTextureManagerInternal.GetAddressOf()).Assert();
- if (result != S.S_OK)
- {
- return result;
- }
-
- using ComPtr resourceTextureManagerInternal = default;
-
- // Then, also check that it implements ID2D1ResourceTextureManagerInternal
- result = unknown.CopyTo(resourceTextureManagerInternal.GetAddressOf());
-
- if (result != S.S_OK)
- {
- return result;
- }
-
- // Initialize the resource texture manager, if an effect context is available
- if (this.d2D1EffectContext is not null)
- {
- uint dimensions = (uint)this.resourceTextureDescriptions[index].Dimensions;
-
- result = resourceTextureManagerInternal.Get()->Initialize(this.d2D1EffectContext, &dimensions);
-
- // ID2D1ResourceTextureManager::Initialize should generally return either S_OK for first
- // initialization, S_FALSE if an ID2D1EffectContext is already present (which is allowed, to
- // enable sharing resource texture managers across different source textures and effects), or
- // E_INVALIDARG if the manager has already been initialized through the public interface,
- // and the stored dimensions for that don't match the ones for this resource texture index.
- if (!Windows.SUCCEEDED(result))
+ // Initialize the resource texture manager, if an effect context is available
+ if (this.d2D1EffectContext is not null)
{
- return result;
+ uint dimensions = (uint)GetGlobals().ResourceTextureDescriptions.Span[index].Dimensions;
+
+ // ID2D1ResourceTextureManager::Initialize should generally return either S_OK for first
+ // initialization, S_FALSE if an ID2D1EffectContext is already present (which is allowed, to
+ // enable sharing resource texture managers across different source textures and effects), or
+ // E_INVALIDARG if the manager has already been initialized through the public interface,
+ // and the stored dimensions for that don't match the ones for this resource texture index.
+ resourceTextureManagerInternal.Get()->Initialize(this.d2D1EffectContext, &dimensions).Assert();
}
+
+ ref ID2D1ResourceTextureManager* currentResourceTextureManager = ref this.resourceTextureManagerBuffer[index];
+
+ // If there's already an existing manager at this index, release it
+ ComPtr.Release(currentResourceTextureManager);
+
+ // Store the resource texture manager into the buffer
+ currentResourceTextureManager = resourceTextureManager.Detach();
+
+ return S.S_OK;
}
-
- ref ID2D1ResourceTextureManager* currentResourceTextureManager = ref this.resourceTextureManagerBuffer[index];
-
- // If there's already an existing manager at this index, release it
- if (currentResourceTextureManager is not null)
+ catch (Exception e)
{
- _ = ((IUnknown*)currentResourceTextureManager)->Release();
+ return Marshal.GetHRForException(e);
}
-
- // Store the resource texture manager into the buffer
- currentResourceTextureManager = resourceTextureManager.Detach();
-
- return S.S_OK;
}
}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs
index 3106e5df..38e87929 100644
--- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs
@@ -106,86 +106,15 @@ internal unsafe partial struct PixelShaderEffect
private volatile int referenceCount;
///
- /// The for the shader.
+ /// The for the instance in use.
///
- private Guid shaderId;
+ private GCHandle globalsHandle;
///
/// The constant buffer data, if set.
///
private byte* constantBuffer;
- ///
- /// The size of .
- ///
- private int constantBufferSize;
-
- ///
- /// The number of inputs for the shader.
- ///
- private int inputCount;
-
- ///
- /// The buffer with the types of inputs for the shader.
- ///
- ///
- /// This buffer is shared among effect instances, so it should not be released. It is
- /// owned by , which will release it when the target type is unloaded.
- ///
- private D2D1PixelShaderInputType* inputTypes;
-
- ///
- /// The number of available input descriptions.
- ///
- private int inputDescriptionCount;
-
- ///
- /// The buffer with the available input descriptions for the shader.
- ///
- ///
- /// This buffer is also shared among effect instances, so it should not be released. It is
- /// owned by , which will release it when the target type is unloaded.
- ///
- private D2D1InputDescription* inputDescriptions;
-
- ///
- /// The pixel options for the shader.
- ///
- private D2D1PixelOptions pixelOptions;
-
- ///
- /// The shader bytecode.
- ///
- private byte* bytecode;
-
- ///
- /// The size of .
- ///
- private int bytecodeSize;
-
- ///
- /// The buffer precision for the resulting output buffer.
- ///
- private D2D1BufferPrecision bufferPrecision;
-
- ///
- /// The channel depth for the resulting output buffer.
- ///
- private D2D1ChannelDepth channelDepth;
-
- ///
- /// The number of available resource texture descriptions.
- ///
- private int resourceTextureDescriptionCount;
-
- ///
- /// The buffer with the available resource texture descriptions for the shader.
- ///
- ///
- /// This buffer is also shared among effect instances, like .
- ///
- private D2D1ResourceTextureDescription* resourceTextureDescriptions;
-
///
/// The instance to use, if any.
///
@@ -209,77 +138,48 @@ internal unsafe partial struct PixelShaderEffect
///
/// The factory method for .
///
- /// The for the shader.
- /// The size of the constant buffer for the shader.
- /// The number of inputs for the shader.
- /// The buffer with the types of inputs for the shader.
- /// The number of available input descriptions.
- /// The buffer with the available input descriptions for the shader.
- /// The pixel options for the shader.
- /// The shader bytecode.
- /// The size of .
- /// The buffer precision for the resulting output buffer.
- /// The channel depth for the resulting output buffer.
- /// The number of available resource texture descriptions.
- /// The buffer with the available resource texture descriptions for the shader.
+ /// The instance to use.
/// The resulting effect instance.
- /// This always returns 0.
- private static int Factory(
- Guid shaderId,
- int constantBufferSize,
- int inputCount,
- D2D1PixelShaderInputType* inputTypes,
- int inputDescriptionCount,
- D2D1InputDescription* inputDescriptions,
- D2D1PixelOptions pixelOptions,
- byte* bytecode,
- int bytecodeSize,
- D2D1BufferPrecision bufferPrecision,
- D2D1ChannelDepth channelDepth,
- int resourceTextureDescriptionCount,
- D2D1ResourceTextureDescription* resourceTextureDescriptions,
- IUnknown** effectImpl)
+ /// The for the operation.
+ private static int Factory(Globals globals, IUnknown** effectImpl)
{
- PixelShaderEffect* @this;
+ PixelShaderEffect* @this = null;
+ GCHandle globalsHandle = default;
try
{
@this = (PixelShaderEffect*)NativeMemory.Alloc((nuint)sizeof(PixelShaderEffect));
+ globalsHandle = GCHandle.Alloc(globals);
+
+ @this->lpVtblForID2D1EffectImpl = VtblForID2D1EffectImpl;
+ @this->lpVtblForID2D1DrawTransform = VtblForID2D1DrawTransform;
+ @this->referenceCount = 1;
+ @this->globalsHandle = globalsHandle;
+ @this->constantBuffer = null;
+ @this->d2D1TransformMapper = null;
+ @this->d2D1DrawInfo = null;
+ @this->d2D1EffectContext = null;
+ @this->resourceTextureManagerBuffer = default;
+
+ *effectImpl = (IUnknown*)@this;
+
+ return S.S_OK;
}
- catch (OutOfMemoryException)
+ catch (Exception e)
{
+ // Free the effect, if we have one
+ NativeMemory.Free(@this);
+
+ // Free the handle, if we have one
+ if (globalsHandle.IsAllocated)
+ {
+ globalsHandle.Free();
+ }
+
*effectImpl = null;
- return E.E_OUTOFMEMORY;
+ return Marshal.GetHRForException(e);
}
-
- *@this = default;
-
- @this->lpVtblForID2D1EffectImpl = VtblForID2D1EffectImpl;
- @this->lpVtblForID2D1DrawTransform = VtblForID2D1DrawTransform;
- @this->referenceCount = 1;
- @this->shaderId = shaderId;
- @this->constantBuffer = null;
- @this->constantBufferSize = constantBufferSize;
- @this->inputCount = inputCount;
- @this->inputTypes = inputTypes;
- @this->inputDescriptionCount = inputDescriptionCount;
- @this->inputDescriptions = inputDescriptions;
- @this->pixelOptions = pixelOptions;
- @this->bytecode = bytecode;
- @this->bytecodeSize = bytecodeSize;
- @this->bufferPrecision = bufferPrecision;
- @this->channelDepth = channelDepth;
- @this->resourceTextureDescriptionCount = resourceTextureDescriptionCount;
- @this->resourceTextureDescriptions = resourceTextureDescriptions;
- @this->d2D1TransformMapper = null;
- @this->d2D1DrawInfo = null;
- @this->d2D1EffectContext = null;
- @this->resourceTextureManagerBuffer = default;
-
- *effectImpl = (IUnknown*)@this;
-
- return S.S_OK;
}
///
@@ -331,35 +231,20 @@ internal unsafe partial struct PixelShaderEffect
if (referenceCount == 0)
{
- if (this.constantBuffer is not null)
- {
- NativeMemory.Free(this.constantBuffer);
- }
+ this.globalsHandle.Free();
- if (this.d2D1TransformMapper is not null)
- {
- _ = ((IUnknown*)this.d2D1TransformMapper)->Release();
- }
+ NativeMemory.Free(this.constantBuffer);
- if (this.d2D1DrawInfo is not null)
- {
- _ = this.d2D1DrawInfo->Release();
- }
+ ComPtr.Release(this.d2D1TransformMapper);
+ ComPtr.Release(this.d2D1DrawInfo);
+ ComPtr.Release(this.d2D1EffectContext);
- if (this.d2D1EffectContext is not null)
+ // Retrieve all possible resource texture managers in use and release the ones that had been
+ // assigned (from one of the property bindings). We just hardcode 16 here and dont access
+ // the globals, as technically invoking APIs on it might throw an exception.
+ for (int i = 0; i < 16; i++)
{
- _ = this.d2D1EffectContext->Release();
- }
-
- // Retrieve all possible resource texture managers in use and release the ones that had been assigned (from one of the property bindings)
- for (int i = 0; i < this.resourceTextureDescriptionCount; i++)
- {
- ID2D1ResourceTextureManager* resourceTextureManager = this.resourceTextureManagerBuffer[i];
-
- if (resourceTextureManager is not null)
- {
- _ = ((IUnknown*)resourceTextureManager)->Release();
- }
+ ComPtr.Release(this.resourceTextureManagerBuffer[i]);
}
NativeMemory.Free(Unsafe.AsPointer(ref this));
@@ -367,4 +252,14 @@ internal unsafe partial struct PixelShaderEffect
return referenceCount;
}
+
+ ///
+ /// Gets the instance for the current effect.
+ ///
+ /// The instance for the current effect.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private Globals GetGlobals()
+ {
+ return Unsafe.As(this.globalsHandle.Target!);
+ }
}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManagerInternal.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManagerInternal.cs
index 1b8a84ed..99aa3985 100644
--- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManagerInternal.cs
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManagerInternal.cs
@@ -124,9 +124,8 @@ partial struct D2D1ResourceTextureManagerImpl
// Now, the effect context can actually be stored safely while holding the lock.
// This is guaranteed to be the case here, as this method is only called (as per
// contact of the COM interface) from ID2D1EffectImpl, which holds the D2D lock.
- _ = effectContext->AddRef();
+ ComPtr.WriteTo(effectContext, out @this->d2D1EffectContext);
- @this->d2D1EffectContext = effectContext;
@this->d2D1Multithread = d2D1Multithread.Detach();
}
@@ -162,9 +161,7 @@ partial struct D2D1ResourceTextureManagerImpl
// If the texture has already been created, just return it
if (@this->d2D1ResourceTexture is not null)
{
- _ = @this->d2D1ResourceTexture->AddRef();
-
- *resourceTexture = @this->d2D1ResourceTexture;
+ ComPtr.WriteTo(@this->d2D1ResourceTexture, out *resourceTexture);
return S.S_OK;
}
diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs
index 575fdcc6..a5fe07c4 100644
--- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs
@@ -247,10 +247,7 @@ internal unsafe partial struct D2D1ResourceTextureManagerImpl
this.d2D1Multithread->Enter();
// Release the resource too if it has been created
- if (this.d2D1ResourceTexture is not null)
- {
- _ = this.d2D1ResourceTexture->Release();
- }
+ ComPtr.Release(this.d2D1ResourceTexture);
// Now that the resource, if any, has been released, the effect context can also
// be released. This must be done only after any associated resource textures have
@@ -263,30 +260,11 @@ internal unsafe partial struct D2D1ResourceTextureManagerImpl
_ = this.d2D1Multithread->Release();
}
- if (this.resourceId is not null)
- {
- NativeMemory.Free(this.resourceId);
- }
-
- if (this.resourceTextureProperties.extents is not null)
- {
- NativeMemory.Free(this.resourceTextureProperties.extents);
- }
-
- if (this.resourceTextureProperties.extendModes is not null)
- {
- NativeMemory.Free(this.resourceTextureProperties.extendModes);
- }
-
- if (this.data is not null)
- {
- NativeMemory.Free(this.data);
- }
-
- if (this.strides is not null)
- {
- NativeMemory.Free(this.strides);
- }
+ NativeMemory.Free(this.resourceId);
+ NativeMemory.Free(this.resourceTextureProperties.extents);
+ NativeMemory.Free(this.resourceTextureProperties.extendModes);
+ NativeMemory.Free(this.data);
+ NativeMemory.Free(this.strides);
}
this.lockHandle.Free();
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 6d302318..e3e616b8 100644
--- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.ID2D1TransformMapper.cs
+++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.ID2D1TransformMapper.cs
@@ -131,7 +131,7 @@ unsafe partial struct D2D1TransformMapperImpl
}
catch (Exception e)
{
- return e.HResult;
+ return Marshal.GetHRForException(e);
}
*outputRect = output.ToRECT();
@@ -163,7 +163,7 @@ unsafe partial struct D2D1TransformMapperImpl
}
catch (Exception e)
{
- return e.HResult;
+ return Marshal.GetHRForException(e);
}
for (int i = 0; i < (int)inputRectsCount; i++)
@@ -192,7 +192,7 @@ unsafe partial struct D2D1TransformMapperImpl
}
catch (Exception e)
{
- return e.HResult;
+ return Marshal.GetHRForException(e);
}
*invalidOutputRect = invalidOutput.ToRECT();
diff --git a/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorFactoryImpl.cs b/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorFactoryImpl.cs
index 2795efa4..35aa47dc 100644
--- a/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorFactoryImpl.cs
+++ b/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorFactoryImpl.cs
@@ -165,7 +165,7 @@ internal unsafe struct ID3D12MemoryAllocatorFactoryImpl
}
catch (Exception e)
{
- return e.HResult;
+ return Marshal.GetHRForException(e);
}
}
}
\ No newline at end of file
diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/ComPtrExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/ComPtrExtensions.cs
index 0b14b7fe..7909fd04 100644
--- a/src/ComputeSharp/Graphics/Extensions/Interop/ComPtrExtensions.cs
+++ b/src/ComputeSharp/Graphics/Extensions/Interop/ComPtrExtensions.cs
@@ -8,52 +8,6 @@ namespace ComputeSharp.Core.Extensions;
///
internal static class ComPtrExtensions
{
-#if NET6_0_OR_GREATER
- ///
- /// Invokes on the wrapped object for an input value.
- ///
- /// The type of the current instance.
- /// The input instance to increment the reference count for.
- /// A instance of type .
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static unsafe uint AddRef(this ComPtr ptr)
- where T : unmanaged, IUnknown.Interface
- {
- if (ptr.Get() is not null)
- {
- return ptr.Get()->AddRef();
- }
-
- return 0;
- }
-
- ///
- /// Invokes on the wrapped object for an input value.
- /// If the object has been deleted, it also resets .
- ///
- /// The type of the current instance.
- /// The input instance to release.
- /// A instance of type .
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static unsafe uint Release(this ref ComPtr ptr)
- where T : unmanaged, IUnknown.Interface
- {
- if (ptr.Get() is not null)
- {
- uint count = ptr.Get()->Release();
-
- if (count == 0)
- {
- ptr = default;
- }
-
- return count;
- }
-
- return 0;
- }
-#endif
-
///
/// Reinterprets the current instance as one of type .
///
diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.IBufferWriter.cs b/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.IBufferWriter.cs
index 54c34722..2f4de787 100644
--- a/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.IBufferWriter.cs
+++ b/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.IBufferWriter.cs
@@ -373,7 +373,7 @@ unsafe partial class IWICStreamExtensions
}
catch (Exception ex)
{
- return ex.HResult;
+ return Marshal.GetHRForException(ex);
}
}
@@ -454,7 +454,7 @@ unsafe partial class IWICStreamExtensions
}
catch (Exception ex)
{
- return ex.HResult;
+ return Marshal.GetHRForException(ex);
}
}
diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.Stream.cs b/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.Stream.cs
index c471afd5..9481099b 100644
--- a/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.Stream.cs
+++ b/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.Stream.cs
@@ -380,7 +380,7 @@ internal static unsafe partial class IWICStreamExtensions
}
catch (Exception ex)
{
- return ex.HResult;
+ return Marshal.GetHRForException(ex);
}
}
@@ -416,7 +416,7 @@ internal static unsafe partial class IWICStreamExtensions
}
catch (Exception ex)
{
- return ex.HResult;
+ return Marshal.GetHRForException(ex);
}
}
@@ -454,7 +454,7 @@ internal static unsafe partial class IWICStreamExtensions
}
catch (Exception ex)
{
- return ex.HResult;
+ return Marshal.GetHRForException(ex);
}
}
@@ -475,7 +475,7 @@ internal static unsafe partial class IWICStreamExtensions
}
catch (Exception ex)
{
- return ex.HResult;
+ return Marshal.GetHRForException(ex);
}
}
@@ -498,7 +498,7 @@ internal static unsafe partial class IWICStreamExtensions
}
catch (Exception ex)
{
- return ex.HResult;
+ return Marshal.GetHRForException(ex);
}
}
@@ -587,7 +587,7 @@ internal static unsafe partial class IWICStreamExtensions
pstatstg->pwcsName = null;
}
- return ex.HResult;
+ return Marshal.GetHRForException(ex);
}
}
diff --git a/src/TerraFX.Interop.Windows/ComPtr`1.cs b/src/TerraFX.Interop.Windows/ComPtr`1.cs
index dcfa9e1f..4f1a3273 100644
--- a/src/TerraFX.Interop.Windows/ComPtr`1.cs
+++ b/src/TerraFX.Interop.Windows/ComPtr`1.cs
@@ -38,6 +38,62 @@ internal unsafe struct ComPtr : IDisposable
InternalAddRef();
}
+ ///
+ /// Releases a target COM object, if it's not .
+ ///
+ /// The COM object to potentially release.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void Release(T* other)
+ {
+ if (other is not null)
+ {
+ _ = ((IUnknown*)other)->Release();
+ }
+ }
+
+ ///
+ /// Copies a given COM object into a target destination, incrementing reference counts where needed.
+ ///
+ /// The input COM object to copy.
+ /// The target destination for the COM object.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void CopyTo(T* obj, ref T* other)
+ {
+ // We specifically need to increment the reference count on the source object before releasing the
+ // target object, 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.
+ if (obj is not null)
+ {
+ _ = ((IUnknown*)obj)->AddRef();
+ }
+
+ T* pointer = other;
+
+ if (pointer is not null)
+ {
+ _ = ((IUnknown*)pointer)->Release();
+ }
+
+ other = obj;
+ }
+
+ ///
+ /// Writes a given COM object into a target (assumed uninitialized) destination, incrementing reference counts where needed.
+ ///
+ /// The input COM object to copy.
+ /// The target destination for the COM object.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void WriteTo(T* obj, out T* other)
+ {
+ _ = ((IUnknown*)obj)->AddRef();
+
+ other = obj;
+ }
+
/// Converts a raw pointer to a new instance and increments the ref count.
/// The raw pointer to wrap.
[MethodImpl(MethodImplOptions.AggressiveInlining)]