using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ComputeSharp.D2D1.Helpers; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; #if NET6_0_OR_GREATER using RuntimeHelpers = System.Runtime.CompilerServices.RuntimeHelpers; #else using RuntimeHelpers = ComputeSharp.D2D1.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; #endif namespace ComputeSharp.D2D1.Interop.Effects; /// /// A simple and implementation for a given pixel shader. /// internal unsafe partial struct PixelShaderEffect { /// /// A generic pixel shader implementation. /// /// The type of shader. public static class For where T : unmanaged, ID2D1PixelShader { /// /// The wrapper for the shader factory. /// private static readonly FactoryDelegate EffectFactory = CreateEffect; /// /// Indicates whether or not initialization has completed. /// private static bool isInitialized; /// /// 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 static Guid shaderId; /// /// The number of inputs for the shader. /// private static int numberOfInputs; /// /// The shader bytecode. /// private static byte* bytecode; /// /// The size of . /// private static int bytecodeSize; /// /// The factory of instances to use for each created effect. /// private static Func>? d2D1DrawTransformMapperFactory; /// /// Initializes the shared state. /// /// The factory of instances to use for each created effect. /// Thrown if initialization is attempted with a mismatched transform factory. public static void Initialize(Func>? factory) { // This conceptually acts as a static constructor, and this type is // internal, so in this very specific case locking on the type is fine. lock (typeof(For)) { if (isInitialized) { // If the factory is already initialized, ensure the draw transform mapper is the same if (d2D1DrawTransformMapperFactory != factory) { ThrowHelper.ThrowInvalidOperationException( "Cannot initialize an ID2D1Effect factory for the same shader type with two different transform mappings. " + "Make sure to only ever register a pixel shader effect with either no transform, or the same transform type."); } } else { // Load all shader properties Guid guid = typeof(T).GUID; int inputCount = (int)D2D1InteropServices.GetPixelShaderInputCount(); ReadOnlyMemory buffer = D2D1InteropServices.LoadPixelShaderBytecode(); byte* typeAssociatedMemory = (byte*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), buffer.Length); // Copy the bytecode to the target buffer buffer.Span.CopyTo(new Span(typeAssociatedMemory, buffer.Length)); // Set the shared state and mark the type as initialized shaderId = guid; numberOfInputs = inputCount; bytecode = typeAssociatedMemory; bytecodeSize = buffer.Length; d2D1DrawTransformMapperFactory = factory; isInitialized = true; } } } /// /// Gets a reference to the id of the effect. /// public static ref Guid Id { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => ref shaderId; } /// /// Gets the factory for the current effect. /// public static delegate* unmanaged[Stdcall] Factory { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => (delegate* unmanaged[Stdcall])Marshal.GetFunctionPointerForDelegate(EffectFactory); } /// /// Gets the number of inputs for the effect. /// public static int NumberOfInputs => numberOfInputs; /// /// Tries to get the effect id, if it has been initialized. /// /// The resulting effect id. /// Whether or not the effect had been initialized. public static bool TryGetId(out Guid id) { lock (typeof(For)) { if (isInitialized) { id = Id; return true; } } id = default; return false; } /// private static int CreateEffect(IUnknown** effectImpl) { D2D1TransformMapper? d2D1TransformMapper; // If there is a custom draw transform factory, run it in a try block and handle exceptions. This // is needed because the factory will be running user code from a method that's invoked by COM, // and managed exceptions should never cross the ABI boundary. If it throws, just return the HRESULT. try { ID2D1TransformMapper? d2D1DrawTransformMapper = d2D1DrawTransformMapperFactory?.Invoke(); d2D1TransformMapper = D2D1TransformMapper.For.Get(d2D1DrawTransformMapper); } catch (Exception e) { *effectImpl = null; return e.HResult; } return PixelShaderEffect.Factory( shaderId, numberOfInputs, bytecode, bytecodeSize, d2D1TransformMapper, effectImpl); } } }