diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs index d6ca1bc2..9ef3b213 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs @@ -249,24 +249,8 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene using (writer.WriteBlock()) { - // Add the System directives first, in the correct order - foreach (string usingDirective in usingDirectives.AsEnumerable().Where(static name => name.StartsWith("global::System")).OrderBy(static name => name)) - { - writer.WriteLine($"using {usingDirective};"); - } - - // Add the other directives, also sorted in the correct order - foreach (string usingDirective in usingDirectives.AsEnumerable().Where(static name => !name.StartsWith("global::System")).OrderBy(static name => name)) - { - writer.WriteLine($"using {usingDirective};"); - } - - foreach (IndentedTextWriter.Callback callback in additionalTypes.WrittenSpan) - { - writer.WriteLine(); - - callback(item, writer); - } + writer.WriteSortedUsingDirectives(usingDirectives.AsEnumerable()); + writer.WriteLineSeparatedMembers(additionalTypes.WrittenSpan, (callback, writer) => callback(item, writer)); } } diff --git a/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs index 41770120..88dd0208 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using System.Linq; using System.Runtime.CompilerServices; using ComputeSharp.SourceGeneration.Helpers; @@ -40,6 +42,30 @@ internal static class IndentedTextWriterExtensions } } + /// + /// Writes a sequence of using directives, sorted correctly. + /// + /// The instance to write into. + /// The sequence of using directives to write. + public static void WriteSortedUsingDirectives(this IndentedTextWriter writer, IEnumerable usingDirectives) + { + // Add the System directives first, in the correct order + foreach (string usingDirective in usingDirectives.Where(static name => name.StartsWith("global::System")).OrderBy(static name => name)) + { + writer.WriteLine($"using {usingDirective};"); + } + + // Add the other directives, also sorted in the correct order + foreach (string usingDirective in usingDirectives.Where(static name => !name.StartsWith("global::System")).OrderBy(static name => name)) + { + writer.WriteLine($"using {usingDirective};"); + } + + // Leave a trailing blank line if at least one using directive has been written. + // This is so that any members will correctly have a leading blank line before. + writer.WriteLineIf(usingDirectives.Any()); + } + /// /// Writes a new line into the target writer depending on an input condition. /// diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index 1fef76ce..bd414527 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -12,38 +12,148 @@ partial class IShaderGenerator partial class LoadBytecode { /// - /// Writes the LoadBytecode method. + /// Writes the HlslBytecode property. /// /// The input instance with gathered shader info. /// The instance to write into. - public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer) + public static void WriteHlslBytecodeSyntax(ShaderInfo info, IndentedTextWriter writer) { writer.WriteLine("/// "); writer.WriteGeneratedAttributes(GeneratorName); - writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.LoadBytecode(ref TLoader loader, int threadsX, int threadsY, int threadsZ)"); + writer.Write($"readonly global::System.ReadOnlyMemory global::ComputeSharp.__Internals.IShader.HlslBytecode => "); - using (writer.WriteBlock()) + // Just like with the D2D1 generator, only return the MemoryManager if we do have HLSL bytecode + if (info.HlslInfo is not HlslBytecodeInfo.Success) { - // If there is no HLSL bytecode, there's nothing left to do - if (info.HlslInfo is not HlslBytecodeInfo.Success success) - { - return; - } + writer.WriteLine("default;"); + } + else + { + writer.WriteLine("global::ComputeSharp.Generated.HlslBytecodeMemoryManager.Instance.Memory;"); + } + } - // Check that the [numthreads] values match - writer.WriteLine($"if (threadsX == {info.ThreadsX} && threadsY == {info.ThreadsY} && threadsZ == {info.ThreadsZ})"); + /// + /// Registers a callback to generate an additional type, if needed. + /// + /// The input instance with gathered shader info. + /// The registered callbacks to generate additional types. + /// The using directives needed by the generated code. + public static void RegisterAdditionalTypeSyntax( + ShaderInfo info, + ImmutableArrayBuilder> callbacks, + ImmutableHashSetBuilder usingDirectives) + { + // If there is no bytecode, no memory manager is needed + if (info.HlslInfo is not HlslBytecodeInfo.Success) + { + return; + } + + usingDirectives.Add("global::System"); + usingDirectives.Add("global::System.Buffers"); + usingDirectives.Add("global::System.CodeDom.Compiler"); + usingDirectives.Add("global::System.Diagnostics"); + usingDirectives.Add("global::System.Diagnostics.CodeAnalysis"); + usingDirectives.Add("global::System.Runtime.CompilerServices"); + usingDirectives.Add("global::System.Runtime.InteropServices"); + + // Declare the HlslBytecodeMemoryManager custom memory manager type + static void Callback(ShaderInfo info, IndentedTextWriter writer) + { + writer.WriteLine($$"""/// """); + writer.WriteLine($$"""/// implementation to get the HLSL bytecode."""); + writer.WriteLine($$"""/// """); + writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false); + writer.WriteLine($$"""file sealed class HlslBytecodeMemoryManager : MemoryManager"""); using (writer.WriteBlock()) { - writer.Write("global::System.ReadOnlySpan bytecode = new byte[] { "); + // Static singleton instance (to avoid the static constructor, just like with the input types) + writer.WriteLine($$"""/// The singleton instance to use."""); + writer.WriteLine($$"""public static readonly HlslBytecodeMemoryManager Instance = new();"""); - SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(success.Bytecode.AsSpan(), writer); + // RVA field (with the compiled HLSL bytecode, on a single line) + writer.WriteLine(); + writer.WriteLine("/// The RVA data with the HLSL bytecode."); + writer.Write("private static ReadOnlySpan Data => new byte[] { "); + + SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(((HlslBytecodeInfo.Success)info.HlslInfo).Bytecode.AsSpan(), writer); writer.WriteLine(" };"); writer.WriteLine(); - writer.WriteLine("loader.LoadEmbeddedBytecode(bytecode);"); + + // Add the remaining members for the memory manager + writer.WriteLine(""" + /// + public override unsafe Span GetSpan() + { + return new(Unsafe.AsPointer(ref MemoryMarshal.GetReference(Data)), Data.Length); + } + + /// + public override Memory Memory + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => CreateMemory(Data.Length); + } + + /// + public override unsafe MemoryHandle Pin(int elementIndex) + { + return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this); + } + + /// + public override void Unpin() + { + } + + /// + protected override void Dispose(bool disposing) + { + } + """, isMultiline: true); } } + + callbacks.Add(Callback); + } + + /// + /// Writes the ThreadsX property. + /// + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteThreadsXSyntax(ShaderInfo info, IndentedTextWriter writer) + { + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(GeneratorName); + writer.WriteLine($"readonly int global::ComputeSharp.__Internals.IShader.ThreadsX => {info.ThreadsX};"); + } + + /// + /// Writes the ThreadsY property. + /// + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteThreadsYSyntax(ShaderInfo info, IndentedTextWriter writer) + { + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(GeneratorName); + writer.WriteLine($"readonly int global::ComputeSharp.__Internals.IShader.ThreadsY => {info.ThreadsY};"); + } + + /// + /// Writes the ThreadsZ property. + /// + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteThreadsZSyntax(ShaderInfo info, IndentedTextWriter writer) + { + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(GeneratorName); + writer.WriteLine($"readonly int global::ComputeSharp.__Internals.IShader.ThreadsZ => {info.ThreadsZ};"); } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index f7b11ec2..d7c41ae6 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -145,10 +145,18 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator { using ImmutableArrayBuilder> declaredMembers = new(); + declaredMembers.Add(LoadBytecode.WriteThreadsXSyntax); + declaredMembers.Add(LoadBytecode.WriteThreadsYSyntax); + declaredMembers.Add(LoadBytecode.WriteThreadsZSyntax); + declaredMembers.Add(LoadBytecode.WriteHlslBytecodeSyntax); declaredMembers.Add(LoadDispatchData.WriteSyntax); declaredMembers.Add(LoadDispatchMetadata.WriteSyntax); declaredMembers.Add(BuildHlslSource.WriteSyntax); - declaredMembers.Add(LoadBytecode.WriteSyntax); + + using ImmutableArrayBuilder> additionalTypes = new(); + using ImmutableHashSetBuilder usingDirectives = new(); + + LoadBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives); using IndentedTextWriter writer = new(); @@ -158,6 +166,19 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator baseTypes: ReadOnlySpan.Empty, memberCallbacks: declaredMembers.WrittenSpan); + // Append any additional types as well + if (additionalTypes.Count > 0) + { + writer.WriteLine(); + writer.WriteLine("namespace ComputeSharp.Generated"); + + using (writer.WriteBlock()) + { + writer.WriteSortedUsingDirectives(usingDirectives.AsEnumerable()); + writer.WriteLineSeparatedMembers(additionalTypes.WrittenSpan, (callback, writer) => callback(item, writer)); + } + } + context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", writer.ToString()); }); } diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IBytecodeLoader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IBytecodeLoader.cs deleted file mode 100644 index 7521536c..00000000 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IBytecodeLoader.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.ComponentModel; - -namespace ComputeSharp.__Internals; - -/// -/// A base representing a bytecode loader for a shader being dispatched. -/// -[EditorBrowsable(EditorBrowsableState.Never)] -[Obsolete("This interface is not intended to be used directly by user code")] -public interface IBytecodeLoader -{ - /// - /// Loads the embedded shader bytecode for the shader being dispatched. - /// - /// The shader bytecode. - /// Thrown if the shader has already been initialized. - void LoadEmbeddedBytecode(ReadOnlySpan bytecode); -} \ No newline at end of file diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs index d39d9234..2a0e128c 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs @@ -10,6 +10,26 @@ namespace ComputeSharp.__Internals; [Obsolete("This interface is not intended to be used directly by user code")] public interface IShader { + /// + /// The number of threads in each thread group for the X axis. + /// + int ThreadsX { get; } + + /// + /// The number of threads in each thread group for the Y axis. + /// + int ThreadsY { get; } + + /// + /// The number of threads in each thread group for the Z axis. + /// + int ThreadsZ { get; } + + /// + /// Gets the HLSL bytecode for the current shader. + /// + ReadOnlyMemory HlslBytecode { get; } + /// /// Loads the dispatch data for the shader. /// @@ -42,18 +62,4 @@ public interface IShader [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This method is not intended to be called directly by user code")] void BuildHlslSource(out string hlslSource); - - /// - /// Loads the bytecode for the current shader. - /// - /// The type of bytecode loader being used. - /// The instance to use to load the bytecode. - /// The number of threads in each thread group for the X axis. - /// The number of threads in each thread group for the Y axis. - /// The number of threads in each thread group for the Z axis. - /// Thrown if the bytecode required runtime compilation and it wasn't supported on the current configuration. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be used directly by user code")] - void LoadBytecode(ref TLoader loader, int threadsX, int threadsY, int threadsZ) - where TLoader : struct, IBytecodeLoader; } \ No newline at end of file diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs index 322b9166..c492f2c4 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs @@ -63,28 +63,6 @@ public static partial class GraphicsDeviceExtensions context.Run(x, y, z, ref Unsafe.AsRef(in shader)); } - /// - /// Runs the input shader on a target instance, with the specified parameters. - /// - /// The type of compute shader to run. - /// The to use to run the shader. - /// The number of iterations to run on the X axis. - /// The number of iterations to run on the Y axis. - /// The number of iterations to run on the Z axis. - /// The number of threads in each thread group for the X axis. - /// The number of threads in each thread group for the Y axis. - /// The number of threads in each thread group for the Z axis. - /// The input instance representing the compute shader to run. - public static void For(this GraphicsDevice device, int x, int y, int z, int threadsX, int threadsY, int threadsZ, in T shader) - where T : struct, IComputeShader - { - default(ArgumentNullException).ThrowIfNull(device); - - using ComputeContext context = device.CreateComputeContext(); - - context.Run(x, y, z, threadsX, threadsY, threadsZ, ref Unsafe.AsRef(in shader)); - } - /// /// Runs the input shader on a target instance, with the specified parameters. /// diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index 0470f306..bb0f6d3f 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -8,7 +8,7 @@ using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Interop; using ComputeSharp.Interop.Allocation; -using ComputeSharp.Shaders.Models; +using ComputeSharp.Shaders.Loading; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE; diff --git a/src/ComputeSharp/Shaders/ComputeContext.cs b/src/ComputeSharp/Shaders/ComputeContext.cs index a2b58cf8..71108959 100644 --- a/src/ComputeSharp/Shaders/ComputeContext.cs +++ b/src/ComputeSharp/Shaders/ComputeContext.cs @@ -7,7 +7,6 @@ using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Shaders.Dispatching; using ComputeSharp.Shaders.Loading; -using ComputeSharp.Shaders.Models; using TerraFX.Interop.DirectX; #pragma warning disable CS0618 @@ -127,7 +126,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable where T : struct, IComputeShader { - Run(x, 1, 1, 64, 1, 1, ref shader); + Run(x, 1, 1, ref shader); } /// @@ -140,21 +139,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable where T : struct, IComputeShader { - Run(x, y, 1, 8, 8, 1, ref shader); - } - - /// - /// Runs the input shader with the specified parameters. - /// - /// The number of iterations to run on the X axis. - /// The number of iterations to run on the Y axis. - /// The number of iterations to run on the Z axis. - /// The input instance representing the compute shader to run. - internal readonly unsafe void Run(int x, int y, int z, ref T shader) - where T : struct, IComputeShader - { - - Run(x, y, z, 4, 4, 4, ref shader); + Run(x, y, 1, ref shader); } /// @@ -164,38 +149,24 @@ public struct ComputeContext : IDisposable, IAsyncDisposable /// The number of iterations to run on the X axis. /// The number of iterations to run on the Y axis. /// The number of iterations to run on the Z axis. - /// The number of threads in each thread group for the X axis. - /// The number of threads in each thread group for the Y axis. - /// The number of threads in each thread group for the Z axis. /// The input instance representing the compute shader to run. - internal readonly unsafe void Run( - int x, - int y, - int z, - int threadsX, - int threadsY, - int threadsZ, - ref T shader) + internal readonly unsafe void Run(int x, int y, int z, ref T shader) where T : struct, IComputeShader { default(InvalidOperationException).ThrowIf(this.device is null); default(ArgumentOutOfRangeException).ThrowIfNegativeOrZero(x); default(ArgumentOutOfRangeException).ThrowIfNegativeOrZero(y); default(ArgumentOutOfRangeException).ThrowIfNegativeOrZero(z); - default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(threadsX, 1, 1024); - default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(threadsY, 1, 1024); - default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(threadsZ, 1, 64); - default(ArgumentOutOfRangeException).ThrowIfGreaterThan(threadsX * threadsY * threadsZ, 1024, "threadsXYZ"); - int groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1); - int groupsY = Math.DivRem(y, threadsY, out int modY) + (modY == 0 ? 0 : 1); - int groupsZ = Math.DivRem(z, threadsZ, out int modZ) + (modZ == 0 ? 0 : 1); + int groupsX = Math.DivRem(x, shader.ThreadsX, out int modX) + (modX == 0 ? 0 : 1); + int groupsY = Math.DivRem(y, shader.ThreadsY, out int modY) + (modY == 0 ? 0 : 1); + int groupsZ = Math.DivRem(z, shader.ThreadsZ, out int modZ) + (modZ == 0 ? 0 : 1); default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(groupsX, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION); default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(groupsY, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(groupsZ, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); - PipelineData pipelineData = PipelineDataLoader.GetPipelineData(this.device, threadsX, threadsY, threadsZ, ref shader); + PipelineData pipelineData = PipelineDataLoader.GetPipelineData(this.device); ref CommandList commandList = ref GetCommandList(pipelineData.D3D12PipelineState); @@ -223,16 +194,13 @@ public struct ComputeContext : IDisposable, IAsyncDisposable int x = texture.Width; int y = texture.Height; - const int threadsX = 8; - const int threadsY = 8; - const int threadsZ = 1; - int groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1); - int groupsY = Math.DivRem(y, threadsY, out int modY) + (modY == 0 ? 0 : 1); + int groupsX = Math.DivRem(x, shader.ThreadsX, out int modX) + (modX == 0 ? 0 : 1); + int groupsY = Math.DivRem(y, shader.ThreadsY, out int modY) + (modY == 0 ? 0 : 1); default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(groupsX, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION); default(ArgumentOutOfRangeException).ThrowIfNotBetweenOrEqual(groupsY, 1, D3D11.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); - PipelineData pipelineData = PipelineDataLoader.GetPipelineData(this.device, threadsX, threadsY, threadsZ, ref shader); + PipelineData pipelineData = PipelineDataLoader.GetPipelineData(this.device); ref CommandList commandList = ref GetCommandList(pipelineData.D3D12PipelineState); diff --git a/src/ComputeSharp/Shaders/Dispatching/ShaderBytecodeLoader.cs b/src/ComputeSharp/Shaders/Dispatching/ShaderBytecodeLoader.cs deleted file mode 100644 index c9a60a5b..00000000 --- a/src/ComputeSharp/Shaders/Dispatching/ShaderBytecodeLoader.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Runtime.CompilerServices; -using ComputeSharp.__Internals; -using ComputeSharp.Shaders.Models; - -#pragma warning disable CS0618 - -namespace ComputeSharp.Shaders.Dispatching; - -/// -/// A bytecode loader for compute shaders. -/// -internal struct ShaderBytecodeLoader : IBytecodeLoader -{ - /// - /// The current cached shader instance. - /// - private ICachedShader? cachedShader; - - /// - /// Gets the current cached shader instance. - /// - /// The current instance. - /// Thrown if the HLSL bytecode is not available. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public readonly ICachedShader GetCachedShader() - { - default(NotSupportedException).ThrowIf(this.cachedShader is null); - - return this.cachedShader; - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void LoadEmbeddedBytecode(ReadOnlySpan bytecode) - { - default(InvalidOperationException).ThrowIf(this.cachedShader is not null); - - this.cachedShader = new ICachedShader.Embedded(bytecode); - } -} \ No newline at end of file diff --git a/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs b/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs index a3ce97a0..2262ca07 100644 --- a/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs +++ b/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs @@ -520,24 +520,6 @@ public static class ComputeContextExtensions context.Run(x, y, z, ref Unsafe.AsRef(in shader)); } - /// - /// Runs the input shader on a target instance, with the specified parameters. - /// - /// The type of compute shader to run. - /// The to use to run the shader. - /// The number of iterations to run on the X axis. - /// The number of iterations to run on the Y axis. - /// The number of iterations to run on the Z axis. - /// The number of threads in each thread group for the X axis. - /// The number of threads in each thread group for the Y axis. - /// The number of threads in each thread group for the Z axis. - /// The input instance representing the compute shader to run. - public static void For(this in ComputeContext context, int x, int y, int z, int threadsX, int threadsY, int threadsZ, in T shader) - where T : struct, IComputeShader - { - context.Run(x, y, z, threadsX, threadsY, threadsZ, ref Unsafe.AsRef(in shader)); - } - /// /// Runs the input shader on a target instance, with the specified parameters. /// diff --git a/src/ComputeSharp/Shaders/Models/PipelineData.cs b/src/ComputeSharp/Shaders/Loading/PipelineData.cs similarity index 98% rename from src/ComputeSharp/Shaders/Models/PipelineData.cs rename to src/ComputeSharp/Shaders/Loading/PipelineData.cs index 617fac35..4faf0429 100644 --- a/src/ComputeSharp/Shaders/Models/PipelineData.cs +++ b/src/ComputeSharp/Shaders/Loading/PipelineData.cs @@ -2,7 +2,7 @@ using ComputeSharp.Interop; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; -namespace ComputeSharp.Shaders.Models; +namespace ComputeSharp.Shaders.Loading; /// /// A representing a custom pipeline state for a compute operation. diff --git a/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs b/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs index cb618e53..59846b79 100644 --- a/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs +++ b/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs @@ -1,12 +1,10 @@ using System; -using System.Collections.Generic; using System.Runtime.CompilerServices; using ComputeSharp.Shaders.Dispatching; using ComputeSharp.Shaders.Extensions; using ComputeSharp.__Internals; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; -using ComputeSharp.Shaders.Models; #pragma warning disable CS0618 @@ -20,86 +18,56 @@ internal static class PipelineDataLoader where T : struct, IShader { /// - /// The mapping used to cache and reuse compiled shaders. + /// The map of cached instances for each GPU in use. /// - private static readonly Dictionary ShadersCache = new(); + private static readonly ConditionalWeakTable CachedPipelines = new(); /// /// Gets the instance for a given shader. /// /// The to use to run the shader. - /// The number of threads in each thread group for the X axis. - /// The number of threads in each thread group for the Y axis. - /// The number of threads in each thread group for the Z axis. - /// The input instance representing the compute shader to run. /// The instance for a given shader. - public static unsafe PipelineData GetPipelineData(GraphicsDevice device, int threadsX, int threadsY, int threadsZ, ref T shader) + public static PipelineData GetPipelineData(GraphicsDevice device) { - ShaderKey key = new(threadsX, threadsY, threadsZ); - - lock (ShadersCache) - { - // Get or preload the shader - if (!ShadersCache.TryGetValue(key, out ICachedShader? shaderData)) - { - LoadShader(threadsX, threadsY, threadsZ, ref shader, out shaderData); - - // Cache for later use - ShadersCache.Add(key, shaderData); - } - - // Create the reusable pipeline state - if (!shaderData.CachedPipelines.TryGetValue(device, out PipelineData? pipelineData)) - { - CreatePipelineData(device, shaderData, out pipelineData); - } - - return pipelineData; - } - } - - /// - /// Loads a shader with the specified parameters. - /// - /// The number of threads in each thread group for the X axis. - /// The number of threads in each thread group for the Y axis. - /// The number of threads in each thread group for the Z axis. - /// The input instance representing the compute shader to run. - /// The instance to return with the cached shader data. - [MethodImpl(MethodImplOptions.NoInlining)] - private static unsafe void LoadShader(int threadsX, int threadsY, int threadsZ, ref T shader, out ICachedShader shaderData) - { - ShaderBytecodeLoader bytecodeLoader = default; - - shader.LoadBytecode(ref bytecodeLoader, threadsX, threadsY, threadsZ); - - shaderData = bytecodeLoader.GetCachedShader(); + return CachedPipelines.GetValue(device, CreatePipelineData); } /// /// Creates and caches a instance for a given shader. /// /// The to use to run the shader. - /// The instance with the data on the loaded shader. - /// The resulting instance to use to run the shader. + /// The resulting instance to use to run the shader. [MethodImpl(MethodImplOptions.NoInlining)] - private static unsafe void CreatePipelineData(GraphicsDevice device, ICachedShader shaderData, out PipelineData pipelineData) + private static unsafe PipelineData CreatePipelineData(GraphicsDevice device) { - using ComPtr d3D12RootSignature = default; + PipelineData pipelineData; - ShaderDispatchMetadataLoader metadataLoader = new(device.D3D12Device); + using (ComPtr d3D12RootSignature = default) + { + ShaderDispatchMetadataLoader metadataLoader = new(device.D3D12Device); - Unsafe.SkipInit(out T shader); + Unsafe.SkipInit(out T shader); - shader.LoadDispatchMetadata(ref metadataLoader, out *(IntPtr*)&d3D12RootSignature); + shader.LoadDispatchMetadata(ref metadataLoader, out *(IntPtr*)&d3D12RootSignature); - using ComPtr d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), shaderData.D3D12ShaderBytecode); + ReadOnlyMemory hlslBytecode = shader.HlslBytecode; - pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get()); + fixed (byte* hlslBytecodePtr = hlslBytecode.Span) + { + D3D12_SHADER_BYTECODE d3D12ShaderBytecode = new(hlslBytecodePtr, (nuint)hlslBytecode.Length); - shaderData.CachedPipelines.Add(device, pipelineData); + using ComPtr d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), d3D12ShaderBytecode); + + pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get()); + } + } + + // Add the pipeline to the cache for this type + CachedPipelines.Add(device, pipelineData); // Register the newly created pipeline data to enable early disposal device.RegisterPipelineData(pipelineData); + + return pipelineData; } } \ No newline at end of file diff --git a/src/ComputeSharp/Shaders/Models/ICachedShader.cs b/src/ComputeSharp/Shaders/Models/ICachedShader.cs deleted file mode 100644 index 8a5d51a3..00000000 --- a/src/ComputeSharp/Shaders/Models/ICachedShader.cs +++ /dev/null @@ -1,96 +0,0 @@ -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using ComputeSharp.Interop; -using TerraFX.Interop.DirectX; -using TerraFX.Interop.Windows; - -namespace ComputeSharp.Shaders.Models; - -/// -/// An interface that contains info on a cached shader. -/// -internal interface ICachedShader -{ - /// - /// Gets the map of cached instances for each GPU in use. - /// - ConditionalWeakTable CachedPipelines { get; } - - /// - /// Gets a value pointing shader bytecode to use. - /// - D3D12_SHADER_BYTECODE D3D12ShaderBytecode { get; } - - /// - /// An implementation for an embedded shader. - /// - public sealed unsafe class Embedded : ICachedShader - { - /// - /// The bytecode buffer, if a precompiled shader is used. - /// - private readonly byte* precompiledBytecodeBuffer; - - /// - /// The buffer size for , if present. - /// - private readonly uint precompiledBytecodeSize; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The shader bytecode buffer to wrap. - /// - /// It is assumed that is a static binary block in the .text segment of the - /// PE file, which is what Roslyn generates when directly assigning a new array to a . As such, - /// the underlying buffer is assumed to be pinned, and it will not be properly tracked for GC compactions. If an invalid - /// buffer is passed and its contents are moved, the behavior is undefined (access violations will most definitely occurr). - /// - public Embedded(ReadOnlySpan precompiledBytecode) - { - this.precompiledBytecodeBuffer = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(precompiledBytecode)); - this.precompiledBytecodeSize = (uint)precompiledBytecode.Length; - } - - /// - public ConditionalWeakTable CachedPipelines { get; } = new(); - - /// - public D3D12_SHADER_BYTECODE D3D12ShaderBytecode => new(this.precompiledBytecodeBuffer, this.precompiledBytecodeSize); - } - - /// - /// An implementation for a dynamically compiled shader. - /// - public sealed unsafe class Dynamic : ReferenceTrackedObject, ICachedShader - { - /// - /// The instance currently in use. - /// - private ComPtr dxcBlobBytecode; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The bytecode instance to wrap. - public Dynamic(IDxcBlob* dxcBlobBytecode) - { - using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); - - this.dxcBlobBytecode = new ComPtr(dxcBlobBytecode); - } - - /// - public ConditionalWeakTable CachedPipelines { get; } = new(); - - /// - public D3D12_SHADER_BYTECODE D3D12ShaderBytecode => new((ID3DBlob*)this.dxcBlobBytecode.Get()); - - /// - protected override void DangerousOnDispose() - { - this.dxcBlobBytecode.Dispose(); - } - } -} \ No newline at end of file diff --git a/src/ComputeSharp/Shaders/Models/ShaderKey.cs b/src/ComputeSharp/Shaders/Models/ShaderKey.cs deleted file mode 100644 index 7b80aff3..00000000 --- a/src/ComputeSharp/Shaders/Models/ShaderKey.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Runtime.CompilerServices; - -namespace ComputeSharp.Shaders.Models; - -/// -/// A representing a key for a given shader. -/// -internal readonly struct ShaderKey : IEquatable -{ - /// - /// The number of iterations to run on the X axis. - /// - private readonly int threadsX; - - /// - /// The number of iterations to run on the Y axis. - /// - private readonly int threadsY; - - /// - /// The number of iterations to run on the Z axis. - /// - private readonly int threadsZ; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The number of iterations to run on the X axis. - /// The number of iterations to run on the Y axis. - /// The number of iterations to run on the Z axis. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ShaderKey(int threadsX, int threadsY, int threadsZ) - { - this.threadsX = threadsX; - this.threadsY = threadsY; - this.threadsZ = threadsZ; - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool Equals(ShaderKey other) - { - return - this.threadsX == other.threadsX && - this.threadsY == other.threadsY && - this.threadsZ == other.threadsZ; - } - - /// - public override bool Equals(object? obj) - { - return obj is ShaderKey other && Equals(other); - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override int GetHashCode() - { - return HashCode.Combine(this.threadsX, this.threadsY, this.threadsZ); - } -} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests.DisableDynamicCompilation/DispatchTests.cs b/tests/ComputeSharp.Tests.DisableDynamicCompilation/DispatchTests.cs index 7c8c903f..775d0256 100644 --- a/tests/ComputeSharp.Tests.DisableDynamicCompilation/DispatchTests.cs +++ b/tests/ComputeSharp.Tests.DisableDynamicCompilation/DispatchTests.cs @@ -18,7 +18,7 @@ public partial class DispatchTests using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(array); - device.Get().For(128, 1, 1, 32, 1, 1, new ComputeShader(buffer, 2.0f)); + device.Get().For(128, 1, 1, new ComputeShader(buffer, 2.0f)); float[] result = buffer.ToArray(); @@ -30,16 +30,6 @@ public partial class DispatchTests CollectionAssert.AreEqual(result, array); } - [CombinatorialTestMethod] - [AllDevices] - [ExpectedException(typeof(NotSupportedException))] - public void ComputeShader_Test_Fail(Device device) - { - using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(128); - - device.Get().For(128, 1, 1, 64, 1, 1, new ComputeShader(buffer, 2.0f)); - } - [AutoConstructor] [EmbeddedBytecode(32, 1, 1)] internal readonly partial struct ComputeShader : IComputeShader diff --git a/tests/ComputeSharp.Tests/DispatchTests.cs b/tests/ComputeSharp.Tests/DispatchTests.cs index e551fb06..1bd1c4e0 100644 --- a/tests/ComputeSharp.Tests/DispatchTests.cs +++ b/tests/ComputeSharp.Tests/DispatchTests.cs @@ -131,7 +131,7 @@ public partial class DispatchTests { using ReadWriteTexture3D buffer = device.Get().AllocateReadWriteTexture3D(50, 50, 50); - device.Get().For(buffer.Width, buffer.Height, buffer.Depth, 4, 4, 4, new GroupIdsShader(buffer)); + device.Get().For(buffer.Width, buffer.Height, buffer.Depth, new GroupIdsShader(buffer)); int4[,,] data = buffer.ToArray(); int* value = stackalloc int[4]; @@ -153,26 +153,6 @@ public partial class DispatchTests } } - [CombinatorialTestMethod] - [AllDevices] - [Data(0, 8, 8)] - [Data(8, 0, 8)] - [Data(8, 8, 0)] - [Data(1025, 8, 8)] - [Data(8, 2000, 8)] - [Data(8, 8, 70)] - [Data(8, -1, 8)] - [Data(8, 15, 16)] - [ExpectedException(typeof(ArgumentOutOfRangeException))] - public void Verify_GroupIds_OutOfRange(Device device, int x, int y, int z) - { - using ReadWriteTexture3D buffer = device.Get().AllocateReadWriteTexture3D(50, 50, 50); - - device.Get().For(buffer.Width, buffer.Height, buffer.Depth, x, y, z, new GroupIdsShader(buffer)); - - Assert.Fail(); - } - [AutoConstructor] [EmbeddedBytecode(DispatchAxis.XYZ)] internal readonly partial struct GroupIdsShader : IComputeShader @@ -192,7 +172,7 @@ public partial class DispatchTests { using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(32); - device.Get().For(1, 1, 1, 4, 15, 7, new GroupSizeShader(buffer)); + device.Get().For(1, 1, 1, new GroupSizeShader(buffer)); int[] data = buffer.ToArray(); @@ -227,7 +207,7 @@ public partial class DispatchTests { using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(256); - device.Get().For(256, 1, 1, 32, 1, 1, new GridIdsShader(buffer)); + device.Get().For(256, 1, 1, new GridIdsShader(buffer)); int[] data = buffer.ToArray(); @@ -373,7 +353,7 @@ public partial class DispatchTests { using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(32); - device.Get().For(64, 1, 1, 32, 1, 1, new DynamicGroupSharedPixelShader(buffer)); + device.Get().For(64, 1, 1, new DynamicGroupSharedPixelShader(buffer)); int[] result = buffer.ToArray(); diff --git a/tests/ComputeSharp.Tests/ThreadGroupSizeTests.cs b/tests/ComputeSharp.Tests/ThreadGroupSizeTests.cs new file mode 100644 index 00000000..ca32174b --- /dev/null +++ b/tests/ComputeSharp.Tests/ThreadGroupSizeTests.cs @@ -0,0 +1,77 @@ +using ComputeSharp.__Internals; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests; + +[TestClass] +[TestCategory("ThreadGroupSize")] +public partial class ThreadGroupSizeTests +{ + [TestMethod] + public unsafe void Verify_ThreadGroupSize() + { + Assert.AreEqual(64, ((IShader)default(DispatchXShader)).ThreadsX); + Assert.AreEqual(1, ((IShader)default(DispatchXShader)).ThreadsY); + Assert.AreEqual(1, ((IShader)default(DispatchXShader)).ThreadsZ); + + Assert.AreEqual(8, ((IShader)default(DispatchXYShader)).ThreadsX); + Assert.AreEqual(8, ((IShader)default(DispatchXYShader)).ThreadsY); + Assert.AreEqual(1, ((IShader)default(DispatchXYShader)).ThreadsZ); + + Assert.AreEqual(4, ((IShader)default(DispatchXYZShader)).ThreadsX); + Assert.AreEqual(4, ((IShader)default(DispatchXYZShader)).ThreadsY); + Assert.AreEqual(4, ((IShader)default(DispatchXYZShader)).ThreadsZ); + + Assert.AreEqual(11, ((IShader)default(DispatchCustomShader)).ThreadsX); + Assert.AreEqual(14, ((IShader)default(DispatchCustomShader)).ThreadsY); + Assert.AreEqual(6, ((IShader)default(DispatchCustomShader)).ThreadsZ); + } + + [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.X)] + internal readonly partial struct DispatchXShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + + public void Execute() + { + this.buffer[ThreadIds.X] = 0; + } + } + + [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XY)] + internal readonly partial struct DispatchXYShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + + public void Execute() + { + this.buffer[ThreadIds.X] = 0; + } + } + + [AutoConstructor] + [EmbeddedBytecode(DispatchAxis.XYZ)] + internal readonly partial struct DispatchXYZShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + + public void Execute() + { + this.buffer[ThreadIds.X] = 0; + } + } + + [AutoConstructor] + [EmbeddedBytecode(11, 14, 6)] + internal readonly partial struct DispatchCustomShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + + public void Execute() + { + this.buffer[ThreadIds.X] = 0; + } + } +} \ No newline at end of file