From 915456139a49f9fcf1080ecdb2f9d80649362e1f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 30 Sep 2023 23:05:33 +0200 Subject: [PATCH 1/7] Add D2D1EffectXmlFactory type --- .../Interop/Helpers/D2D1EffectXmlFactory.cs | 183 ++++++++++++++++++ 1 file changed, 183 insertions(+) create mode 100644 src/ComputeSharp.D2D1/Shaders/Interop/Helpers/D2D1EffectXmlFactory.cs diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Helpers/D2D1EffectXmlFactory.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Helpers/D2D1EffectXmlFactory.cs new file mode 100644 index 00000000..a832e566 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Helpers/D2D1EffectXmlFactory.cs @@ -0,0 +1,183 @@ +using System; +using System.Text; +using System.Threading; +using ComputeSharp.D2D1.Descriptors; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.Interop; + +/// +/// A factory type to produce effect registration XML blobs. +/// +internal static unsafe class D2D1EffectXmlFactory +{ + /// + /// The shared instance to use to build effect registration XML blobs. + /// + private static readonly StringBuilder XmlBuilder = new(4096); + + /// + /// Gets a instance with the effect registration XML blob for a given shader type. + /// + /// The type of shader type to build the XML for. + /// The instance with the effect registration XML blob. + public static EffectXml GetXmlBuffer() + where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor + { + StringBuilder builder = XmlBuilder; + + // We assume that the typical use of these APIs is not to ever try to concurrently register multiple + // effects, also because D2D factories are not even thread-safe anyway. So we can just serialize calls + // to the registration APIs and get away with a very simple and fast caching scheme, where we simply + // use a single StringBuilder instance as temporary buffer to write the XML text to. The builder is + // initialized with a size of 4096, which should be more than enough to hold pretty much all XML values. + // When the returned Buffer value is disposed, the lock will be released. + Monitor.Enter(builder); + + // Guard the XML building logic in a try/finally to avoid hanging + try + { + _ = XmlBuilder.Clear(); + + // Write the metadata properties for the effect + _ = builder.Append($""" + + + + + + + + """); + + // Add the input nodes, if any + for (int i = 0; i < D2D1PixelShader.GetInputCount(); i++) + { + _ = builder.Append('\n'); + _ = builder.Append($" "); + } + + // Close the inputs tag and add all effect properties + _ = builder.Append('\n'); + _ = builder.Append(""" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + """); + + // Null terminator for the text + _ = builder.Append('\0'); + } + catch + { + // Something went wrong building the XML, so we have to release the lock early + Monitor.Exit(builder); + } + + return new(builder); + } + + /// + /// A simple buffer for an effect XML blob. + /// + public readonly ref struct EffectXml + { + /// + /// The instance holding the registration blob. + /// + private readonly StringBuilder builder; + + /// + /// Creates a new value with the specified parameters. + /// + /// The instance with the effect XML. + [Obsolete($"This should only be used by {nameof(D2D1EffectXmlFactory)}.")] + public EffectXml(StringBuilder builder) + { + this.builder = builder; + } + + /// + /// Gets a for the buffer (pretty much always with no allocation). + /// + /// The value with the effect XML blob. + public ReadOnlySpan GetOrAllocateBuffer() + { +#if NET6_0_OR_GREATER + StringBuilder.ChunkEnumerator enumerator = this.builder.GetChunks(); + + if (enumerator.MoveNext()) + { + ReadOnlyMemory segment = enumerator.Current; + + if (!enumerator.MoveNext()) + { + return segment.Span; + } + } +#endif + + return this.builder.ToString().AsSpan(); + } + + /// + public void Dispose() + { + Monitor.Exit(this.builder); + } + } +} \ No newline at end of file From aae13e1c3e4097b0d6f5c3cef513147483c834aa Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 1 Oct 2023 00:55:43 +0200 Subject: [PATCH 2/7] Use centralized XML writer for effect registration --- .../Shaders/Interop/D2D1PixelShaderEffect.cs | 223 ++---------------- 1 file changed, 19 insertions(+), 204 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs index 71ac7af4..5966c1f2 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs @@ -1,5 +1,7 @@ using System; +using System.Buffers; using System.Runtime.CompilerServices; +using System.Text; using ComputeSharp.D2D1.Descriptors; using ComputeSharp.D2D1.Extensions; using ComputeSharp.D2D1.Interop.Effects; @@ -101,111 +103,9 @@ public static unsafe class D2D1PixelShaderEffect effectId = default; - ArrayPoolBufferWriter writer = new(ArrayPoolBinaryWriter.DefaultInitialBufferSize); + using D2D1EffectXmlFactory.EffectXml effectXml = D2D1EffectXmlFactory.GetXmlBuffer(); - // Build the XML text - writer.WriteRaw(""" - - - - - - - - - """); - - // Add the input nodes - for (int i = 0; i < PixelShaderEffect.For.Instance.InputCount; i++) - { - writer.WriteRaw(" - - """); - } - - // Write the last part of the XML (including the buffer property) - writer.WriteRaw(""" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - """); - - // Null terminator for the text - writer.WriteRaw('\0'); - - fixed (char* pXml = writer.WrittenSpan) + fixed (char* pXml = effectXml.GetOrAllocateBuffer()) fixed (char* pBufferPropertyName = nameof(D2D1PixelShaderEffectProperty.ConstantBuffer)) fixed (char* pResourceTextureManager0PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager0)) fixed (char* pResourceTextureManager1PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager1)) @@ -301,8 +201,6 @@ public static unsafe class D2D1PixelShaderEffect effectId = PixelShaderEffect.For.Instance.Id; } - - writer.Dispose(); } /// @@ -355,108 +253,25 @@ public static unsafe class D2D1PixelShaderEffect writer.WriteRaw(PixelShaderEffect.For.Instance.Id); writer.WriteRaw(PixelShaderEffect.For.Instance.InputCount); - // Build the XML text - writer.WriteRaw(""" - - - - - - - - - """u8); - - // Add the input nodes - for (int i = 0; i < PixelShaderEffect.For.Instance.InputCount; i++) + // Retrieve the effect XML and include it into the registration blob + using (D2D1EffectXmlFactory.EffectXml effectXml = D2D1EffectXmlFactory.GetXmlBuffer()) { - writer.WriteRaw(" + ReadOnlySpan registrationText = effectXml.GetOrAllocateBuffer(); + int maxRegistrationTextByteCount = Encoding.UTF8.GetMaxByteCount(registrationText.Length); + byte[] registrationTextUtf8 = ArrayPool.Shared.Rent(maxRegistrationTextByteCount); - """u8); + // Encode the effect XML into UTF8 to write into the registration blob. + // This is marginally slower than building it inline here directly in + // UTF8 format, but the registration blob is not the primary scenario. + // Besides, the overhead is just a matter of a few more microseconds. + int registrationTextByteCount = Encoding.UTF8.GetBytes(registrationText, registrationTextUtf8); + + // Build the XML text + writer.WriteRaw(registrationTextUtf8.AsSpan(0, registrationTextByteCount)); + + ArrayPool.Shared.Return(registrationTextUtf8); } - // Write the last part of the XML (including the buffer property) - writer.WriteRaw(""" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - """u8); - - // Null terminator for the text - writer.WriteRaw((byte)'\0'); - // Bindings writer.WriteRaw(D2D1PixelShaderEffectProperty.NumberOfProperties); writer.WriteRaw("ConstantBuffer"u8); From ba7d015a7596d130544bfcc6ff2143feebee4846 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 1 Oct 2023 00:56:36 +0200 Subject: [PATCH 3/7] Remove leftover methods --- .../ArrayPoolBinaryWriterExtensions.cs | 92 ------------------- 1 file changed, 92 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriterExtensions.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriterExtensions.cs index a4d08422..1b9baf7a 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriterExtensions.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriterExtensions.cs @@ -1,10 +1,6 @@ using System; -#if NET6_0_OR_GREATER -using System.Buffers.Text; -#endif using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Text; namespace ComputeSharp.D2D1.Shaders.Interop.Buffers; @@ -30,22 +26,6 @@ internal static class ArrayPoolBinaryWriterExtensions writer.Advance(sizeof(T)); } - /// - /// Writes the raw value of type into the buffer. - /// - /// The type of value to write. - /// The target instance to write data to. - /// The value to write. - public static unsafe void WriteRaw(this ref ArrayPoolBufferWriter writer, scoped in T value) - where T : unmanaged - { - Span span = writer.GetSpan(1); - - MemoryMarshal.GetReference(span) = value; - - writer.Advance(1); - } - /// /// Writes the raw data from the input into the buffer. /// @@ -61,76 +41,4 @@ internal static class ArrayPoolBinaryWriterExtensions writer.Advance(data.Length); } - -#if !NET6_0_OR_GREATER - /// - /// Writes the raw data from the input into the buffer. - /// - /// The target instance to write data to. - /// The data to write. - public static void WriteRaw(this ref ArrayPoolBufferWriter writer, string data) - { - Span span = writer.GetSpan(data.Length); - - data.AsSpan().CopyTo(span); - - writer.Advance(data.Length); - } -#endif - - /// - /// Writes an value as UTF8 bytes into the buffer. - /// - /// The target instance to write data to. - /// The value to write. - public static void WriteAsUtf8(this ref ArrayPoolBufferWriter writer, int value) - { -#if NET6_0_OR_GREATER - // Get a span of at least 10 elements (10 is the length of int.MaxValue as text) - Span span = writer.GetSpan(10); - - _ = Utf8Formatter.TryFormat(value, span, out int bytesWritten); - - writer.Advance(bytesWritten); -#else - // Just accept the allocation on .NET Standard 2.0 - writer.WriteAsUtf8(value.ToString()); -#endif - } - - /// - /// Writes text as UTF8 bytes into the buffer. - /// - /// The target instance to write data to. - /// The text to write. - public static void WriteAsUtf8(this ref ArrayPoolBufferWriter writer, string text) - { - int maximumByteSize = Encoding.UTF8.GetMaxByteCount(text.Length); - - Span span = writer.GetSpan(maximumByteSize); - - int writtenBytes = Encoding.UTF8.GetBytes(text.AsSpan(), span); - - writer.Advance(writtenBytes); - } - - /// - /// Writes an value as Unicode bytes into the buffer. - /// - /// The target instance to write data to. - /// The value to write. - public static void WriteAsUnicode(this ref ArrayPoolBufferWriter writer, int value) - { -#if NET6_0_OR_GREATER - // Get a span of at least 10 elements (10 is the length of int.MaxValue as text) - Span span = writer.GetSpan(10); - - _ = value.TryFormat(span, out int charsWritten); - - writer.Advance(charsWritten); -#else - // Just accept the allocation on .NET Standard 2.0 - writer.WriteRaw(value.ToString().AsSpan()); -#endif - } } \ No newline at end of file From 3479b3b049c3a4ed54820d1b3ea94aa260309783 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 1 Oct 2023 01:04:23 +0200 Subject: [PATCH 4/7] Simplify ArrayPoolBufferWriter type --- ...yWriter{T}.cs => ArrayPoolBinaryWriter.cs} | 99 ++++++----- .../ArrayPoolBinaryWriterExtensions.cs | 44 ----- .../Shaders/Interop/D2D1PixelShaderEffect.cs | 158 +++++++++--------- 3 files changed, 140 insertions(+), 161 deletions(-) rename src/ComputeSharp.D2D1/Shaders/Interop/Buffers/{ArrayPoolBinaryWriter{T}.cs => ArrayPoolBinaryWriter.cs} (71%) delete mode 100644 src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriterExtensions.cs diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter{T}.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs similarity index 71% rename from src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter{T}.cs rename to src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs index ba7c3cf5..1b65ad4c 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter{T}.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs @@ -5,32 +5,27 @@ using System.Diagnostics.CodeAnalysis; using System.Numerics; #endif using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; #if !NET6_0_OR_GREATER using BitOperations = ComputeSharp.NetStandard.BitOperations; #endif namespace ComputeSharp.D2D1.Shaders.Interop.Buffers; -/// -internal static class ArrayPoolBinaryWriter +/// +/// Represents a heap-based, array-backed output sink into which binary data can be written. +/// +internal ref struct ArrayPoolBufferWriter { /// /// The default buffer size to use to expand empty arrays. /// public const int DefaultInitialBufferSize = 256; -} -/// -/// Represents a heap-based, array-backed output sink into which data can be written. -/// -/// The type of values to write. -internal ref struct ArrayPoolBufferWriter - where T : unmanaged -{ /// - /// The underlying array. + /// The underlying array. /// - private T[]? array; + private byte[]? array; /// /// The starting offset within . @@ -38,11 +33,11 @@ internal ref struct ArrayPoolBufferWriter private int index; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the type. /// public ArrayPoolBufferWriter(int capacity) { - this.array = ArrayPool.Shared.Rent(capacity); + this.array = ArrayPool.Shared.Rent(capacity); this.index = 0; } @@ -50,12 +45,12 @@ internal ref struct ArrayPoolBufferWriter /// Gets the data written to the underlying buffer so far, as a . /// [UnscopedRef] - public readonly ReadOnlySpan WrittenSpan + public readonly ReadOnlySpan WrittenSpan { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - T[]? array = this.array; + byte[]? array = this.array; default(ObjectDisposedException).ThrowIfNull(array); @@ -63,14 +58,57 @@ internal ref struct ArrayPoolBufferWriter } } + /// + /// Writes the raw value of type into the buffer. + /// + /// The type of value to write. + /// The value to write. + /// This method will just blit the data of into the target buffer. + public unsafe void Write(scoped in T value) + { + Span span = GetSpan(sizeof(T)); + + Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(span), value); + + Advance(sizeof(T)); + } + + /// + /// Writes the raw data from the input into the buffer. + /// + /// The data to write. + public void Write(scoped ReadOnlySpan data) + { + Span span = GetSpan(data.Length); + + data.CopyTo(span); + + Advance(data.Length); + } + + /// + public void Dispose() + { + byte[]? array = this.array; + + if (array is null) + { + return; + } + + this.array = null; + + ArrayPool.Shared.Return(array); + } + /// /// Advances the current writer. /// /// The amount to advance. /// Must be called after . - internal void Advance(int count) + private void Advance(int count) { - T[]? array = this.array; + byte[]? array = this.array; default(ObjectDisposedException).ThrowIfNull(array); default(ArgumentOutOfRangeException).ThrowIfNegative(count); @@ -85,7 +123,7 @@ internal ref struct ArrayPoolBufferWriter /// The capacity to request. /// A to write data to. [UnscopedRef] - internal Span GetSpan(int sizeHint = 0) + private Span GetSpan(int sizeHint = 0) { CheckBufferAndEnsureCapacity(sizeHint); @@ -99,7 +137,7 @@ internal ref struct ArrayPoolBufferWriter [MethodImpl(MethodImplOptions.AggressiveInlining)] private void CheckBufferAndEnsureCapacity(int sizeHint) { - T[]? array = this.array; + byte[]? array = this.array; default(ObjectDisposedException).ThrowIfNull(array); default(ArgumentOutOfRangeException).ThrowIfNegative(sizeHint); @@ -134,27 +172,12 @@ internal ref struct ArrayPoolBufferWriter minimumSize = BitOperations.RoundUpToPowerOf2(minimumSize); } - T[] newArray = ArrayPool.Shared.Rent((int)minimumSize); + byte[] newArray = ArrayPool.Shared.Rent((int)minimumSize); - Buffer.BlockCopy(this.array!, 0, newArray, 0, this.index * sizeof(T)); + Buffer.BlockCopy(this.array!, 0, newArray, 0, this.index); - ArrayPool.Shared.Return(this.array!); + ArrayPool.Shared.Return(this.array!); this.array = newArray; } - - /// - public void Dispose() - { - T[]? array = this.array; - - if (array is null) - { - return; - } - - this.array = null; - - ArrayPool.Shared.Return(array); - } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriterExtensions.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriterExtensions.cs deleted file mode 100644 index 1b9baf7a..00000000 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriterExtensions.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace ComputeSharp.D2D1.Shaders.Interop.Buffers; - -/// -/// Helpers for the type. -/// -internal static class ArrayPoolBinaryWriterExtensions -{ - /// - /// Writes the raw value of type into the buffer. - /// - /// The type of value to write. - /// The target instance to write data to. - /// The value to write. - /// This method will just blit the data of into the target buffer. - public static unsafe void WriteRaw(this ref ArrayPoolBufferWriter writer, scoped in T value) - where T : unmanaged - { - Span span = writer.GetSpan(sizeof(T)); - - Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(span), value); - - writer.Advance(sizeof(T)); - } - - /// - /// Writes the raw data from the input into the buffer. - /// - /// The type of values in the target writer. - /// The target instance to write data to. - /// The data to write. - public static void WriteRaw(this ref ArrayPoolBufferWriter writer, scoped ReadOnlySpan data) - where T : unmanaged - { - Span span = writer.GetSpan(data.Length); - - data.CopyTo(span); - - writer.Advance(data.Length); - } -} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs index 5966c1f2..9db401a5 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs @@ -244,14 +244,14 @@ public static unsafe class D2D1PixelShaderEffect public static ReadOnlyMemory GetRegistrationBlob(out Guid effectId) where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor { - ArrayPoolBufferWriter writer = new(ArrayPoolBinaryWriter.DefaultInitialBufferSize); + ArrayPoolBufferWriter writer = new(ArrayPoolBufferWriter.DefaultInitialBufferSize); // Blob id - writer.WriteRaw(D2D1EffectRegistrationData.V1.BlobId); + writer.Write(D2D1EffectRegistrationData.V1.BlobId); // Effect id and number of inputs - writer.WriteRaw(PixelShaderEffect.For.Instance.Id); - writer.WriteRaw(PixelShaderEffect.For.Instance.InputCount); + writer.Write(PixelShaderEffect.For.Instance.Id); + writer.Write(PixelShaderEffect.For.Instance.InputCount); // Retrieve the effect XML and include it into the registration blob using (D2D1EffectXmlFactory.EffectXml effectXml = D2D1EffectXmlFactory.GetXmlBuffer()) @@ -267,88 +267,88 @@ public static unsafe class D2D1PixelShaderEffect int registrationTextByteCount = Encoding.UTF8.GetBytes(registrationText, registrationTextUtf8); // Build the XML text - writer.WriteRaw(registrationTextUtf8.AsSpan(0, registrationTextByteCount)); + writer.Write(registrationTextUtf8.AsSpan(0, registrationTextByteCount)); ArrayPool.Shared.Return(registrationTextUtf8); } // Bindings - writer.WriteRaw(D2D1PixelShaderEffectProperty.NumberOfProperties); - writer.WriteRaw("ConstantBuffer"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetConstantBuffer); - writer.WriteRaw((nint)PixelShaderEffect.SetConstantBuffer); - writer.WriteRaw("ResourceTextureManager0"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager0); - writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager0); - writer.WriteRaw("ResourceTextureManager1"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager1); - writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager1); - writer.WriteRaw("ResourceTextureManager2"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager2); - writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager2); - writer.WriteRaw("ResourceTextureManager3"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager3); - writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager3); - writer.WriteRaw("ResourceTextureManager4"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager4); - writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager4); - writer.WriteRaw("ResourceTextureManager5"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager5); - writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager5); - writer.WriteRaw("ResourceTextureManager6"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager6); - writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager6); - writer.WriteRaw("ResourceTextureManager7"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager7); - writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager7); - writer.WriteRaw("ResourceTextureManager8"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager8); - writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager8); - writer.WriteRaw("ResourceTextureManager9"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager9); - writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager9); - writer.WriteRaw("ResourceTextureManager10"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager10); - writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager10); - writer.WriteRaw("ResourceTextureManager11"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager11); - writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager11); - writer.WriteRaw("ResourceTextureManager12"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager12); - writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager12); - writer.WriteRaw("ResourceTextureManager13"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager13); - writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager13); - writer.WriteRaw("ResourceTextureManager14"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager14); - writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager14); - writer.WriteRaw("ResourceTextureManager15"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager15); - writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager15); - writer.WriteRaw("TransformMapper"u8); - writer.WriteRaw((byte)'\0'); - writer.WriteRaw((nint)PixelShaderEffect.GetTransformMapper); - writer.WriteRaw((nint)PixelShaderEffect.SetTransformMapper); + writer.Write(D2D1PixelShaderEffectProperty.NumberOfProperties); + writer.Write("ConstantBuffer"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetConstantBuffer); + writer.Write((nint)PixelShaderEffect.SetConstantBuffer); + writer.Write("ResourceTextureManager0"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager0); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager0); + writer.Write("ResourceTextureManager1"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager1); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager1); + writer.Write("ResourceTextureManager2"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager2); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager2); + writer.Write("ResourceTextureManager3"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager3); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager3); + writer.Write("ResourceTextureManager4"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager4); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager4); + writer.Write("ResourceTextureManager5"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager5); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager5); + writer.Write("ResourceTextureManager6"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager6); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager6); + writer.Write("ResourceTextureManager7"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager7); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager7); + writer.Write("ResourceTextureManager8"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager8); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager8); + writer.Write("ResourceTextureManager9"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager9); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager9); + writer.Write("ResourceTextureManager10"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager10); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager10); + writer.Write("ResourceTextureManager11"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager11); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager11); + writer.Write("ResourceTextureManager12"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager12); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager12); + writer.Write("ResourceTextureManager13"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager13); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager13); + writer.Write("ResourceTextureManager14"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager14); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager14); + writer.Write("ResourceTextureManager15"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager15); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager15); + writer.Write("TransformMapper"u8); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetTransformMapper); + writer.Write((nint)PixelShaderEffect.SetTransformMapper); // Effect factory - writer.WriteRaw((nint)PixelShaderEffect.For.Instance.Factory); + writer.Write((nint)PixelShaderEffect.For.Instance.Factory); byte[] registrationBlob = writer.WrittenSpan.ToArray(); From a2a9a07806dadab2081352ee53ced0fbb5b053c6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 1 Oct 2023 01:05:36 +0200 Subject: [PATCH 5/7] Remove leftover PinnedBufferMemoryManager type --- .../Buffers/PinnedBufferMemoryManager.cs | 56 ------------------- 1 file changed, 56 deletions(-) delete mode 100644 src/ComputeSharp.D2D1/Shaders/Interop/Buffers/PinnedBufferMemoryManager.cs diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/PinnedBufferMemoryManager.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/PinnedBufferMemoryManager.cs deleted file mode 100644 index 72f366df..00000000 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/PinnedBufferMemoryManager.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Buffers; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace ComputeSharp.D2D1.Shaders.Interop.Buffers; - -/// -/// A custom that wraps a pinned memory buffer. -/// -internal sealed unsafe class PinnedBufferMemoryManager : MemoryManager -{ - /// - /// A pointer to the buffer. - /// - private readonly byte* buffer; - - /// - /// The length of the buffer. - /// - private readonly int length; - - /// - /// Initializes a new instance of the class with the specified parameters. - /// - /// A wrapping the input pinned buffer. - public PinnedBufferMemoryManager(ReadOnlySpan span) - { - this.buffer = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(span)); - this.length = span.Length; - } - - /// - public override Span GetSpan() - { - return new(this.buffer, this.length); - } - - /// - public override unsafe MemoryHandle Pin(int elementIndex = 0) - { - default(ArgumentOutOfRangeException).ThrowIfNotInRange(elementIndex, 0, this.length); - - return new(this.buffer + elementIndex); - } - - /// - public override void Unpin() - { - } - - /// - protected override void Dispose(bool disposing) - { - } -} \ No newline at end of file From 277b9a6354c13a2bfbd9348c1c9a437423cb4f8f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 1 Oct 2023 01:16:17 +0200 Subject: [PATCH 6/7] Improve concurrency in D2D1EffectXmlFactory --- .../Shaders/Interop/D2D1PixelShaderEffect.cs | 4 +- .../Interop/Helpers/D2D1EffectXmlFactory.cs | 67 ++++++++----------- 2 files changed, 29 insertions(+), 42 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs index 9db401a5..a03c6b9e 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs @@ -105,7 +105,7 @@ public static unsafe class D2D1PixelShaderEffect using D2D1EffectXmlFactory.EffectXml effectXml = D2D1EffectXmlFactory.GetXmlBuffer(); - fixed (char* pXml = effectXml.GetOrAllocateBuffer()) + fixed (char* pXml = effectXml.GetBuffer()) fixed (char* pBufferPropertyName = nameof(D2D1PixelShaderEffectProperty.ConstantBuffer)) fixed (char* pResourceTextureManager0PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager0)) fixed (char* pResourceTextureManager1PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager1)) @@ -256,7 +256,7 @@ public static unsafe class D2D1PixelShaderEffect // Retrieve the effect XML and include it into the registration blob using (D2D1EffectXmlFactory.EffectXml effectXml = D2D1EffectXmlFactory.GetXmlBuffer()) { - ReadOnlySpan registrationText = effectXml.GetOrAllocateBuffer(); + ReadOnlySpan registrationText = effectXml.GetBuffer(); int maxRegistrationTextByteCount = Encoding.UTF8.GetMaxByteCount(registrationText.Length); byte[] registrationTextUtf8 = ArrayPool.Shared.Rent(maxRegistrationTextByteCount); diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Helpers/D2D1EffectXmlFactory.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Helpers/D2D1EffectXmlFactory.cs index a832e566..36f6bc56 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Helpers/D2D1EffectXmlFactory.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Helpers/D2D1EffectXmlFactory.cs @@ -1,6 +1,6 @@ using System; +using System.Buffers; using System.Text; -using System.Threading; using ComputeSharp.D2D1.Descriptors; #pragma warning disable CS0618 @@ -27,18 +27,13 @@ internal static unsafe class D2D1EffectXmlFactory { StringBuilder builder = XmlBuilder; - // We assume that the typical use of these APIs is not to ever try to concurrently register multiple - // effects, also because D2D factories are not even thread-safe anyway. So we can just serialize calls - // to the registration APIs and get away with a very simple and fast caching scheme, where we simply - // use a single StringBuilder instance as temporary buffer to write the XML text to. The builder is - // initialized with a size of 4096, which should be more than enough to hold pretty much all XML values. - // When the returned Buffer value is disposed, the lock will be released. - Monitor.Enter(builder); - - // Guard the XML building logic in a try/finally to avoid hanging - try + // We use a simple caching schema here with a single StringBuilder instance shared across all threads. + // It is only used to write the effect XML blob and copy it, which is extremely fast. The lock itself + // is not taken during the actual effect registration, but only to build the effect XML text. The builder + // is initialized with a size of 4096, which should be more than enough to hold pretty much all XML values. + lock (builder) { - _ = XmlBuilder.Clear(); + _ = builder.Clear(); // Write the metadata properties for the effect _ = builder.Append($""" @@ -121,14 +116,9 @@ internal static unsafe class D2D1EffectXmlFactory // Null terminator for the text _ = builder.Append('\0'); - } - catch - { - // Something went wrong building the XML, so we have to release the lock early - Monitor.Exit(builder); - } - return new(builder); + return new(builder); + } } /// @@ -137,9 +127,14 @@ internal static unsafe class D2D1EffectXmlFactory public readonly ref struct EffectXml { /// - /// The instance holding the registration blob. + /// The buffer with the effect XML blob. /// - private readonly StringBuilder builder; + private readonly char[] buffer; + + /// + /// The length of the effect XML blob. + /// + private readonly int length; /// /// Creates a new value with the specified parameters. @@ -148,36 +143,28 @@ internal static unsafe class D2D1EffectXmlFactory [Obsolete($"This should only be used by {nameof(D2D1EffectXmlFactory)}.")] public EffectXml(StringBuilder builder) { - this.builder = builder; + // Rent a buffer from the pool with the current builder size + this.buffer = ArrayPool.Shared.Rent(builder.Length); + this.length = builder.Length; + + // Copy the current builder content with the effect XML blob into the + // rented buffer. This allows the builder to be reused for other effects. + builder.CopyTo(0, this.buffer, 0, builder.Length); } /// - /// Gets a for the buffer (pretty much always with no allocation). + /// Gets a for the effect XML blob. /// /// The value with the effect XML blob. - public ReadOnlySpan GetOrAllocateBuffer() + public ReadOnlySpan GetBuffer() { -#if NET6_0_OR_GREATER - StringBuilder.ChunkEnumerator enumerator = this.builder.GetChunks(); - - if (enumerator.MoveNext()) - { - ReadOnlyMemory segment = enumerator.Current; - - if (!enumerator.MoveNext()) - { - return segment.Span; - } - } -#endif - - return this.builder.ToString().AsSpan(); + return this.buffer.AsSpan(0, this.length); } /// public void Dispose() { - Monitor.Exit(this.builder); + ArrayPool.Shared.Return(this.buffer); } } } \ No newline at end of file From dba631bf3ba3d1a6e38ef41184a1a1b2ce3a3c57 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 1 Oct 2023 11:33:52 +0200 Subject: [PATCH 7/7] Rename ArrayPoolBufferWriter type for consistency --- .../Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs | 7 +++---- .../Shaders/Interop/D2D1PixelShaderEffect.cs | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs index 1b65ad4c..c7a95502 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Buffers/ArrayPoolBinaryWriter.cs @@ -15,7 +15,7 @@ namespace ComputeSharp.D2D1.Shaders.Interop.Buffers; /// /// Represents a heap-based, array-backed output sink into which binary data can be written. /// -internal ref struct ArrayPoolBufferWriter +internal ref struct ArrayPoolBinaryWriter { /// /// The default buffer size to use to expand empty arrays. @@ -33,9 +33,9 @@ internal ref struct ArrayPoolBufferWriter private int index; /// - /// Initializes a new instance of the type. + /// Initializes a new instance of the type. /// - public ArrayPoolBufferWriter(int capacity) + public ArrayPoolBinaryWriter(int capacity) { this.array = ArrayPool.Shared.Rent(capacity); this.index = 0; @@ -111,7 +111,6 @@ internal ref struct ArrayPoolBufferWriter byte[]? array = this.array; default(ObjectDisposedException).ThrowIfNull(array); - default(ArgumentOutOfRangeException).ThrowIfNegative(count); default(ArgumentException).ThrowIf(this.index > array.Length - count); this.index += count; diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs index a03c6b9e..a248c778 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs @@ -244,7 +244,7 @@ public static unsafe class D2D1PixelShaderEffect public static ReadOnlyMemory GetRegistrationBlob(out Guid effectId) where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor { - ArrayPoolBufferWriter writer = new(ArrayPoolBufferWriter.DefaultInitialBufferSize); + ArrayPoolBinaryWriter writer = new(ArrayPoolBinaryWriter.DefaultInitialBufferSize); // Blob id writer.Write(D2D1EffectRegistrationData.V1.BlobId);