From f6282f53ffbd10c4b713b02e7c5fa9d2a9b4d63d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 18 Apr 2022 00:34:59 +0200 Subject: [PATCH] Add GetPixelShaderEffectRegistrationBlob APIs --- .../ComputeSharp.D2D1.NetStandard.projitems | 1 + .../System/Buffers/BitOperations.cs | 32 +++ .../Interop/Buffers/ArrayPoolBinaryWriter.cs | 235 ++++++++++++++++++ .../Interop/D2D1InteropServices.Effects.cs | 125 +++++++++- 4 files changed, 390 insertions(+), 3 deletions(-) create mode 100644 src/ComputeSharp.D2D1.NetStandard/System/Buffers/BitOperations.cs create mode 100644 src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs diff --git a/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems b/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems index 501f2db0..5e0080d3 100644 --- a/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems +++ b/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems @@ -9,6 +9,7 @@ ComputeSharp.D2D1.NetStandard + diff --git a/src/ComputeSharp.D2D1.NetStandard/System/Buffers/BitOperations.cs b/src/ComputeSharp.D2D1.NetStandard/System/Buffers/BitOperations.cs new file mode 100644 index 00000000..a8f36d90 --- /dev/null +++ b/src/ComputeSharp.D2D1.NetStandard/System/Buffers/BitOperations.cs @@ -0,0 +1,32 @@ +using System.Runtime.CompilerServices; + +namespace ComputeSharp.D2D1.NetStandard.System.Buffers; + +/// +/// A polyfill type that mirrors some methods from on .NET 6. +/// +internal static class BitOperations +{ + /// + /// Rounds the given integral value up to a power of 2. + /// + /// The value. + /// + /// The smallest power of 2 which is greater than or equal to . + /// If is 0 or the result overflows, returns 0. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint RoundUpToPowerOf2(uint value) + { + // Based on https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 + --value; + + value |= value >> 1; + value |= value >> 2; + value |= value >> 4; + value |= value >> 8; + value |= value >> 16; + + return value + 1; + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs new file mode 100644 index 00000000..ebef74a0 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs @@ -0,0 +1,235 @@ +using System; +using System.Buffers; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +#if !NET6_0_OR_GREATER +using ComputeSharp.D2D1.NetStandard.System.Text; +using BitOperations = ComputeSharp.D2D1.NetStandard.System.Buffers.BitOperations; +#endif + +namespace ComputeSharp.D2D1.Shaders.Interop.Buffers; + +/// +/// Represents a heap-based, array-backed output sink into which binary data can be written. +/// +internal ref struct ArrayPoolBinaryWriter +{ + /// + /// The default buffer size to use to expand empty arrays. + /// + public const int DefaultInitialBufferSize = 256; + + /// + /// The underlying array. + /// + private byte[]? array; + + /// + /// The starting offset within . + /// + private int index; + + /// + /// Initializes a new instance of the class. + /// + public ArrayPoolBinaryWriter(int capacity) + { + this.array = ArrayPool.Shared.Rent(capacity); + this.index = 0; + } + + /// + /// Gets the data written to the underlying buffer so far, as a . + /// + public ReadOnlySpan WrittenSpan + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + byte[]? array = this.array; + + if (array is null) + { + ThrowObjectDisposedException(); + } + + return array!.AsSpan(0, this.index); + } + } + + /// + /// Writes a value of type into the buffer. + /// + /// The type of value to write. + /// The value to write. + public unsafe void Write(in T value) + where T : unmanaged + { + Span span = GetSpan(sizeof(T)); + + MemoryMarshal.Write(span, ref Unsafe.AsRef(in value)); + + Advance(sizeof(T)); + } + + /// + /// Writes text as UTF8 bytes into the buffer. + /// + /// The text to write. + public unsafe void WriteAsUtf8(string text) + { + int maximumByteSize = Encoding.UTF8.GetMaxByteCount(text.Length); + + Span span = GetSpan(maximumByteSize); + + int writtenBytes = Encoding.UTF8.GetBytes(text.AsSpan(), span); + + Advance(writtenBytes); + } + + /// + /// Advances the current writer. + /// + /// The amount to advance. + /// Must be called after . + private void Advance(int count) + { + byte[]? array = this.array; + + if (array is null) + { + ThrowObjectDisposedException(); + } + + if (count < 0) + { + ThrowArgumentOutOfRangeExceptionForNegativeCount(); + } + + if (this.index > array!.Length - count) + { + ThrowArgumentExceptionForAdvancedTooFar(); + } + + this.index += count; + } + + /// + /// Gets a to write data to, with an optional minimum capacity. + /// + /// The capacity to request. + /// A to write data to. + private Span GetSpan(int sizeHint = 0) + { + CheckBufferAndEnsureCapacity(sizeHint); + + return this.array.AsSpan(this.index); + } + + /// + /// Ensures that has enough free space to contain a given number of new items. + /// + /// The minimum number of items to ensure space for in . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void CheckBufferAndEnsureCapacity(int sizeHint) + { + byte[]? array = this.array; + + if (array is null) + { + ThrowObjectDisposedException(); + } + + if (sizeHint < 0) + { + ThrowArgumentOutOfRangeExceptionForNegativeSizeHint(); + } + + if (sizeHint == 0) + { + sizeHint = 1; + } + + if (sizeHint > array!.Length - this.index) + { + ResizeBuffer(sizeHint); + } + } + + /// + /// Resizes to ensure it can fit the specified number of new items. + /// + /// The minimum number of items to ensure space for in . + [MethodImpl(MethodImplOptions.NoInlining)] + private void ResizeBuffer(int sizeHint) + { + uint minimumSize = (uint)this.index + (uint)sizeHint; + + // The ArrayPool class has a maximum threshold of 1024 * 1024 for the maximum length of + // pooled arrays, and once this is exceeded it will just allocate a new array every time + // of exactly the requested size. In that case, we manually round up the requested size to + // the nearest power of two, to ensure that repeated consecutive writes when the array in + // use is bigger than that threshold don't end up causing a resize every single time. + if (minimumSize > 1024 * 1024) + { + minimumSize = BitOperations.RoundUpToPowerOf2(minimumSize); + } + + byte[] newArray = ArrayPool.Shared.Rent((int)minimumSize); + + Buffer.BlockCopy(this.array!, 0, newArray, 0, this.index); + + ArrayPool.Shared.Return(this.array!); + + this.array = newArray; + } + + /// + public void Dispose() + { + byte[]? array = this.array; + + if (array is null) + { + return; + } + + this.array = null; + + ArrayPool.Shared.Return(array); + } + + /// + /// Throws an when the requested count is negative. + /// + private static void ThrowArgumentOutOfRangeExceptionForNegativeCount() + { + throw new ArgumentOutOfRangeException("count", "The count can't be a negative value."); + } + + /// + /// Throws an when the size hint is negative. + /// + private static void ThrowArgumentOutOfRangeExceptionForNegativeSizeHint() + { + throw new ArgumentOutOfRangeException("sizeHint", "The size hint can't be a negative value."); + } + + /// + /// Throws an when the requested count is negative. + /// + private static void ThrowArgumentExceptionForAdvancedTooFar() + { + throw new ArgumentException("The buffer writer has advanced too far."); + } + + /// + /// Throws an when is . + /// + private static void ThrowObjectDisposedException() + { + throw new ObjectDisposedException("The current buffer has already been disposed."); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.Effects.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.Effects.cs index e7daf335..f7242758 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.Effects.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1InteropServices.Effects.cs @@ -7,6 +7,7 @@ using System.Text; using ComputeSharp.D2D1.Extensions; using ComputeSharp.D2D1.Interop.Effects; using ComputeSharp.D2D1.Shaders.Dispatching; +using ComputeSharp.D2D1.Shaders.Interop.Buffers; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -65,15 +66,14 @@ unsafe partial class D2D1InteropServices for (int i = 0; i < PixelShaderEffect.For.NumberOfInputs; i++) { - effectInputsBuilder.Append($""); + effectInputsBuilder.Append("'/>"); } // Prepare the XML with a variable number of inputs string xml = @$" - @@ -121,6 +121,125 @@ unsafe partial class D2D1InteropServices } } + /// + /// Gets a binary blob containing serialized information that can be used to register an effect, by using ID2D1Factory1::RegisterEffectFromString. + /// + /// The type of D2D1 pixel shader to register. + /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. + /// For more info and for details on the binary format, see . + public static unsafe ReadOnlyMemory GetPixelShaderEffectRegistrationBlob(out Guid effectId) + where T : unmanaged, ID2D1PixelShader + { + return GetPixelShaderEffectRegistrationBlob(null, out effectId); + } + + /// + /// Gets a binary blob containing serialized information that can be used to register an effect, by using ID2D1Factory1::RegisterEffectFromString. + /// + /// The type of D2D1 pixel shader to register. + /// The type of implementation to register. + /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. + /// For more info and for details on the binary format, see . + public static unsafe ReadOnlyMemory GetPixelShaderEffectRegistrationBlob(out Guid effectId) + where T : unmanaged, ID2D1PixelShader + where TMapper : class, ID2D1TransformMapper, new() + { + return GetPixelShaderEffectRegistrationBlob(static () => new TMapper(), out effectId); + } + + /// + /// Gets a binary blob containing serialized information that can be used to register an effect, by using ID2D1Factory1::RegisterEffectFromString. + /// + /// The type of D2D1 pixel shader to get the registration blob for. + /// An optional factory of instances to use for the transform. + /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. + /// + /// + /// The binary blob contains information with the following format: + /// + /// The effect id (a ). + /// The number of inputs for the effect (an ). + /// The effect XML description (as null-terminated UTF8 text). + /// The number of property bindings (an ). + /// The property name (as null-terminated UTF8 text). + /// The property getter (a ). + /// The property setter (a ). + /// The effect factory (a ). + /// + /// The property name, getter and setter are grouped together after the number of bindings. + /// + /// + /// For more info, see . + /// + /// + public static unsafe ReadOnlyMemory GetPixelShaderEffectRegistrationBlob(Func>? mapperFactory, out Guid effectId) + where T : unmanaged, ID2D1PixelShader + { + effectId = default; + + PixelShaderEffect.For.Initialize(mapperFactory); + + using ArrayPoolBinaryWriter writer = new(ArrayPoolBinaryWriter.DefaultInitialBufferSize); + + // Effect id and number of inputs + writer.Write(*PixelShaderEffect.For.Id); + writer.Write(PixelShaderEffect.For.NumberOfInputs); + + // Build the XML text + writer.WriteAsUtf8(@" + + + + + + + "); + + // Add the input nodes + for (int i = 0; i < PixelShaderEffect.For.NumberOfInputs; i++) + { + writer.WriteAsUtf8(""); + } + + // Write the last part of the XML (including the buffer property) + writer.WriteAsUtf8(@" + + + + +"); + + // Null terminator for the text + writer.Write((byte)'\0'); + + // Property accessors +#if NET6_0_OR_GREATER + nint getBufferPointer = (nint)(delegate* unmanaged)&PixelShaderEffect.GetConstantBuffer; + nint setBufferPointer = (nint)(delegate* unmanaged)&PixelShaderEffect.SetConstantBuffer; +#else + nint getBufferPointer = Marshal.GetFunctionPointerForDelegate(PixelShaderEffect.GetConstantBufferWrapper); + nint setBufferPointer = Marshal.GetFunctionPointerForDelegate(PixelShaderEffect.SetConstantBufferWrapper); +#endif + + // Bindings + writer.Write(1); + writer.WriteAsUtf8("Buffer"); + writer.Write((byte)'\0'); + writer.Write(getBufferPointer); + writer.Write(setBufferPointer); + + // Effect factory + writer.Write((nint)PixelShaderEffect.For.Factory); + + effectId = *PixelShaderEffect.For.Id; + + return writer.WrittenSpan.ToArray(); + } + /// /// Creates an effect wrapping an input D2D1 pixel shader, by calling ID2D1DeviceContext::CreateEffect. ///