diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource.cs index 6e266844..79407efe 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource.cs @@ -1,89 +1,85 @@ -using System; +using ComputeSharp.Core.Interop; +using ComputeSharp.Graphics.Extensions; +using System; using System.Runtime.CompilerServices; -using Vortice.Direct3D12; +using TerraFX.Interop; namespace ComputeSharp.Graphics.Buffers.Abstract { /// - /// An abstract that represents a graphics resource object + /// An abstract that represents a graphics resource object. /// - public abstract class GraphicsResource : IDisposable + public abstract unsafe class GraphicsResource : NativeObject { /// - /// Creates a new instance with the specified parameters + /// The instance currently mapped. /// - /// The associated with the current instance - protected GraphicsResource(GraphicsDevice device) + protected internal readonly ID3D12Resource* D3D12Resource; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The associated with the current instance. + protected GraphicsResource(GraphicsDevice device, ID3D12Resource* d3d12resource) { + D3D12Resource = d3d12resource; + GraphicsDevice = device; } /// - /// Gets the associated with the current instance + /// Gets the associated with the current instance. /// public GraphicsDevice GraphicsDevice { get; } /// - /// Gets the object currently mapped + /// Maps the current resource to a specified subresource. /// - protected internal ID3D12Resource? NativeResource { get; set; } - - /// - /// Gets the instance for the current resource - /// - protected internal CpuDescriptorHandle? NativeCpuDescriptorHandle { get; protected set; } - - /// - /// Gets the instance for the current resource - /// - protected internal GpuDescriptorHandle? NativeGpuDescriptorHandle { get; protected set; } - - /// - /// Maps the current resource to a specified subresource - /// - /// A instance representing the mapped resource + /// A instance representing the mapped resource. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal MappedResource MapResource() { - var resource = NativeResource ?? throw new InvalidOperationException("Missing resource"); - - return new MappedResource(resource); + return new MappedResource(D3D12Resource); } /// - public virtual void Dispose() => NativeResource?.Dispose(); + protected override void OnDispose() + { + D3D12Resource->Release(); + } /// - /// A type representing a mapped memory resource + /// A type representing a mapped memory resource. /// internal readonly ref struct MappedResource { /// - /// The target to map + /// The target to map. /// - private readonly ID3D12Resource Resource; + private readonly ID3D12Resource* d3D12Resource; /// - /// The pointer to the mapped resource + /// The pointer to the mapped resource. /// public readonly IntPtr Pointer; /// - /// Creates a new instance for a given value + /// Creates a new instance for a given value. /// - /// The input instance to map + /// The input instance to map. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public MappedResource(ID3D12Resource resource) + public MappedResource(ID3D12Resource* d3d12resource) { - Resource = resource; - Pointer = resource.Map(0); + d3D12Resource = d3d12resource; + + Pointer = d3d12resource->Map(); } /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { - Resource.Unmap(0); + d3D12Resource->Unmap(); } } } diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource2.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource2.cs deleted file mode 100644 index 78514237..00000000 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/GraphicsResource2.cs +++ /dev/null @@ -1,86 +0,0 @@ -using ComputeSharp.Core.Interop; -using ComputeSharp.Graphics.Extensions; -using System; -using System.Runtime.CompilerServices; -using TerraFX.Interop; - -namespace ComputeSharp.Graphics.Buffers.Abstract -{ - /// - /// An abstract that represents a graphics resource object. - /// - public abstract unsafe class GraphicsResource2 : NativeObject - { - /// - /// The instance currently mapped. - /// - protected internal readonly ID3D12Resource* D3D12Resource; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The associated with the current instance. - protected GraphicsResource2(GraphicsDevice2 device, ID3D12Resource* d3d12resource) - { - D3D12Resource = d3d12resource; - - GraphicsDevice = device; - } - - /// - /// Gets the associated with the current instance. - /// - public GraphicsDevice2 GraphicsDevice { get; } - - /// - /// Maps the current resource to a specified subresource. - /// - /// A instance representing the mapped resource. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal MappedResource MapResource() - { - return new MappedResource(D3D12Resource); - } - - /// - protected override void OnDispose() - { - D3D12Resource->Release(); - } - - /// - /// A type representing a mapped memory resource. - /// - internal readonly ref struct MappedResource - { - /// - /// The target to map. - /// - private readonly ID3D12Resource* d3D12Resource; - - /// - /// The pointer to the mapped resource. - /// - public readonly IntPtr Pointer; - - /// - /// Creates a new instance for a given value. - /// - /// The input instance to map. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public MappedResource(ID3D12Resource* d3d12resource) - { - d3D12Resource = d3d12resource; - - Pointer = d3d12resource->Map(); - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Dispose() - { - d3D12Resource->Unmap(); - } - } - } -} diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer2{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer2{T}.cs deleted file mode 100644 index 298d19a8..00000000 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer2{T}.cs +++ /dev/null @@ -1,115 +0,0 @@ -using System; -using System.Buffers; -using System.Diagnostics.Contracts; -using ComputeSharp.Graphics.Buffers.Enums; - -namespace ComputeSharp.Graphics.Buffers.Abstract -{ - /// - /// A representing a typed buffer stored on GPU memory, that can be used from an HLSL shader - /// - /// The type of items stored on the buffer - public abstract class HlslBuffer2 : Buffer2 where T : unmanaged - { - /// - /// Creates a new instance with the specified parameters - /// - /// The associated with the current instance - /// The number of items to store in the current buffer - /// The size in bytes for the current buffer - /// The buffer type for the current buffer - private protected HlslBuffer2(GraphicsDevice2 device, int size, int sizeInBytes, BufferType bufferType) - : base(device, size, sizeInBytes, bufferType) - { - } - - /// - /// Reads the contents of the current instance and returns an array - /// - /// A array with the contents of the current buffer - [Pure] - public T[] GetData() => GetData(0, Size); - - /// - /// Reads the contents of the current instance in a given range and returns an array - /// - /// The offset to start reading data from - /// The number of items to read - /// A array with the contents of the specified range from the current buffer - [Pure] - public T[] GetData(int offset, int count) - { - T[] data = new T[count]; - GetData(data, offset, count); - - return data; - } - - /// - /// Reads the contents of the current instance and writes them into a target - /// - /// The input to write data to - public void GetData(Span span) => GetData(span, 0, Size); - - /// - /// Reads the contents of the specified range from the current instance and writes them into a target - /// - /// The input to write data to - /// The offset to start reading data from - /// The number of items to read - public abstract void GetData(Span span, int offset, int count); - - /// - /// Writes the contents of a given array to the current instance - /// - /// The input array to read data from - public void SetData(T[] array) => SetData(array.AsSpan()); - - /// - /// Writes the contents of a given array to a specified area of the current instance - /// - /// The input array to read data from - /// The offset to start writing data to - /// The number of items to write - public void SetData(T[] array, int offset, int count) => SetData(array.AsSpan(), offset, count); - - /// - /// Writes the contents of a given to the current instance - /// - /// The input to read data from - public void SetData(ReadOnlySpan span) => SetData(span, 0, Size); - - /// - /// Writes the contents of a given to a specified area of the current instance - /// - /// The input to read data from - /// The offset to start writing data to - /// The number of items to write - public abstract void SetData(ReadOnlySpan span, int offset, int count); - - /// - /// Writes the contents of a given to the current instance - /// - /// The input to read data from - public abstract void SetData(HlslBuffer2 buffer); - - /// - /// Writes the contents of a given to the current instance, using a temporary CPU buffer - /// - /// The input to read data from - protected void SetDataWithCpuBuffer(HlslBuffer2 buffer) - { - // Create a temporary array - T[] array = ArrayPool.Shared.Rent(buffer.Size); - Span span = array.AsSpan(0, buffer.Size); - - // Get the unpadded data from the read write buffer - buffer.GetData(span); - - // Set the data, adding the padding if needed - SetData(span); - - ArrayPool.Shared.Return(array); - } - } -} diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs index 4b938cca..1751bb9b 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslBuffer{T}.cs @@ -18,7 +18,10 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// The number of items to store in the current buffer /// The size in bytes for the current buffer /// The buffer type for the current buffer - private protected HlslBuffer(GraphicsDevice device, int size, int sizeInBytes, BufferType bufferType) : base(device, size, sizeInBytes, bufferType) { } + private protected HlslBuffer(GraphicsDevice device, int size, int sizeInBytes, BufferType bufferType) + : base(device, size, sizeInBytes, bufferType) + { + } /// /// Reads the contents of the current instance and returns an array diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer2{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer2{T}.cs deleted file mode 100644 index 0333b579..00000000 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer2{T}.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Runtime.CompilerServices; -using ComputeSharp.Graphics.Buffers.Enums; -using ComputeSharp.Graphics.Commands; -using ComputeSharp.Graphics.Helpers; -using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; - -namespace ComputeSharp.Graphics.Buffers.Abstract -{ - /// - /// A representing a typed structured buffer stored on GPU memory - /// - /// The type of items stored on the buffer - public abstract class HlslStructuredBuffer2 : HlslBuffer2 - where T : unmanaged - { - /// - /// Creates a new instance with the specified parameters - /// - /// The associated with the current instance - /// The number of items to store in the current buffer - /// The buffer type for the current buffer - internal HlslStructuredBuffer2(GraphicsDevice2 device, int size, BufferType bufferType) - : base(device, size, size * Unsafe.SizeOf(), bufferType) - { - } - - /// - public override unsafe void GetData(Span span, int offset, int count) - { - using Buffer2 transferBuffer = new Buffer2(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.ReadBack); - - using (CommandList2 copyCommandList = new CommandList2(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY)) - { - copyCommandList.CopyBufferRegion(D3D12Resource, offset * ElementSizeInBytes, transferBuffer.D3D12Resource, 0, count * ElementSizeInBytes); - copyCommandList.ExecuteAndWaitForCompletion(); - } - - using MappedResource resource = transferBuffer.MapResource(); - - MemoryHelper.Copy(resource.Pointer, 0, span, 0, count); - } - - /// - public override unsafe void SetData(ReadOnlySpan span, int offset, int count) - { - using Buffer2 transferBuffer = new Buffer2(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.Transfer); - - using (MappedResource resource = transferBuffer.MapResource()) - { - MemoryHelper.Copy(span, resource.Pointer, 0, count); - } - - using CommandList2 copyCommandList = new CommandList2(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); - - copyCommandList.CopyBufferRegion(transferBuffer.D3D12Resource, 0, D3D12Resource, offset * ElementSizeInBytes, count * ElementSizeInBytes); - copyCommandList.ExecuteAndWaitForCompletion(); - } - - /// - public override unsafe void SetData(HlslBuffer2 buffer) - { - if (!buffer.IsPaddingPresent) - { - // Directly copy the input buffer - using CommandList2 copyCommandList = new CommandList2(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); - - copyCommandList.CopyBufferRegion(buffer.D3D12Resource, 0, D3D12Resource, 0, SizeInBytes); - copyCommandList.ExecuteAndWaitForCompletion(); - } - else SetDataWithCpuBuffer(buffer); - } - } -} diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs index 1a60a5f1..b15fbaaa 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/HlslStructuredBuffer{T}.cs @@ -1,9 +1,9 @@ using System; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Enums; +using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Helpers; -using Vortice.Direct3D12; -using CommandList = ComputeSharp.Graphics.Commands.CommandList; +using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; namespace ComputeSharp.Graphics.Buffers.Abstract { @@ -20,16 +20,19 @@ namespace ComputeSharp.Graphics.Buffers.Abstract /// The associated with the current instance /// The number of items to store in the current buffer /// The buffer type for the current buffer - internal HlslStructuredBuffer(GraphicsDevice device, int size, BufferType bufferType) : base(device, size, size * Unsafe.SizeOf(), bufferType) { } + internal HlslStructuredBuffer(GraphicsDevice device, int size, BufferType bufferType) + : base(device, size, size * Unsafe.SizeOf(), bufferType) + { + } /// - public override void GetData(Span span, int offset, int count) + public override unsafe void GetData(Span span, int offset, int count) { using Buffer transferBuffer = new Buffer(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.ReadBack); - using (CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy)) + using (CommandList copyCommandList = new CommandList(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY)) { - copyCommandList.CopyBufferRegion(this, offset * ElementSizeInBytes, transferBuffer, 0, count * ElementSizeInBytes); + copyCommandList.CopyBufferRegion(D3D12Resource, offset * ElementSizeInBytes, transferBuffer.D3D12Resource, 0, count * ElementSizeInBytes); copyCommandList.ExecuteAndWaitForCompletion(); } @@ -39,7 +42,7 @@ namespace ComputeSharp.Graphics.Buffers.Abstract } /// - public override void SetData(ReadOnlySpan span, int offset, int count) + public override unsafe void SetData(ReadOnlySpan span, int offset, int count) { using Buffer transferBuffer = new Buffer(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.Transfer); @@ -48,21 +51,21 @@ namespace ComputeSharp.Graphics.Buffers.Abstract MemoryHelper.Copy(span, resource.Pointer, 0, count); } - using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + using CommandList copyCommandList = new CommandList(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); - copyCommandList.CopyBufferRegion(transferBuffer, 0, this, offset * ElementSizeInBytes, count * ElementSizeInBytes); + copyCommandList.CopyBufferRegion(transferBuffer.D3D12Resource, 0, D3D12Resource, offset * ElementSizeInBytes, count * ElementSizeInBytes); copyCommandList.ExecuteAndWaitForCompletion(); } /// - public override void SetData(HlslBuffer buffer) + public override unsafe void SetData(HlslBuffer buffer) { if (!buffer.IsPaddingPresent) { // Directly copy the input buffer - using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + using CommandList copyCommandList = new CommandList(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); - copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); + copyCommandList.CopyBufferRegion(buffer.D3D12Resource, 0, D3D12Resource, 0, SizeInBytes); copyCommandList.ExecuteAndWaitForCompletion(); } else SetDataWithCpuBuffer(buffer); diff --git a/src/ComputeSharp.Graphics/Buffers/Buffer2{T}.cs b/src/ComputeSharp.Graphics/Buffers/Buffer2{T}.cs deleted file mode 100644 index 076f8b75..00000000 --- a/src/ComputeSharp.Graphics/Buffers/Buffer2{T}.cs +++ /dev/null @@ -1,156 +0,0 @@ -using System.Runtime.CompilerServices; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Buffers.Enums; -using ComputeSharp.Graphics.Extensions; -using TerraFX.Interop; -using static TerraFX.Interop.D3D12_HEAP_TYPE; -using static TerraFX.Interop.D3D12_RESOURCE_FLAGS; -using static TerraFX.Interop.D3D12_RESOURCE_STATES; -using static TerraFX.Interop.D3D12_SRV_DIMENSION; -using static TerraFX.Interop.D3D12_UAV_DIMENSION; -using FX = TerraFX.Interop.Windows; - -namespace ComputeSharp.Graphics.Buffers -{ - /// - /// A representing a typed buffer stored on GPU memory. - /// - /// The type of items stored on the buffer. - public unsafe class Buffer2 : GraphicsResource2 - where T : unmanaged - { - /// - /// The instance for the current resource. - /// - protected internal readonly D3D12_CPU_DESCRIPTOR_HANDLE D3D12CpuDescriptorHandle; - - /// - /// The instance for the current resource. - /// - protected internal readonly D3D12_GPU_DESCRIPTOR_HANDLE D3D12GpuDescriptorHandle; - - /// - /// The size in bytes of the current buffer. - /// - protected readonly int SizeInBytes; - - /// - /// The size in bytes of each value contained in the buffer. - /// - protected readonly int ElementSizeInBytes; - - /// - /// The size in bytes of the current buffer. - /// - internal readonly int PaddedElementSizeInBytes; - - /// - /// The buffer type for the current instance. - /// - internal readonly BufferType BufferType; - - /// - /// Creates a new instance with the specified parameters - /// - /// The associated with the current instance - /// The number of items to store in the current buffer - /// The size in bytes for the current buffer - /// The buffer type for the current buffer - internal Buffer2(GraphicsDevice2 device, int size, int sizeInBytes, BufferType bufferType) - : base(device, CreateCommittedResource(device.D3D12Device, bufferType, sizeInBytes)) - { - Size = size; - SizeInBytes = sizeInBytes; - ElementSizeInBytes = Unsafe.SizeOf(); - BufferType = bufferType; - PaddedElementSizeInBytes = sizeInBytes / size; - - if (bufferType is BufferType.Constant or BufferType.ReadOnly or BufferType.ReadWrite) - { - GraphicsDevice.AllocateShaderResourceViewDescriptorHandles(out D3D12CpuDescriptorHandle, out D3D12GpuDescriptorHandle); - - switch (bufferType) - { - case BufferType.Constant: CreateConstantBufferView(); break; - case BufferType.ReadOnly: CreateShaderResourceView(); break; - case BufferType.ReadWrite: CreateUnorderedAccessView(); break; - } - } - } - - /// - /// Gets the size of the current buffer, as in the number of values it contains - /// - public int Size { get; } - - /// - /// Gets whether or not there is some padding between elements in the current buffer - /// - internal bool IsPaddingPresent => PaddedElementSizeInBytes > ElementSizeInBytes; - - /// - /// Creates a committed resource for a given buffer type. - /// - /// The instance in use. - /// The buffer type currently in use. - /// The size in bytes of the current buffer. - /// An reference for the current buffer. - private static ID3D12Resource* CreateCommittedResource(ID3D12Device* d3D12Device, BufferType bufferType, int sizeInBytes) - { - (D3D12_HEAP_TYPE d3D12HeapType, - D3D12_RESOURCE_FLAGS d3D12ResourceFlags, - D3D12_RESOURCE_STATES d3D12ResourceStates) = bufferType switch - { - BufferType.Constant => (D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ), - BufferType.ReadOnly => (D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COMMON), - BufferType.ReadWrite => (D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON), - BufferType.ReadBack => (D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST), - BufferType.Transfer => (D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ), - _ => throw null! - }; - - return d3D12Device->CreateCommittedResource(d3D12HeapType, (uint)sizeInBytes, d3D12ResourceFlags, d3D12ResourceStates); - } - - /// - /// Creates a view for a constant buffer. - /// - private void CreateConstantBufferView() - { - uint constantBufferSize = (uint)((SizeInBytes + 255) & ~255); - - D3D12_CONSTANT_BUFFER_VIEW_DESC d3D12ConstantBufferViewDescription; - d3D12ConstantBufferViewDescription.BufferLocation = D3D12Resource->GetGPUVirtualAddress(); - d3D12ConstantBufferViewDescription.SizeInBytes = constantBufferSize; - - GraphicsDevice.D3D12Device->CreateConstantBufferView(&d3D12ConstantBufferViewDescription, D3D12CpuDescriptorHandle); - } - - /// - /// Creates a view for a readonly buffer. - /// - private void CreateShaderResourceView() - { - D3D12_SHADER_RESOURCE_VIEW_DESC d3D12ShaderResourceViewDescription = default; - d3D12ShaderResourceViewDescription.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; - d3D12ShaderResourceViewDescription.Shader4ComponentMapping = FX.D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - d3D12ShaderResourceViewDescription.Buffer.NumElements = (uint)Size; - d3D12ShaderResourceViewDescription.Buffer.StructureByteStride = (uint)ElementSizeInBytes; - - GraphicsDevice.D3D12Device->CreateShaderResourceView(D3D12Resource, &d3D12ShaderResourceViewDescription, D3D12CpuDescriptorHandle); - } - - /// - /// Creates a view for a buffer than be both read and written to. - /// - private void CreateUnorderedAccessView() - { - D3D12_UNORDERED_ACCESS_VIEW_DESC d3D12UnorderedAccessViewDescription = default; - d3D12UnorderedAccessViewDescription.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; - d3D12UnorderedAccessViewDescription.Buffer.NumElements = (uint)Size; - d3D12UnorderedAccessViewDescription.Buffer.StructureByteStride = (uint)ElementSizeInBytes; - - GraphicsDevice.D3D12Device->CreateUnorderedAccessView(D3D12Resource, null, &d3D12UnorderedAccessViewDescription, D3D12CpuDescriptorHandle); - } - } -} diff --git a/src/ComputeSharp.Graphics/Buffers/Buffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Buffer{T}.cs index 1d8f881c..e640ebdf 100644 --- a/src/ComputeSharp.Graphics/Buffers/Buffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Buffer{T}.cs @@ -1,20 +1,54 @@ -using System; -using System.Diagnostics.Contracts; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Abstract; using ComputeSharp.Graphics.Buffers.Enums; -using SharpGen.Runtime; -using Vortice.Direct3D12; +using ComputeSharp.Graphics.Extensions; +using TerraFX.Interop; +using static TerraFX.Interop.D3D12_HEAP_TYPE; +using static TerraFX.Interop.D3D12_RESOURCE_FLAGS; +using static TerraFX.Interop.D3D12_RESOURCE_STATES; +using static TerraFX.Interop.D3D12_SRV_DIMENSION; +using static TerraFX.Interop.D3D12_UAV_DIMENSION; +using FX = TerraFX.Interop.Windows; namespace ComputeSharp.Graphics.Buffers { /// - /// A representing a typed buffer stored on GPU memory + /// A representing a typed buffer stored on GPU memory. /// - /// The type of items stored on the buffer - public class Buffer : GraphicsResource where T : unmanaged + /// The type of items stored on the buffer. + public unsafe class Buffer : GraphicsResource + where T : unmanaged { + /// + /// The instance for the current resource. + /// + protected internal readonly D3D12_CPU_DESCRIPTOR_HANDLE D3D12CpuDescriptorHandle; + + /// + /// The instance for the current resource. + /// + protected internal readonly D3D12_GPU_DESCRIPTOR_HANDLE D3D12GpuDescriptorHandle; + + /// + /// The size in bytes of the current buffer. + /// + protected readonly int SizeInBytes; + + /// + /// The size in bytes of each value contained in the buffer. + /// + protected readonly int ElementSizeInBytes; + + /// + /// The size in bytes of the current buffer. + /// + internal readonly int PaddedElementSizeInBytes; + + /// + /// The buffer type for the current instance. + /// + internal readonly BufferType BufferType; + /// /// Creates a new instance with the specified parameters /// @@ -22,44 +56,26 @@ namespace ComputeSharp.Graphics.Buffers /// The number of items to store in the current buffer /// The size in bytes for the current buffer /// The buffer type for the current buffer - internal Buffer(GraphicsDevice device, int size, int sizeInBytes, BufferType bufferType) : base(device) + internal Buffer(GraphicsDevice device, int size, int sizeInBytes, BufferType bufferType) + : base(device, CreateCommittedResource(device.D3D12Device, bufferType, sizeInBytes)) { Size = size; - SizeInBytes = sizeInBytes; // Not necessarily a multiple of the element size, as there could be padding + SizeInBytes = sizeInBytes; ElementSizeInBytes = Unsafe.SizeOf(); BufferType = bufferType; PaddedElementSizeInBytes = sizeInBytes / size; - // Determine the right heap type and flags - (HeapType heapType, ResourceFlags flags, ResourceStates states) = bufferType switch + if (bufferType is BufferType.Constant or BufferType.ReadOnly or BufferType.ReadWrite) { - BufferType.Constant => (HeapType.Upload, ResourceFlags.None, ResourceStates.GenericRead), - BufferType.ReadOnly => (HeapType.Default, ResourceFlags.None, ResourceStates.Common), - BufferType.ReadWrite => (HeapType.Default, ResourceFlags.AllowUnorderedAccess, ResourceStates.Common), - BufferType.ReadBack => (HeapType.Readback, ResourceFlags.None, ResourceStates.CopyDestination), - BufferType.Transfer => (HeapType.Upload, ResourceFlags.None, ResourceStates.GenericRead), - _ => throw new ArgumentException($"Invalid buffer type {bufferType}", nameof(bufferType)) - }; + GraphicsDevice.AllocateShaderResourceViewDescriptorHandles(out D3D12CpuDescriptorHandle, out D3D12GpuDescriptorHandle); - // Create the native resource - ResourceDescription description = ResourceDescription.Buffer(sizeInBytes, flags); - Result result = GraphicsDevice.NativeDevice.CreateCommittedResource(new HeapProperties(heapType), HeapFlags.None, description, states, out ID3D12Resource? resource); - - if (result.Failure) - { - throw new COMException("Failed to create the committed resource", result.Code); + switch (bufferType) + { + case BufferType.Constant: CreateConstantBufferView(); break; + case BufferType.ReadOnly: CreateShaderResourceView(); break; + case BufferType.ReadWrite: CreateUnorderedAccessView(); break; + } } - - NativeResource = resource!; - - // Create the resource handles, if needed - (NativeCpuDescriptorHandle, NativeGpuDescriptorHandle) = bufferType switch - { - BufferType.Constant => CreateConstantBufferView(), - BufferType.ReadOnly => CreateShaderResourceView(), - BufferType.ReadWrite => CreateUnorderedAccessView(), - _ => default - }; } /// @@ -67,87 +83,74 @@ namespace ComputeSharp.Graphics.Buffers /// public int Size { get; } - /// - /// Gets the size in bytes of the current buffer - /// - protected int SizeInBytes { get; } - - /// - /// Gets the size in bytes of each value contained in the buffer - /// - protected int ElementSizeInBytes { get; } - - /// - /// Gets the size in bytes of the current buffer - /// - internal int PaddedElementSizeInBytes { get; } - /// /// Gets whether or not there is some padding between elements in the current buffer /// internal bool IsPaddingPresent => PaddedElementSizeInBytes > ElementSizeInBytes; /// - /// Gets the buffer type for the current instance + /// Creates a committed resource for a given buffer type. /// - internal BufferType BufferType { get; } - - /// - /// Creates the descriptors for a constant buffer - /// - /// The CPU and GPU handles for a constant buffer - [Pure] - private (CpuDescriptorHandle, GpuDescriptorHandle) CreateConstantBufferView() + /// The instance in use. + /// The buffer type currently in use. + /// The size in bytes of the current buffer. + /// An reference for the current buffer. + private static ID3D12Resource* CreateCommittedResource(ID3D12Device* d3D12Device, BufferType bufferType, int sizeInBytes) { - (CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(); - - int constantBufferSize = (SizeInBytes + 255) & ~255; - - ConstantBufferViewDescription description = new ConstantBufferViewDescription + (D3D12_HEAP_TYPE d3D12HeapType, + D3D12_RESOURCE_FLAGS d3D12ResourceFlags, + D3D12_RESOURCE_STATES d3D12ResourceStates) = bufferType switch { - BufferLocation = NativeResource!.GPUVirtualAddress, - SizeInBytes = constantBufferSize + BufferType.Constant => (D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ), + BufferType.ReadOnly => (D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COMMON), + BufferType.ReadWrite => (D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON), + BufferType.ReadBack => (D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST), + BufferType.Transfer => (D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ), + _ => throw null! }; - GraphicsDevice.NativeDevice.CreateConstantBufferView(description, cpuHandle); - - return (cpuHandle, gpuHandle); - } - - private (CpuDescriptorHandle, GpuDescriptorHandle) CreateShaderResourceView() - { - (CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(); - - ShaderResourceViewDescription description = new ShaderResourceViewDescription - { - Shader4ComponentMapping = 5768, - ViewDimension = ShaderResourceViewDimension.Buffer, - Buffer = { NumElements = Size, StructureByteStride = ElementSizeInBytes } - }; - - GraphicsDevice.NativeDevice.CreateShaderResourceView(NativeResource, description, cpuHandle); - - return (cpuHandle, gpuHandle); + return d3D12Device->CreateCommittedResource(d3D12HeapType, (uint)sizeInBytes, d3D12ResourceFlags, d3D12ResourceStates); } /// - /// Creates the descriptors for a read write buffer + /// Creates a view for a constant buffer. /// - /// The CPU and GPU handles for a read write buffer - [Pure] - private (CpuDescriptorHandle, GpuDescriptorHandle) CreateUnorderedAccessView() + private void CreateConstantBufferView() { - (CpuDescriptorHandle cpuHandle, GpuDescriptorHandle gpuHandle) = GraphicsDevice.ShaderResourceViewAllocator.Allocate(); + uint constantBufferSize = (uint)((SizeInBytes + 255) & ~255); - UnorderedAccessViewDescription description = new UnorderedAccessViewDescription - { - ViewDimension = UnorderedAccessViewDimension.Buffer, - Buffer = { NumElements = Size, StructureByteStride = ElementSizeInBytes } - }; + D3D12_CONSTANT_BUFFER_VIEW_DESC d3D12ConstantBufferViewDescription; + d3D12ConstantBufferViewDescription.BufferLocation = D3D12Resource->GetGPUVirtualAddress(); + d3D12ConstantBufferViewDescription.SizeInBytes = constantBufferSize; - GraphicsDevice.NativeDevice.CreateUnorderedAccessView(NativeResource, null, description, cpuHandle); + GraphicsDevice.D3D12Device->CreateConstantBufferView(&d3D12ConstantBufferViewDescription, D3D12CpuDescriptorHandle); + } + + /// + /// Creates a view for a readonly buffer. + /// + private void CreateShaderResourceView() + { + D3D12_SHADER_RESOURCE_VIEW_DESC d3D12ShaderResourceViewDescription = default; + d3D12ShaderResourceViewDescription.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + d3D12ShaderResourceViewDescription.Shader4ComponentMapping = FX.D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + d3D12ShaderResourceViewDescription.Buffer.NumElements = (uint)Size; + d3D12ShaderResourceViewDescription.Buffer.StructureByteStride = (uint)ElementSizeInBytes; - return (cpuHandle, gpuHandle); + GraphicsDevice.D3D12Device->CreateShaderResourceView(D3D12Resource, &d3D12ShaderResourceViewDescription, D3D12CpuDescriptorHandle); + } + + /// + /// Creates a view for a buffer than be both read and written to. + /// + private void CreateUnorderedAccessView() + { + D3D12_UNORDERED_ACCESS_VIEW_DESC d3D12UnorderedAccessViewDescription = default; + d3D12UnorderedAccessViewDescription.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + d3D12UnorderedAccessViewDescription.Buffer.NumElements = (uint)Size; + d3D12UnorderedAccessViewDescription.Buffer.StructureByteStride = (uint)ElementSizeInBytes; + + GraphicsDevice.D3D12Device->CreateUnorderedAccessView(D3D12Resource, null, &d3D12UnorderedAccessViewDescription, D3D12CpuDescriptorHandle); } } } diff --git a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer2{T}.cs b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer2{T}.cs deleted file mode 100644 index b2bda877..00000000 --- a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer2{T}.cs +++ /dev/null @@ -1,111 +0,0 @@ -using System; -using System.Diagnostics.Contracts; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using ComputeSharp.Exceptions; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Buffers.Enums; -using ComputeSharp.Graphics.Commands; -using ComputeSharp.Graphics.Helpers; -using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; - -namespace ComputeSharp -{ - /// - /// A representing a typed read write buffer stored on GPU memory - /// - /// The type of items stored on the buffer - public sealed class ConstantBuffer2 : HlslBuffer2 - where T : unmanaged - { - /// - /// Creates a new instance with the specified parameters - /// - /// The associated with the current instance - /// The number of items to store in the current buffer - internal ConstantBuffer2(GraphicsDevice2 device, int size) - : base(device, size, size * GetPaddedSize(), BufferType.Constant) - { - } - - /// - /// Gets the right padded size for elements to store in the current instance - /// - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static int GetPaddedSize() - { - int size = Unsafe.SizeOf(); - - return (size + 15) & ~15; - } - - /// - /// Gets a single value from the current constant buffer - /// - /// The index of the value to get - /// This API can only be used from a compute shader, and will always throw if used anywhere else - public T this[int i] => throw new InvalidExecutionContextException($"{nameof(ConstantBuffer)}[int]"); - - /// - public override unsafe void GetData(Span span, int offset, int count) - { - using MappedResource resource = MapResource(); - - if (IsPaddingPresent) - { - ref T spanRef = ref MemoryMarshal.GetReference(span); - ref byte resourceRef = ref Unsafe.AsRef((void*)resource.Pointer); - - // Move to the initial ref - resourceRef = ref Unsafe.Add(ref resourceRef, offset * GetPaddedSize()); - - for (var i = 0; i < count; i++) - { - ref byte targetRef = ref Unsafe.Add(ref resourceRef, i * GetPaddedSize()); - - Unsafe.Add(ref spanRef, i) = Unsafe.As(ref targetRef); - } - } - else MemoryHelper.Copy(resource.Pointer, offset, span, 0, count); - } - - /// - public override unsafe void SetData(ReadOnlySpan span, int offset, int count) - { - using MappedResource resource = MapResource(); - - if (IsPaddingPresent) - { - ref T spanRef = ref MemoryMarshal.GetReference(span); - ref byte resourceRef = ref Unsafe.AsRef((void*)resource.Pointer); - - // Move to the initial offset - resourceRef = ref Unsafe.Add(ref resourceRef, offset * GetPaddedSize()); - - for (var i = 0; i < count; i++) - { - ref byte targetRef = ref Unsafe.Add(ref resourceRef, i * GetPaddedSize()); - - Unsafe.As(ref targetRef) = Unsafe.Add(ref spanRef, i); - } - } - else MemoryHelper.Copy(span, resource.Pointer, offset, count); - } - - /// - public override unsafe void SetData(HlslBuffer2 buffer) - { - if (buffer is ConstantBuffer2) - { - // Directly copy the input buffer, if possible - using CommandList2 copyCommandList = new CommandList2(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); - - copyCommandList.CopyBufferRegion(buffer.D3D12Resource, 0, D3D12Resource, 0, SizeInBytes); - copyCommandList.ExecuteAndWaitForCompletion(); - } - else SetDataWithCpuBuffer(buffer); - } - } -} diff --git a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs index 57fe2430..415af033 100644 --- a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs @@ -6,9 +6,9 @@ using ComputeSharp.Exceptions; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Buffers.Abstract; using ComputeSharp.Graphics.Buffers.Enums; +using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Helpers; -using Vortice.Direct3D12; -using CommandList = ComputeSharp.Graphics.Commands.CommandList; +using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; namespace ComputeSharp { @@ -16,14 +16,18 @@ namespace ComputeSharp /// A representing a typed read write buffer stored on GPU memory /// /// The type of items stored on the buffer - public sealed class ConstantBuffer : HlslBuffer where T : unmanaged + public sealed class ConstantBuffer : HlslBuffer + where T : unmanaged { /// /// Creates a new instance with the specified parameters /// /// The associated with the current instance /// The number of items to store in the current buffer - internal ConstantBuffer(GraphicsDevice device, int size) : base(device, size, size * GetPaddedSize(), BufferType.Constant) { } + internal ConstantBuffer(GraphicsDevice device, int size) + : base(device, size, size * GetPaddedSize(), BufferType.Constant) + { + } /// /// Gets the right padded size for elements to store in the current instance @@ -91,14 +95,14 @@ namespace ComputeSharp } /// - public override void SetData(HlslBuffer buffer) + public override unsafe void SetData(HlslBuffer buffer) { if (buffer is ConstantBuffer) { // Directly copy the input buffer, if possible - using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + using CommandList copyCommandList = new CommandList(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); - copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes); + copyCommandList.CopyBufferRegion(buffer.D3D12Resource, 0, D3D12Resource, 0, SizeInBytes); copyCommandList.ExecuteAndWaitForCompletion(); } else SetDataWithCpuBuffer(buffer); diff --git a/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs b/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs index 2a035738..e6c0edeb 100644 --- a/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs +++ b/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions.cs @@ -7,177 +7,194 @@ using ComputeSharp.Graphics.Buffers.Abstract; namespace ComputeSharp { /// - /// A with extension methods for the type to allocate buffers + /// A with extension methods for the type to allocate buffers. /// public static class BufferExtensions { /// - /// Allocates a new constant buffer with the specified parameters + /// Allocates a new constant buffer with the specified parameters. /// - /// The type of items to store in the buffer - /// The instance to use to allocate the buffer - /// The input array with the data to copy on the allocated buffer - /// A constant instance with the contents of the input array + /// The type of items to store in the buffer. + /// The instance to use to allocate the buffer. + /// The input array with the data to copy on the allocated buffer. + /// A constant instance with the contents of the input array. [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ConstantBuffer AllocateConstantBuffer(this GraphicsDevice device, T[] array) where T : unmanaged + public static ConstantBuffer AllocateConstantBuffer(this GraphicsDevice device, T[] array) + where T : unmanaged { return device.AllocateConstantBuffer(array.AsSpan()); } /// - /// Allocates a new constant buffer with the specified parameters + /// Allocates a new constant buffer with the specified parameters. /// - /// The type of items to store in the buffer - /// The instance to use to allocate the buffer - /// The input with the data to copy on the allocated buffer - /// A constant instance with the contents of the input + /// The type of items to store in the buffer. + /// The instance to use to allocate the buffer. + /// The input with the data to copy on the allocated buffer. + /// A constant instance with the contents of the input . [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ConstantBuffer AllocateConstantBuffer(this GraphicsDevice device, Span span) where T : unmanaged + public static ConstantBuffer AllocateConstantBuffer(this GraphicsDevice device, Span span) + where T : unmanaged { - ConstantBuffer buffer = new ConstantBuffer(device, span.Length); + ConstantBuffer buffer = new(device, span.Length); + buffer.SetData(span); return buffer; } /// - /// Allocates a new constant buffer with the specified parameters + /// Allocates a new constant buffer with the specified parameters. /// - /// The type of items to store in the buffer - /// The instance to use to allocate the buffer - /// The input with the data to copy on the allocated buffer - /// A constant instance with the contents of the input + /// The type of items to store in the buffer. + /// The instance to use to allocate the buffer. + /// The input with the data to copy on the allocated buffer. + /// A constant instance with the contents of the input . [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ConstantBuffer AllocateConstantBuffer(this GraphicsDevice device, HlslBuffer buffer) where T : unmanaged + public static ConstantBuffer AllocateConstantBuffer(this GraphicsDevice device, HlslBuffer buffer) + where T : unmanaged { - ConstantBuffer constantBuffer = new ConstantBuffer(device, buffer.Size); + ConstantBuffer constantBuffer = new(device, buffer.Size); + constantBuffer.SetData(buffer); return constantBuffer; } /// - /// Allocates a new readonly buffer with the specified parameters + /// Allocates a new readonly buffer with the specified parameters. /// - /// The type of items to store in the buffer - /// The instance to use to allocate the buffer - /// The size of the buffer to allocate - /// A zeroed instance of size + /// The type of items to store in the buffer. + /// The instance to use to allocate the buffer. + /// The size of the buffer to allocate. + /// A zeroed instance of size . [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, int size) where T : unmanaged + public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, int size) + where T : unmanaged { - return new ReadOnlyBuffer(device, size); + return new(device, size); } /// - /// Allocates a new readonly buffer with the specified parameters + /// Allocates a new readonly buffer with the specified parameters. /// - /// The type of items to store in the buffer - /// The instance to use to allocate the buffer - /// The input array with the data to copy on the allocated buffer - /// A read write instance with the contents of the input array + /// The type of items to store in the buffer. + /// The instance to use to allocate the buffer. + /// The input array with the data to copy on the allocated buffer. + /// A read write instance with the contents of the input array. [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, T[] array) where T : unmanaged + public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, T[] array) + where T : unmanaged { return device.AllocateReadOnlyBuffer(array.AsSpan()); } /// - /// Allocates a new readonly buffer with the specified parameters + /// Allocates a new readonly buffer with the specified parameters. /// - /// The type of items to store in the buffer - /// The instance to use to allocate the buffer - /// The input with the data to copy on the allocated buffer - /// A read write instance with the contents of the input + /// The type of items to store in the buffer. + /// The instance to use to allocate the buffer. + /// The input with the data to copy on the allocated buffer. + /// A read write instance with the contents of the input . [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, Span span) where T : unmanaged + public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, Span span) + where T : unmanaged { - ReadOnlyBuffer buffer = new ReadOnlyBuffer(device, span.Length); + ReadOnlyBuffer buffer = new(device, span.Length); + buffer.SetData(span); return buffer; } /// - /// Allocates a new readonly buffer with the specified parameters + /// Allocates a new readonly buffer with the specified parameters. /// - /// The type of items to store in the buffer - /// The instance to use to allocate the buffer - /// The input with the data to copy on the allocated buffer - /// A read write instance with the contents of the input + /// The type of items to store in the buffer. + /// The instance to use to allocate the buffer. + /// The input with the data to copy on the allocated buffer. + /// A read write instance with the contents of the input . [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, HlslBuffer buffer) where T : unmanaged + public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, HlslBuffer buffer) + where T : unmanaged { - ReadOnlyBuffer readWriteBuffer = new ReadOnlyBuffer(device, buffer.Size); + ReadOnlyBuffer readWriteBuffer = new(device, buffer.Size); + readWriteBuffer.SetData(buffer); return readWriteBuffer; } /// - /// Allocates a new read write buffer with the specified parameters + /// Allocates a new read write buffer with the specified parameters. /// - /// The type of items to store in the buffer - /// The instance to use to allocate the buffer - /// The size of the buffer to allocate - /// A zeroed instance of size + /// The type of items to store in the buffer. + /// The instance to use to allocate the buffer. + /// The size of the buffer to allocate. + /// A zeroed instance of size . [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, int size) where T : unmanaged + public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, int size) + where T : unmanaged { - return new ReadWriteBuffer(device, size); + return new(device, size); } /// - /// Allocates a new read write buffer with the specified parameters + /// Allocates a new read write buffer with the specified parameters. /// - /// The type of items to store in the buffer - /// The instance to use to allocate the buffer - /// The input array with the data to copy on the allocated buffer - /// A read write instance with the contents of the input array + /// The type of items to store in the buffer. + /// The instance to use to allocate the buffer. + /// The input array with the data to copy on the allocated buffer. + /// A read write instance with the contents of the input array. [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, T[] array) where T : unmanaged + public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, T[] array) + where T : unmanaged { return device.AllocateReadWriteBuffer(array.AsSpan()); } /// - /// Allocates a new read write buffer with the specified parameters + /// Allocates a new read write buffer with the specified parameters. /// - /// The type of items to store in the buffer - /// The instance to use to allocate the buffer - /// The input with the data to copy on the allocated buffer - /// A read write instance with the contents of the input + /// The type of items to store in the buffer. + /// The instance to use to allocate the buffer. + /// The input with the data to copy on the allocated buffer. + /// A read write instance with the contents of the input . [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, Span span) where T : unmanaged + public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, Span span) + where T : unmanaged { - ReadWriteBuffer buffer = new ReadWriteBuffer(device, span.Length); + ReadWriteBuffer buffer = new(device, span.Length); + buffer.SetData(span); return buffer; } /// - /// Allocates a new read write buffer with the specified parameters + /// Allocates a new read write buffer with the specified parameters. /// - /// The type of items to store in the buffer - /// The instance to use to allocate the buffer - /// The input with the data to copy on the allocated buffer - /// A read write instance with the contents of the input + /// The type of items to store in the buffer. + /// The instance to use to allocate the buffer. + /// The input with the data to copy on the allocated buffer. + /// A read write instance with the contents of the input . [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, HlslBuffer buffer) where T : unmanaged + public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, HlslBuffer buffer) + where T : unmanaged { - ReadWriteBuffer readWriteBuffer = new ReadWriteBuffer(device, buffer.Size); + ReadWriteBuffer readWriteBuffer = new (device, buffer.Size); + readWriteBuffer.SetData(buffer); return readWriteBuffer; diff --git a/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions2.cs b/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions2.cs deleted file mode 100644 index 523f171f..00000000 --- a/src/ComputeSharp.Graphics/Buffers/Extensions/BufferExtensions2.cs +++ /dev/null @@ -1,203 +0,0 @@ -using System; -using System.Diagnostics.Contracts; -using System.Runtime.CompilerServices; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; - -namespace ComputeSharp -{ - /// - /// A with extension methods for the type to allocate buffers. - /// - public static class BufferExtensions2 - { - /// - /// Allocates a new constant buffer with the specified parameters. - /// - /// The type of items to store in the buffer. - /// The instance to use to allocate the buffer. - /// The input array with the data to copy on the allocated buffer. - /// A constant instance with the contents of the input array. - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ConstantBuffer2 AllocateConstantBuffer(this GraphicsDevice2 device, T[] array) - where T : unmanaged - { - return device.AllocateConstantBuffer(array.AsSpan()); - } - - /// - /// Allocates a new constant buffer with the specified parameters. - /// - /// The type of items to store in the buffer. - /// The instance to use to allocate the buffer. - /// The input with the data to copy on the allocated buffer. - /// A constant instance with the contents of the input . - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ConstantBuffer2 AllocateConstantBuffer(this GraphicsDevice2 device, Span span) - where T : unmanaged - { - ConstantBuffer2 buffer = new(device, span.Length); - - buffer.SetData(span); - - return buffer; - } - - /// - /// Allocates a new constant buffer with the specified parameters. - /// - /// The type of items to store in the buffer. - /// The instance to use to allocate the buffer. - /// The input with the data to copy on the allocated buffer. - /// A constant instance with the contents of the input . - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ConstantBuffer2 AllocateConstantBuffer(this GraphicsDevice2 device, HlslBuffer2 buffer) - where T : unmanaged - { - ConstantBuffer2 constantBuffer = new(device, buffer.Size); - - constantBuffer.SetData(buffer); - - return constantBuffer; - } - - /// - /// Allocates a new readonly buffer with the specified parameters. - /// - /// The type of items to store in the buffer. - /// The instance to use to allocate the buffer. - /// The size of the buffer to allocate. - /// A zeroed instance of size . - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlyBuffer2 AllocateReadOnlyBuffer(this GraphicsDevice2 device, int size) - where T : unmanaged - { - return new(device, size); - } - - /// - /// Allocates a new readonly buffer with the specified parameters. - /// - /// The type of items to store in the buffer. - /// The instance to use to allocate the buffer. - /// The input array with the data to copy on the allocated buffer. - /// A read write instance with the contents of the input array. - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlyBuffer2 AllocateReadOnlyBuffer(this GraphicsDevice2 device, T[] array) - where T : unmanaged - { - return device.AllocateReadOnlyBuffer(array.AsSpan()); - } - - /// - /// Allocates a new readonly buffer with the specified parameters. - /// - /// The type of items to store in the buffer. - /// The instance to use to allocate the buffer. - /// The input with the data to copy on the allocated buffer. - /// A read write instance with the contents of the input . - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlyBuffer2 AllocateReadOnlyBuffer(this GraphicsDevice2 device, Span span) - where T : unmanaged - { - ReadOnlyBuffer2 buffer = new(device, span.Length); - - buffer.SetData(span); - - return buffer; - } - - /// - /// Allocates a new readonly buffer with the specified parameters. - /// - /// The type of items to store in the buffer. - /// The instance to use to allocate the buffer. - /// The input with the data to copy on the allocated buffer. - /// A read write instance with the contents of the input . - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlyBuffer2 AllocateReadOnlyBuffer(this GraphicsDevice2 device, HlslBuffer2 buffer) - where T : unmanaged - { - ReadOnlyBuffer2 readWriteBuffer = new(device, buffer.Size); - - readWriteBuffer.SetData(buffer); - - return readWriteBuffer; - } - - /// - /// Allocates a new read write buffer with the specified parameters. - /// - /// The type of items to store in the buffer. - /// The instance to use to allocate the buffer. - /// The size of the buffer to allocate. - /// A zeroed instance of size . - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadWriteBuffer2 AllocateReadWriteBuffer(this GraphicsDevice2 device, int size) - where T : unmanaged - { - return new(device, size); - } - - /// - /// Allocates a new read write buffer with the specified parameters. - /// - /// The type of items to store in the buffer. - /// The instance to use to allocate the buffer. - /// The input array with the data to copy on the allocated buffer. - /// A read write instance with the contents of the input array. - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadWriteBuffer2 AllocateReadWriteBuffer(this GraphicsDevice2 device, T[] array) - where T : unmanaged - { - return device.AllocateReadWriteBuffer(array.AsSpan()); - } - - /// - /// Allocates a new read write buffer with the specified parameters. - /// - /// The type of items to store in the buffer. - /// The instance to use to allocate the buffer. - /// The input with the data to copy on the allocated buffer. - /// A read write instance with the contents of the input . - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadWriteBuffer2 AllocateReadWriteBuffer(this GraphicsDevice2 device, Span span) - where T : unmanaged - { - ReadWriteBuffer2 buffer = new(device, span.Length); - - buffer.SetData(span); - - return buffer; - } - - /// - /// Allocates a new read write buffer with the specified parameters. - /// - /// The type of items to store in the buffer. - /// The instance to use to allocate the buffer. - /// The input with the data to copy on the allocated buffer. - /// A read write instance with the contents of the input . - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadWriteBuffer2 AllocateReadWriteBuffer(this GraphicsDevice2 device, HlslBuffer2 buffer) - where T : unmanaged - { - ReadWriteBuffer2 readWriteBuffer = new (device, buffer.Size); - - readWriteBuffer.SetData(buffer); - - return readWriteBuffer; - } - } -} diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer2{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer2{T}.cs deleted file mode 100644 index e4af7c6e..00000000 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer2{T}.cs +++ /dev/null @@ -1,32 +0,0 @@ -using ComputeSharp.Exceptions; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Buffers.Enums; - -namespace ComputeSharp -{ - /// - /// A representing a typed readonly buffer stored on GPU memory - /// - /// The type of items stored on the buffer - public sealed class ReadOnlyBuffer2 : HlslStructuredBuffer2 - where T : unmanaged - { - /// - /// Creates a new instance with the specified parameters - /// - /// The associated with the current instance - /// The number of items to store in the current buffer - internal ReadOnlyBuffer2(GraphicsDevice2 device, int size) - : base(device, size, BufferType.ReadOnly) - { - } - - /// - /// Gets a single value from the current read write buffer - /// - /// The index of the value to get - /// This API can only be used from a compute shader, and will always throw if used anywhere else - public T this[int i] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyBuffer)}[int]"); - } -} diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs index bbcc5f32..b95259b1 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs @@ -9,14 +9,18 @@ namespace ComputeSharp /// A representing a typed readonly buffer stored on GPU memory /// /// The type of items stored on the buffer - public sealed class ReadOnlyBuffer : HlslStructuredBuffer where T : unmanaged + public sealed class ReadOnlyBuffer : HlslStructuredBuffer + where T : unmanaged { /// /// Creates a new instance with the specified parameters /// /// The associated with the current instance /// The number of items to store in the current buffer - internal ReadOnlyBuffer(GraphicsDevice device, int size) : base(device, size, BufferType.ReadOnly) { } + internal ReadOnlyBuffer(GraphicsDevice device, int size) + : base(device, size, BufferType.ReadOnly) + { + } /// /// Gets a single value from the current read write buffer diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer2{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer2{T}.cs deleted file mode 100644 index bea19683..00000000 --- a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer2{T}.cs +++ /dev/null @@ -1,32 +0,0 @@ -using ComputeSharp.Exceptions; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Buffers.Enums; - -namespace ComputeSharp -{ - /// - /// A representing a typed read write buffer stored on GPU memory - /// - /// The type of items stored on the buffer - public sealed class ReadWriteBuffer2 : HlslStructuredBuffer2 - where T : unmanaged - { - /// - /// Creates a new instance with the specified parameters - /// - /// The associated with the current instance - /// The number of items to store in the current buffer - internal ReadWriteBuffer2(GraphicsDevice2 device, int size) - : base(device, size, BufferType.ReadWrite) - { - } - - /// - /// Gets or sets a single value from the current read write buffer - /// - /// The index of the value to get or set - /// This API can only be used from a compute shader, and will always throw if used anywhere else - public ref T this[int i] => throw new InvalidExecutionContextException($"{nameof(ReadWriteBuffer)}[int]"); - } -} diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs index 3dfdac1e..5da8a8ad 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs @@ -9,14 +9,18 @@ namespace ComputeSharp /// A representing a typed read write buffer stored on GPU memory /// /// The type of items stored on the buffer - public sealed class ReadWriteBuffer : HlslStructuredBuffer where T : unmanaged + public sealed class ReadWriteBuffer : HlslStructuredBuffer + where T : unmanaged { /// /// Creates a new instance with the specified parameters /// /// The associated with the current instance /// The number of items to store in the current buffer - internal ReadWriteBuffer(GraphicsDevice device, int size) : base(device, size, BufferType.ReadWrite) { } + internal ReadWriteBuffer(GraphicsDevice device, int size) + : base(device, size, BufferType.ReadWrite) + { + } /// /// Gets or sets a single value from the current read write buffer diff --git a/src/ComputeSharp.Graphics/Commands/Abstract/CommandController.cs b/src/ComputeSharp.Graphics/Commands/Abstract/CommandController.cs deleted file mode 100644 index 618eecfa..00000000 --- a/src/ComputeSharp.Graphics/Commands/Abstract/CommandController.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using Vortice.Direct3D12; - -namespace ComputeSharp.Graphics.Commands.Abstract -{ - /// - /// A base for an instance that deals with GPU commands in some way - /// - internal abstract class CommandController : IDisposable - { - /// - /// Creates a new instance with the specified parameters - /// - /// The input to use to perform requested operations - /// The type of command list to use for the current instance - protected CommandController(GraphicsDevice device, CommandListType commandListType) - { - GraphicsDevice = device; - CommandListType = commandListType; - } - - /// - /// Gets the object targeted by the current instance - /// - public GraphicsDevice GraphicsDevice { get; } - - /// - /// Gets the command list type being used by the current instance - /// - public CommandListType CommandListType { get; } - - /// - public abstract void Dispose(); - } -} diff --git a/src/ComputeSharp.Graphics/Commands/CommandAllocatorPool.cs b/src/ComputeSharp.Graphics/Commands/CommandAllocatorPool.cs deleted file mode 100644 index d9f162bb..00000000 --- a/src/ComputeSharp.Graphics/Commands/CommandAllocatorPool.cs +++ /dev/null @@ -1,92 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Runtime.InteropServices; -using ComputeSharp.Graphics.Commands.Abstract; -using SharpGen.Runtime; -using Vortice.Direct3D12; - -namespace ComputeSharp.Graphics.Commands -{ - /// - /// A that acts as a pool to get new instances wheen needed - /// - internal sealed class CommandAllocatorPool : CommandController - { - /// - /// The queue of currently pooled instances - /// - private readonly Queue<(ID3D12CommandAllocator CommandAllocator, long FenceValue)> CommandAllocatorQueue = new Queue<(ID3D12CommandAllocator, long)>(); - - /// - public CommandAllocatorPool(GraphicsDevice device, CommandListType commandListType) : base(device, commandListType) { } - - /// - /// Adds a new item to the internal pool queue - /// - /// The input to enqueue - /// The fence value for the input - public void Enqueue(ID3D12CommandAllocator commandAllocator, long fenceValue) - { - lock (CommandAllocatorQueue) - { - CommandAllocatorQueue.Enqueue((commandAllocator, fenceValue)); - } - } - - /// - /// Gets a new or reused item to use to issue GPU commands - /// - [Pure] - public ID3D12CommandAllocator GetCommandAllocator() - { - lock (CommandAllocatorQueue) - { - // Reuse an existing command allocator, if one is present in the queue - if (CommandAllocatorQueue.Count > 0) - { - (ID3D12CommandAllocator commandAllocator, long fenceValue) = CommandAllocatorQueue.Peek(); - - long completedValue = CommandListType switch - { - CommandListType.Compute => GraphicsDevice.NativeComputeFence.CompletedValue, - CommandListType.Copy => GraphicsDevice.NativeCopyFence.CompletedValue, - _ => throw new NotSupportedException($"Unsupported command list type with value {CommandListType}") - }; - - if (fenceValue <= completedValue) - { - CommandAllocatorQueue.Dequeue(); - commandAllocator.Reset(); - - return commandAllocator; - } - } - - // Create a new command allocator - Result result = GraphicsDevice.NativeDevice.CreateCommandAllocator(CommandListType, out ID3D12CommandAllocator? nativeCommandAllocator); - - if (result.Failure) - { - throw new COMException("Failed to create the command allocator", result.Code); - } - - return nativeCommandAllocator!; - } - } - - /// - public override void Dispose() - { - lock (CommandAllocatorQueue) - { - foreach ((ID3D12CommandAllocator commandAllocator, long _) in CommandAllocatorQueue) - { - commandAllocator.Dispose(); - } - - CommandAllocatorQueue.Clear(); - } - } - } -} diff --git a/src/ComputeSharp.Graphics/Commands/CommandList.cs b/src/ComputeSharp.Graphics/Commands/CommandList.cs index 01f6fdd5..beda0a6c 100644 --- a/src/ComputeSharp.Graphics/Commands/CommandList.cs +++ b/src/ComputeSharp.Graphics/Commands/CommandList.cs @@ -1,116 +1,142 @@ using System; -using System.Runtime.InteropServices; -using ComputeSharp.Exceptions; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Commands.Abstract; -using SharpGen.Runtime; -using Vortice.Direct3D12; +using ComputeSharp.Graphics.Extensions; +using TerraFX.Interop; +using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; namespace ComputeSharp.Graphics.Commands { /// - /// A that represents a list of commands to issue to a GPU + /// A command list to set and execute operaations on the GPU. /// - internal sealed class CommandList : CommandController + internal unsafe ref struct CommandList { - /// - public CommandList(GraphicsDevice device, CommandListType commandListType) : base(device, commandListType) + /// + /// The instance associated with the current command list. + /// + private readonly GraphicsDevice device; + + /// + /// The command list type being used by the current instance. + /// + private readonly D3D12_COMMAND_LIST_TYPE d3d12CommandListType; + + /// + /// The object in use by the current instance. + /// + private ComPtr d3D12CommandAllocator; + + /// + /// The object in use by the current instance. + /// + private ComPtr d3D12GraphicsCommandList; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The target instance to use. + /// The type of command list to create. + public CommandList(GraphicsDevice device, D3D12_COMMAND_LIST_TYPE d3d12CommandListType) { - CommandAllocator = CommandListType switch - { - CommandListType.Compute => GraphicsDevice.ComputeAllocatorPool.GetCommandAllocator(), - CommandListType.Copy => GraphicsDevice.CopyAllocatorPool.GetCommandAllocator(), - _ => throw new NotSupportedException($"Unsupported command list type with value {CommandListType}") - }; - - Result result = GraphicsDevice.NativeDevice.CreateCommandList(0, commandListType, CommandAllocator, null, out ID3D12GraphicsCommandList? nativeCommandList); - - if (result.Failure) - { - throw new COMException("Failed to create the commands list", result.Code); - } - - NativeCommandList = nativeCommandList!; + this.device = device; + this.d3d12CommandListType = d3d12CommandListType; + this.d3D12CommandAllocator = device.GetCommandAllocator(d3d12CommandListType); + this.d3D12GraphicsCommandList = device.D3D12Device->CreateCommandList(d3d12CommandListType, this.d3D12CommandAllocator); // Set the heap descriptor if the command list is not for copy operations - if (CommandListType != CommandListType.Copy) + if (d3d12CommandListType is not D3D12_COMMAND_LIST_TYPE_COPY) { - NativeCommandList.SetDescriptorHeaps(1, new[] { GraphicsDevice.ShaderResourceViewAllocator.DescriptorHeap }); + device.SetDescriptorHeapForCommandList(this.d3D12GraphicsCommandList); } } + /// + /// Gets the command list type being used by the current instance. + /// + public readonly D3D12_COMMAND_LIST_TYPE D3d12CommandListType => this.d3d12CommandListType; /// - /// Gets the object in use by the current instance + /// Detaches the object in use by the current instance. /// - public ID3D12CommandAllocator CommandAllocator { get; } - - /// - /// Gets the object in use by the current instance - /// - public ID3D12GraphicsCommandList NativeCommandList { get; } - - /// - /// Copies a memory region from one resource to another - /// - /// The source to read from - /// The starting offset to read the source resource from - /// The destination to write to - /// The starting offset to write the destination resource from - /// The total number of bytes to copy from one resource to another - public void CopyBufferRegion(GraphicsResource source, long sourceOffset, GraphicsResource destination, long destinationOffset, long numBytes) + /// The object in use, with ownership. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ComPtr DetachD3D12CommandAllocator() { - NativeCommandList.CopyBufferRegion(destination.NativeResource, destinationOffset, source.NativeResource, sourceOffset, numBytes); + return this.d3D12CommandAllocator.Move(); } /// - /// Binds an input object to a specified root parameter + /// Gets a pointer to the object in use by the current instance. /// - /// The root parameter index to bind to the input resource - /// The input instance to bind - public void SetComputeRootDescriptorTable(int rootParameterIndex, GraphicsResource resource) + /// A double pointer to the current object to execute. + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly ID3D12CommandList** GetD3D12CommandListAddressOf() { - if (resource.NativeGpuDescriptorHandle == null) throw new InvalidOperationException("Invalid graphics resource GPU descriptor"); - if (resource.GraphicsDevice != GraphicsDevice) throw new GraphicsDeviceMismatchException(GraphicsDevice, resource); - - NativeCommandList.SetComputeRootDescriptorTable(rootParameterIndex, resource.NativeGpuDescriptorHandle.Value); + return this.d3D12GraphicsCommandList.Upcast().GetAddressOf(); } /// - /// Sets a given object ready to be executed + /// Copies a memory region from one resource to another. /// - /// The input to setup - public void SetPipelineState(PipelineState pipelineState) + /// The source to read from. + /// The starting offset to read the source resource from. + /// The destination to write to. + /// The starting offset to write the destination resource from. + /// The total number of bytes to copy from one resource to another. + public readonly void CopyBufferRegion(ID3D12Resource* d3D12ResourceSource, int sourceOffset, ID3D12Resource* d3d12ResourceDestination, int destinationOffset, int numBytes) { - NativeCommandList.SetComputeRootSignature(pipelineState.RootSignature); - NativeCommandList.SetPipelineState(pipelineState.NativePipelineState); + this.d3D12GraphicsCommandList.Get()->CopyBufferRegion(d3d12ResourceDestination, (uint)destinationOffset, d3D12ResourceSource, (uint)sourceOffset, (uint)numBytes); } /// - /// Dispatches the pending shader using the specified thread group values + /// Binds an input object to a specified root parameter. /// - /// The number of thread groups to schedule for the X axis - /// The number of thread groups to schedule for the Y axis - /// The number of thread groups to schedule for the Z axis - public void Dispatch(int threadGroupCountX, int threadGroupCountY, int threadGroupCountZ) + /// The root parameter index to bind to the input resource. + /// The input instance to bind. + public readonly void SetComputeRootDescriptorTable(int rootParameterIndex, D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle) { - NativeCommandList.Dispatch(threadGroupCountX, threadGroupCountY, threadGroupCountZ); + this.d3D12GraphicsCommandList.Get()->SetComputeRootDescriptorTable((uint)rootParameterIndex, d3D12GpuDescriptorHandle); } /// - /// Executes the commands in the current commands list, and waits for completion + /// Sets a given object ready to be executed. + /// + /// The input to setup. + public readonly void SetPipelineData(PipelineData pipelineData) + { + this.d3D12GraphicsCommandList.Get()->SetComputeRootSignature(pipelineData.D3D12RootSignature); + this.d3D12GraphicsCommandList.Get()->SetPipelineState(pipelineData.D3D12PipelineState); + } + + /// + /// Dispatches the pending shader using the specified thread group values. + /// + /// The number of thread groups to schedule for the X axis. + /// The number of thread groups to schedule for the Y axis. + /// The number of thread groups to schedule for the Z axis. + public readonly void Dispatch(int threadGroupCountX, int threadGroupCountY, int threadGroupCountZ) + { + this.d3D12GraphicsCommandList.Get()->Dispatch((uint)threadGroupCountX, (uint)threadGroupCountY, (uint)threadGroupCountZ); + } + + /// + /// Executes the commands in the current commands list, and waits for completion. /// public void ExecuteAndWaitForCompletion() { - NativeCommandList.Close(); + this.d3D12GraphicsCommandList.Get()->Close(); - GraphicsDevice.ExecuteCommandList(this); + this.device.ExecuteCommandList(ref this); } - /// - public override void Dispose() + /// + public void Dispose() { - NativeCommandList.Dispose(); + this.d3D12CommandAllocator.Dispose(); + this.d3D12GraphicsCommandList.Dispose(); } } } diff --git a/src/ComputeSharp.Graphics/Commands/CommandList2.cs b/src/ComputeSharp.Graphics/Commands/CommandList2.cs deleted file mode 100644 index c60432f2..00000000 --- a/src/ComputeSharp.Graphics/Commands/CommandList2.cs +++ /dev/null @@ -1,142 +0,0 @@ -using System; -using System.Diagnostics.Contracts; -using System.Runtime.CompilerServices; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Extensions; -using TerraFX.Interop; -using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; - -namespace ComputeSharp.Graphics.Commands -{ - /// - /// A command list to set and execute operaations on the GPU. - /// - internal unsafe ref struct CommandList2 - { - /// - /// The instance associated with the current command list. - /// - private readonly GraphicsDevice2 device; - - /// - /// The command list type being used by the current instance. - /// - private readonly D3D12_COMMAND_LIST_TYPE d3d12CommandListType; - - /// - /// The object in use by the current instance. - /// - private ComPtr d3D12CommandAllocator; - - /// - /// The object in use by the current instance. - /// - private ComPtr d3D12GraphicsCommandList; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The target instance to use. - /// The type of command list to create. - public CommandList2(GraphicsDevice2 device, D3D12_COMMAND_LIST_TYPE d3d12CommandListType) - { - this.device = device; - this.d3d12CommandListType = d3d12CommandListType; - this.d3D12CommandAllocator = device.GetCommandAllocator(d3d12CommandListType); - this.d3D12GraphicsCommandList = device.D3D12Device->CreateCommandList(d3d12CommandListType, this.d3D12CommandAllocator); - - // Set the heap descriptor if the command list is not for copy operations - if (d3d12CommandListType is not D3D12_COMMAND_LIST_TYPE_COPY) - { - device.SetDescriptorHeapForCommandList(this.d3D12GraphicsCommandList); - } - } - - /// - /// Gets the command list type being used by the current instance. - /// - public readonly D3D12_COMMAND_LIST_TYPE D3d12CommandListType => this.d3d12CommandListType; - - /// - /// Detaches the object in use by the current instance. - /// - /// The object in use, with ownership. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ComPtr DetachD3D12CommandAllocator() - { - return this.d3D12CommandAllocator.Move(); - } - - /// - /// Gets a pointer to the object in use by the current instance. - /// - /// A double pointer to the current object to execute. - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public readonly ID3D12CommandList** GetD3D12CommandListAddressOf() - { - return this.d3D12GraphicsCommandList.Upcast().GetAddressOf(); - } - - /// - /// Copies a memory region from one resource to another. - /// - /// The source to read from. - /// The starting offset to read the source resource from. - /// The destination to write to. - /// The starting offset to write the destination resource from. - /// The total number of bytes to copy from one resource to another. - public readonly void CopyBufferRegion(ID3D12Resource* d3D12ResourceSource, int sourceOffset, ID3D12Resource* d3d12ResourceDestination, int destinationOffset, int numBytes) - { - this.d3D12GraphicsCommandList.Get()->CopyBufferRegion(d3d12ResourceDestination, (uint)destinationOffset, d3D12ResourceSource, (uint)sourceOffset, (uint)numBytes); - } - - /// - /// Binds an input object to a specified root parameter. - /// - /// The root parameter index to bind to the input resource. - /// The input instance to bind. - public readonly void SetComputeRootDescriptorTable(int rootParameterIndex, D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle) - { - this.d3D12GraphicsCommandList.Get()->SetComputeRootDescriptorTable((uint)rootParameterIndex, d3D12GpuDescriptorHandle); - } - - /// - /// Sets a given object ready to be executed. - /// - /// The input to setup. - public readonly void SetPipelineData(PipelineData pipelineData) - { - this.d3D12GraphicsCommandList.Get()->SetComputeRootSignature(pipelineData.D3D12RootSignature); - this.d3D12GraphicsCommandList.Get()->SetPipelineState(pipelineData.D3D12PipelineState); - } - - /// - /// Dispatches the pending shader using the specified thread group values. - /// - /// The number of thread groups to schedule for the X axis. - /// The number of thread groups to schedule for the Y axis. - /// The number of thread groups to schedule for the Z axis. - public readonly void Dispatch(int threadGroupCountX, int threadGroupCountY, int threadGroupCountZ) - { - this.d3D12GraphicsCommandList.Get()->Dispatch((uint)threadGroupCountX, (uint)threadGroupCountY, (uint)threadGroupCountZ); - } - - /// - /// Executes the commands in the current commands list, and waits for completion. - /// - public void ExecuteAndWaitForCompletion() - { - this.d3D12GraphicsCommandList.Get()->Close(); - - this.device.ExecuteCommandList(ref this); - } - - /// - public void Dispose() - { - this.d3D12CommandAllocator.Dispose(); - this.d3D12GraphicsCommandList.Dispose(); - } - } -} diff --git a/src/ComputeSharp.Graphics/Commands/PipelineState.cs b/src/ComputeSharp.Graphics/Commands/PipelineState.cs deleted file mode 100644 index a7323687..00000000 --- a/src/ComputeSharp.Graphics/Commands/PipelineState.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Vortice.Direct3D12; - -namespace ComputeSharp.Graphics.Commands -{ - /// - /// A representing a custom pipeline state for a compute operation - /// - internal sealed class PipelineState : ComputePipelineStateDescription - { - /// - /// Creates a new instance with the specified parameters - /// - /// The to use - /// The value for the current shader - /// The bytecode for the compute shader to run - public PipelineState(GraphicsDevice device, ID3D12RootSignature rootSignature, ShaderBytecode computeShader) - { - RootSignature = rootSignature; - ComputeShader = computeShader; - - NativePipelineState = device.NativeDevice.CreateComputePipelineState(this); - } - - /// - /// Gets the instance for the current object - /// - public ID3D12PipelineState NativePipelineState { get; } - } -} diff --git a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj index d2bcebb7..1b2a72f0 100644 --- a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj +++ b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj @@ -6,10 +6,6 @@ true - - - - diff --git a/src/ComputeSharp.Graphics/DescriptorAllocator.cs b/src/ComputeSharp.Graphics/DescriptorAllocator.cs index a1b92065..5c5c0a47 100644 --- a/src/ComputeSharp.Graphics/DescriptorAllocator.cs +++ b/src/ComputeSharp.Graphics/DescriptorAllocator.cs @@ -1,97 +1,100 @@ -using System; -using Vortice.Direct3D12; +using ComputeSharp.Graphics.Extensions; +using System; +using TerraFX.Interop; +using static TerraFX.Interop.D3D12_DESCRIPTOR_HEAP_TYPE; namespace ComputeSharp.Graphics { /// - /// A that provides logic to create resource descriptors for a instance + /// A type that provides logic to create resource descriptors for a instance. /// - internal sealed class DescriptorAllocator : IDisposable + internal unsafe struct DescriptorAllocator : IDisposable { /// - /// The default number of available descriptors per heap + /// The default number of available descriptors per heap. /// - private const int DescriptorsPerHeap = 4096; + private const uint DescriptorsPerHeap = 4096; /// - /// The dummy object used to handle concurrent allocation requests + /// The in use for the current instance. /// - private readonly object Lock = new object(); + private ComPtr d3D12DescriptorHeap; /// - /// The size of each new descriptor being allocated + /// The dummy object used to handle concurrent allocation requests. /// - private readonly int DescriptorSize; + private readonly object allocationLock; /// - /// The current for the instance in use + /// The size of each new descriptor being allocated. /// - private CpuDescriptorHandle _CurrentCpuHandle; + private readonly uint descriptorSize; /// - /// The current for the instance in use + /// The current for the instance in use. /// - private GpuDescriptorHandle _CurrentGpuHandle; + private D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandle; /// - /// The number of remaining handles to allocate on the current heap + /// The current for the instance in use. /// - private int _RemainingHandles; + private D3D12_GPU_DESCRIPTOR_HANDLE d3d12GpuDescriptorHandle; /// - /// Creates a new instance with the specified parameters + /// The number of remaining handles to allocate on the current heap. + /// + private uint remainingHandles; + + /// + /// Creates a new instance with the specified parameters. /// /// The instance to use - public DescriptorAllocator(ID3D12Device device) + public DescriptorAllocator(ID3D12Device* device) { - DescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); - - DescriptorHeapDescription descriptorHeapDescription = new DescriptorHeapDescription - { - DescriptorCount = DescriptorsPerHeap, - Flags = DescriptorHeapFlags.ShaderVisible, - Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView - }; - - DescriptorHeap = device.CreateDescriptorHeap(descriptorHeapDescription); - - _RemainingHandles = DescriptorsPerHeap; - _CurrentCpuHandle = DescriptorHeap.GetCPUDescriptorHandleForHeapStart(); - _CurrentGpuHandle = DescriptorHeap.GetGPUDescriptorHandleForHeapStart(); + this.d3D12DescriptorHeap = device->CreateDescriptorHeap(DescriptorsPerHeap); + this.allocationLock = new object(); + this.descriptorSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + this.d3d12CpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetCPUDescriptorHandleForHeapStart(); + this.d3d12GpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetGPUDescriptorHandleForHeapStart(); + this.remainingHandles = this.d3D12DescriptorHeap.Get()->GetDesc().NumDescriptors; } /// - /// Gets the object in use for the current instance + /// Gets the in use for the current instance. /// - public ID3D12DescriptorHeap DescriptorHeap { get; } + public ID3D12DescriptorHeap* D3D12DescriptorHeap => this.d3D12DescriptorHeap; /// /// Allocates a new CPU and GPU handle pair to use in a memory buffer /// - /// A pair of and to use - public (CpuDescriptorHandle, GpuDescriptorHandle) Allocate() + /// The resulting value. + /// The resulting value. + public void Allocate( + out D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandle, + out D3D12_GPU_DESCRIPTOR_HANDLE d3d12GpuDescriptorHandle) { - lock (Lock) + lock (this.allocationLock) { - if (_RemainingHandles == 0) + if (this.remainingHandles == 0) { - _RemainingHandles = DescriptorHeap.Description.DescriptorCount; - _CurrentCpuHandle = DescriptorHeap.GetCPUDescriptorHandleForHeapStart(); - _CurrentGpuHandle = DescriptorHeap.GetGPUDescriptorHandleForHeapStart(); + this.d3d12CpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetCPUDescriptorHandleForHeapStart(); + this.d3d12GpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetGPUDescriptorHandleForHeapStart(); + this.remainingHandles = this.d3D12DescriptorHeap.Get()->GetDesc().NumDescriptors; } - CpuDescriptorHandle cpuDescriptorHandle = _CurrentCpuHandle; - GpuDescriptorHandle gpuDescriptorHandle = _CurrentGpuHandle; + d3d12CpuDescriptorHandle = this.d3d12CpuDescriptorHandle; + d3d12GpuDescriptorHandle = this.d3d12GpuDescriptorHandle; - _CurrentCpuHandle += DescriptorSize; - _CurrentGpuHandle += DescriptorSize; - _RemainingHandles -= 1; - - return (cpuDescriptorHandle, gpuDescriptorHandle); + this.d3d12CpuDescriptorHandle.ptr += this.descriptorSize; + this.d3d12GpuDescriptorHandle.ptr += this.descriptorSize; + this.remainingHandles--; } } /// - public void Dispose() => DescriptorHeap.Dispose(); + public void Dispose() + { + this.d3D12DescriptorHeap.Dispose(); + } } } diff --git a/src/ComputeSharp.Graphics/DescriptorAllocator2.cs b/src/ComputeSharp.Graphics/DescriptorAllocator2.cs deleted file mode 100644 index 7eb6bd6b..00000000 --- a/src/ComputeSharp.Graphics/DescriptorAllocator2.cs +++ /dev/null @@ -1,100 +0,0 @@ -using ComputeSharp.Graphics.Extensions; -using System; -using TerraFX.Interop; -using static TerraFX.Interop.D3D12_DESCRIPTOR_HEAP_TYPE; - -namespace ComputeSharp.Graphics -{ - /// - /// A type that provides logic to create resource descriptors for a instance. - /// - internal unsafe struct DescriptorAllocator2 : IDisposable - { - /// - /// The default number of available descriptors per heap. - /// - private const uint DescriptorsPerHeap = 4096; - - /// - /// The in use for the current instance. - /// - private ComPtr d3D12DescriptorHeap; - - /// - /// The dummy object used to handle concurrent allocation requests. - /// - private readonly object allocationLock; - - /// - /// The size of each new descriptor being allocated. - /// - private readonly uint descriptorSize; - - /// - /// The current for the instance in use. - /// - private D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandle; - - /// - /// The current for the instance in use. - /// - private D3D12_GPU_DESCRIPTOR_HANDLE d3d12GpuDescriptorHandle; - - /// - /// The number of remaining handles to allocate on the current heap. - /// - private uint remainingHandles; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The instance to use - public DescriptorAllocator2(ID3D12Device* device) - { - this.d3D12DescriptorHeap = device->CreateDescriptorHeap(DescriptorsPerHeap); - this.allocationLock = new object(); - this.descriptorSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - this.d3d12CpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetCPUDescriptorHandleForHeapStart(); - this.d3d12GpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetGPUDescriptorHandleForHeapStart(); - this.remainingHandles = this.d3D12DescriptorHeap.Get()->GetDesc().NumDescriptors; - } - - /// - /// Gets the in use for the current instance. - /// - public ID3D12DescriptorHeap* D3D12DescriptorHeap => this.d3D12DescriptorHeap; - - /// - /// Allocates a new CPU and GPU handle pair to use in a memory buffer - /// - /// The resulting value. - /// The resulting value. - public void Allocate( - out D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandle, - out D3D12_GPU_DESCRIPTOR_HANDLE d3d12GpuDescriptorHandle) - { - lock (this.allocationLock) - { - if (this.remainingHandles == 0) - { - this.d3d12CpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetCPUDescriptorHandleForHeapStart(); - this.d3d12GpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetGPUDescriptorHandleForHeapStart(); - this.remainingHandles = this.d3D12DescriptorHeap.Get()->GetDesc().NumDescriptors; - } - - d3d12CpuDescriptorHandle = this.d3d12CpuDescriptorHandle; - d3d12GpuDescriptorHandle = this.d3d12GpuDescriptorHandle; - - this.d3d12CpuDescriptorHandle.ptr += this.descriptorSize; - this.d3d12GpuDescriptorHandle.ptr += this.descriptorSize; - this.remainingHandles--; - } - } - - /// - public void Dispose() - { - this.d3D12DescriptorHeap.Dispose(); - } - } -} diff --git a/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs b/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs index f3ceeae2..20ab7cbb 100644 --- a/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs +++ b/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs @@ -15,17 +15,20 @@ namespace ComputeSharp.Exceptions /// /// Creates a new instance /// - internal GraphicsDeviceMismatchException(GraphicsDevice device, GraphicsResource resource) : base(GetExceptionMessage(device, resource)) { } + internal GraphicsDeviceMismatchException(GraphicsDevice device, GraphicsResource resource) + : base(GetExceptionMessage(device, resource)) + { + } // Gets a proper exception message for a pair of device and resource [Pure] - private static string GetExceptionMessage(GraphicsDevice device, GraphicsResource resource) + private static unsafe string GetExceptionMessage(GraphicsDevice device, GraphicsResource resource) { StringBuilder builder = new StringBuilder(); builder.AppendLine("Invalid pairing of graphics devices used to run a compute shader and allocate memory buffers."); // Check if the device is effectively the same but with two instances pointing to the same adapter - if (device.NativeDevice.AdapterLuid == resource.GraphicsDevice.NativeDevice.AdapterLuid) + if (device.D3D12Device->GetAdapterLuid().Equals(resource.GraphicsDevice.D3D12Device->GetAdapterLuid())) { builder.AppendLine("The graphics devices used to allocate buffers and run the shader must be the same instance, not just be using the same physical device."); builder.AppendLine("You can still run different shaders on different devices, but a shader run on one device must only use buffers allocated by the same device instance."); @@ -33,8 +36,8 @@ namespace ComputeSharp.Exceptions else { // Actually different devices - builder.AppendLine($"The target device to run the compute shader is \"{device.Name}\" (id: {device.NativeDevice.AdapterLuid})."); - builder.AppendLine($"The buffer of type {resource.GetType().ToFriendlyString()} was allocated on device \"{resource.GraphicsDevice.Name}\" (id: {resource.GraphicsDevice.NativeDevice.AdapterLuid})."); + builder.AppendLine($"The target device to run the compute shader is \"{device.Name}\" (id: {device.D3D12Device->GetAdapterLuid()})."); + builder.AppendLine($"The buffer of type {resource.GetType().ToFriendlyString()} was allocated on device \"{resource.GraphicsDevice.Name}\" (id: {resource.GraphicsDevice.D3D12Device->GetAdapterLuid()})."); builder.AppendLine("Make sure to always allocate buffers on the same device used to actually run the code that accesses them."); } diff --git a/src/ComputeSharp.Graphics/GraphicsDevice.cs b/src/ComputeSharp.Graphics/GraphicsDevice.cs index 4693d290..b0a1352b 100644 --- a/src/ComputeSharp.Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp.Graphics/GraphicsDevice.cs @@ -1,198 +1,206 @@ -using System; +using ComputeSharp.Core.Interop; using ComputeSharp.Graphics.Commands; -using Vortice.Direct3D12; -using Vortice.DXGI; -using CommandList = ComputeSharp.Graphics.Commands.CommandList; -using Direct3DFeatureLevel = Vortice.Direct3D.FeatureLevel; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.Graphics.Helpers; +using System.Runtime.CompilerServices; +using TerraFX.Interop; +using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; +using static TerraFX.Interop.D3D12_FEATURE; namespace ComputeSharp.Graphics { /// - /// A that represents a DX12.1-compatible GPU device that can be used to run compute shaders + /// A that represents a DX12.1-compatible GPU device that can be used to run compute shaders. /// - public sealed class GraphicsDevice : IDisposable + public sealed unsafe class GraphicsDevice : NativeObject { /// - /// Gets the value that needs to be supported by GPUs mapped to a instance + /// The underlying wrapped by the current instance. /// - public const Direct3DFeatureLevel FeatureLevel = Direct3DFeatureLevel.Level_12_1; + private ComPtr d3D12Device; /// - /// The instance to use for compute operations + /// The instance to use for compute operations. /// - private readonly ID3D12CommandQueue NativeComputeCommandQueue; + private ComPtr d3D12ComputeCommandQueue; /// - /// The instance to use for copy operations + /// The instance to use for copy operations. /// - private readonly ID3D12CommandQueue NativeCopyCommandQueue; + private ComPtr d3D12CopyCommandQueue; /// - /// Creates a new instance for the input + /// The instance used for compute operations. /// - /// The to use for the new instance - /// The available info for the new instance - public GraphicsDevice(ID3D12Device device, AdapterDescription description) + private ComPtr d3D12ComputeFence; + + /// + /// The instance used for copy operations. + /// + private ComPtr d3D12CopyFence; + + /// + /// The instance for compute operations. + /// + private readonly ID3D12CommandAllocatorPool computeCommandAllocatorPool; + + /// + /// Gets the instance for copy operations. + /// + private readonly ID3D12CommandAllocatorPool copyCommandAllocatorPool; + + /// + /// The instance to use when allocating new buffers. + /// + private DescriptorAllocator shaderResourceViewDescriptorAllocator; + + /// + /// The next fence value for compute operations using . + /// + private ulong nextD3D12ComputeFenceValue = 1; + + /// + /// The next fence value for copy operations using . + /// + private ulong nextD3D12CopyFenceValue = 1; + + /// + /// Creates a new instance for the input . + /// + /// The to use for the new instance. + /// The available info for the new instance. + internal GraphicsDevice(ComPtr d3d12device, DXGI_ADAPTER_DESC1* dxgiDescription1) { - NativeDevice = device; - Name = description.Description; - MemorySize = description.DedicatedVideoMemory; - ComputeUnits = device.Options1.TotalLaneCount; - WavefrontSize = device.Options1.WaveLaneCountMin; + this.d3D12Device = d3d12device; + this.d3D12ComputeCommandQueue = d3d12device.Get()->CreateCommandQueue(D3D12_COMMAND_LIST_TYPE_COMPUTE); + this.d3D12CopyCommandQueue = d3d12device.Get()->CreateCommandQueue(D3D12_COMMAND_LIST_TYPE_COPY); + this.d3D12ComputeFence = d3d12device.Get()->CreateFence(); + this.d3D12CopyFence = d3d12device.Get()->CreateFence(); - NativeComputeCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(CommandListType.Compute)); - NativeCopyCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(CommandListType.Copy)); + this.computeCommandAllocatorPool = new ID3D12CommandAllocatorPool(D3D12_COMMAND_LIST_TYPE_COMPUTE); + this.copyCommandAllocatorPool = new ID3D12CommandAllocatorPool(D3D12_COMMAND_LIST_TYPE_COPY); + this.shaderResourceViewDescriptorAllocator = new DescriptorAllocator(d3d12device); - ComputeAllocatorPool = new CommandAllocatorPool(this, CommandListType.Compute); - CopyAllocatorPool = new CommandAllocatorPool(this, CommandListType.Copy); + Name = new string((char*)dxgiDescription1->Description); + MemorySize = dxgiDescription1->DedicatedVideoMemory; - NativeComputeFence = NativeDevice.CreateFence(0); - NativeCopyFence = NativeDevice.CreateFence(0); + var d3D12Options1Data = d3d12device.Get()->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1); - ShaderResourceViewAllocator = new DescriptorAllocator(NativeDevice); + ComputeUnits = d3D12Options1Data.TotalLaneCount; + WavefrontSize = d3D12Options1Data.WaveLaneCountMin; } /// - /// Gets the name of the current instance + /// Gets the name of the current instance. /// public string Name { get; } /// - /// Gets the size of the dedicated video memory for the current instance + /// Gets the size of the dedicated video memory for the current instance. /// - public long MemorySize { get; } + public nuint MemorySize { get; } /// - /// Gets the number of total lanes on the current device (eg. CUDA cores on an nVidia GPU) + /// Gets the number of total lanes on the current device (eg. CUDA cores on an nVidia GPU). /// - public int ComputeUnits { get; } + public uint ComputeUnits { get; } /// - /// Gets the number of lanes in a SIMD wave on the current device (also known as "wavefront size" or "warp width") + /// Gets the number of lanes in a SIMD wave on the current device (also known as "wavefront size" or "warp width"). /// - public int WavefrontSize { get; } + public uint WavefrontSize { get; } /// - /// Gets the object wrapped by the current instance + /// Gets the underlying wrapped by the current instance. /// - internal ID3D12Device NativeDevice { get; } + internal ID3D12Device* D3D12Device => this.d3D12Device; - /// - /// Gets the object for the current instance, used when allocating new buffers - /// - internal DescriptorAllocator ShaderResourceViewAllocator { get; set; } - - /// - /// Gets the instance for compute operations - /// - internal CommandAllocatorPool ComputeAllocatorPool { get; } - - /// - /// Gets the instance for copy operations - /// - internal CommandAllocatorPool CopyAllocatorPool { get; } - - /// - /// Gets the instance used for compute operations - /// - internal ID3D12Fence NativeComputeFence { get; } - - /// - /// Gets the instance used for copy operations - /// - internal ID3D12Fence NativeCopyFence { get; } - - /// - /// Gets the next fence value for compute operations - /// - internal long NextComputeFenceValue { get; private set; } = 1; - - /// - /// Gets the next fence value for copy operations - /// - internal long NextCopyFenceValue { get; private set; } = 1; - - /// - /// Creates a instance from a description - /// - /// A instance with the info for the new object to create - /// A new instance to use in a compute shader - internal ID3D12RootSignature CreateRootSignature(VersionedRootSignatureDescription rootSignatureDescription) + /// + internal void AllocateShaderResourceViewDescriptorHandles( + out D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandle, + out D3D12_GPU_DESCRIPTOR_HANDLE d3d12GpuDescriptorHandle) { - return NativeDevice.CreateRootSignature(0, rootSignatureDescription); + this.shaderResourceViewDescriptorAllocator.Allocate(out d3d12CpuDescriptorHandle, out d3d12GpuDescriptorHandle); } - /// - /// Executes a and waits for the GPU to finish processing it - /// - /// The input to execute - internal void ExecuteCommandList(CommandList commandList) + /// + /// The type of command allocator to rent. + internal ComPtr GetCommandAllocator(D3D12_COMMAND_LIST_TYPE d3d12CommandListType) { - ID3D12Fence fence = commandList.CommandListType switch + return d3d12CommandListType switch { - CommandListType.Compute => NativeComputeFence, - CommandListType.Copy => NativeCopyFence, - _ => throw new NotSupportedException("This command list type is not supported.") + D3D12_COMMAND_LIST_TYPE_COMPUTE => this.computeCommandAllocatorPool.GetCommandAllocator(this.d3D12Device, this.d3D12ComputeFence), + D3D12_COMMAND_LIST_TYPE_COPY => this.computeCommandAllocatorPool.GetCommandAllocator(this.d3D12Device, this.d3D12CopyFence), + _ => throw null! }; - - long fenceValue = GetFenceValueForCommandList(commandList); - - if (fenceValue <= fence.CompletedValue) return; - - fence.SetEventOnCompletion(fenceValue, default(IntPtr)); } /// - /// Executes a and, signals and retrieves the following fence value + /// Sets the descriptor heap for a given instance. /// - /// The input to execute - /// The value of the new fence to wait for - private long GetFenceValueForCommandList(CommandList commandList) + /// The input instance to use. + internal void SetDescriptorHeapForCommandList(ID3D12GraphicsCommandList* d3D12GraphicsCommandList) { - CommandAllocatorPool commandAllocatorPool; - ID3D12CommandQueue commandQueue; - ID3D12Fence fence; - long fenceValue; + ID3D12DescriptorHeap* d3D12DescriptorHeap = this.shaderResourceViewDescriptorAllocator.D3D12DescriptorHeap; - switch (commandList.CommandListType) + d3D12GraphicsCommandList->SetDescriptorHeaps(1, &d3D12DescriptorHeap); + } + + /// + /// Executes a given command list and waits for the operation to be completed. + /// + /// The input to execute. + internal void ExecuteCommandList(ref CommandList commandList) + { + ref readonly ID3D12CommandAllocatorPool commandAllocatorPool = ref Unsafe.NullRef(); + ID3D12CommandQueue* d3D12CommandQueue; + ID3D12Fence* d3D12Fence; + ulong d3D12FenceValue; + + // Get the target command queue, fence and pool for the list type + switch (commandList.D3d12CommandListType) { - case CommandListType.Compute: - commandAllocatorPool = ComputeAllocatorPool; - commandQueue = NativeComputeCommandQueue; - fence = NativeComputeFence; - fenceValue = NextComputeFenceValue++; + case D3D12_COMMAND_LIST_TYPE_COMPUTE: + commandAllocatorPool = ref this.computeCommandAllocatorPool; + d3D12CommandQueue = this.d3D12ComputeCommandQueue; + d3D12Fence = this.d3D12ComputeFence; + d3D12FenceValue = this.nextD3D12ComputeFenceValue++; break; - case CommandListType.Copy: - commandAllocatorPool = CopyAllocatorPool; - commandQueue = NativeCopyCommandQueue; - fence = NativeCopyFence; - fenceValue = NextCopyFenceValue++; + case D3D12_COMMAND_LIST_TYPE_COPY: + commandAllocatorPool = ref this.copyCommandAllocatorPool; + d3D12CommandQueue = this.d3D12CopyCommandQueue; + d3D12Fence = this.d3D12CopyFence; + d3D12FenceValue = this.nextD3D12CopyFenceValue++; break; - default: throw new NotSupportedException($"Unsupported command list of type {commandList.CommandListType}"); + default: throw null!; } - commandAllocatorPool.Enqueue(commandList.CommandAllocator, fenceValue); - commandQueue.ExecuteCommandLists(commandList.NativeCommandList); - commandQueue.Signal(fence, fenceValue); + // Execute the command list and signal to the target fence + d3D12CommandQueue->ExecuteCommandLists(1, commandList.GetD3D12CommandListAddressOf()); - return fenceValue; + d3D12CommandQueue->Signal(d3D12Fence, d3D12FenceValue).Assert(); + + // If the fence value hasn't been reached, wait until the operation completes + if (d3D12FenceValue > d3D12Fence->GetCompletedValue()) + { + d3D12Fence->SetEventOnCompletion(d3D12FenceValue, default).Assert(); + } + + // Enqueue the command allocator pool so that it can be reused later + commandAllocatorPool.Enqueue(commandList.DetachD3D12CommandAllocator()); } /// - public void Dispose() + protected override void OnDispose() { - ShaderResourceViewAllocator.Dispose(); - - ComputeAllocatorPool.Dispose(); - CopyAllocatorPool.Dispose(); - - NativeComputeCommandQueue.Dispose(); - NativeCopyCommandQueue.Dispose(); - - NativeComputeFence.Dispose(); - NativeCopyFence.Dispose(); - - NativeDevice.Dispose(); + this.d3D12Device.Dispose(); + this.d3D12ComputeCommandQueue.Dispose(); + this.d3D12CopyCommandQueue.Dispose(); + this.d3D12ComputeFence.Dispose(); + this.d3D12CopyFence.Dispose(); + this.computeCommandAllocatorPool.Dispose(); + this.copyCommandAllocatorPool.Dispose(); + this.shaderResourceViewDescriptorAllocator.Dispose(); } } } diff --git a/src/ComputeSharp.Graphics/GraphicsDevice2.cs b/src/ComputeSharp.Graphics/GraphicsDevice2.cs deleted file mode 100644 index 989a8a16..00000000 --- a/src/ComputeSharp.Graphics/GraphicsDevice2.cs +++ /dev/null @@ -1,206 +0,0 @@ -using ComputeSharp.Core.Interop; -using ComputeSharp.Graphics.Commands; -using ComputeSharp.Graphics.Extensions; -using ComputeSharp.Graphics.Helpers; -using System.Runtime.CompilerServices; -using TerraFX.Interop; -using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; -using static TerraFX.Interop.D3D12_FEATURE; - -namespace ComputeSharp.Graphics -{ - /// - /// A that represents a DX12.1-compatible GPU device that can be used to run compute shaders. - /// - public sealed unsafe class GraphicsDevice2 : NativeObject - { - /// - /// The underlying wrapped by the current instance. - /// - private ComPtr d3D12Device; - - /// - /// The instance to use for compute operations. - /// - private ComPtr d3D12ComputeCommandQueue; - - /// - /// The instance to use for copy operations. - /// - private ComPtr d3D12CopyCommandQueue; - - /// - /// The instance used for compute operations. - /// - private ComPtr d3D12ComputeFence; - - /// - /// The instance used for copy operations. - /// - private ComPtr d3D12CopyFence; - - /// - /// The instance for compute operations. - /// - private readonly ID3D12CommandAllocatorPool computeCommandAllocatorPool; - - /// - /// Gets the instance for copy operations. - /// - private readonly ID3D12CommandAllocatorPool copyCommandAllocatorPool; - - /// - /// The instance to use when allocating new buffers. - /// - private DescriptorAllocator2 shaderResourceViewDescriptorAllocator; - - /// - /// The next fence value for compute operations using . - /// - private ulong nextD3D12ComputeFenceValue = 1; - - /// - /// The next fence value for copy operations using . - /// - private ulong nextD3D12CopyFenceValue = 1; - - /// - /// Creates a new instance for the input . - /// - /// The to use for the new instance. - /// The available info for the new instance. - internal GraphicsDevice2(ComPtr d3d12device, DXGI_ADAPTER_DESC1* dxgiDescription1) - { - this.d3D12Device = d3d12device; - this.d3D12ComputeCommandQueue = d3d12device.Get()->CreateCommandQueue(D3D12_COMMAND_LIST_TYPE_COMPUTE); - this.d3D12CopyCommandQueue = d3d12device.Get()->CreateCommandQueue(D3D12_COMMAND_LIST_TYPE_COPY); - this.d3D12ComputeFence = d3d12device.Get()->CreateFence(); - this.d3D12CopyFence = d3d12device.Get()->CreateFence(); - - this.computeCommandAllocatorPool = new ID3D12CommandAllocatorPool(D3D12_COMMAND_LIST_TYPE_COMPUTE); - this.copyCommandAllocatorPool = new ID3D12CommandAllocatorPool(D3D12_COMMAND_LIST_TYPE_COPY); - this.shaderResourceViewDescriptorAllocator = new DescriptorAllocator2(d3d12device); - - Name = new string((char*)dxgiDescription1->Description); - MemorySize = dxgiDescription1->DedicatedVideoMemory; - - var d3D12Options1Data = d3d12device.Get()->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1); - - ComputeUnits = d3D12Options1Data.TotalLaneCount; - WavefrontSize = d3D12Options1Data.WaveLaneCountMin; - } - - /// - /// Gets the name of the current instance. - /// - public string Name { get; } - - /// - /// Gets the size of the dedicated video memory for the current instance. - /// - public nuint MemorySize { get; } - - /// - /// Gets the number of total lanes on the current device (eg. CUDA cores on an nVidia GPU). - /// - public uint ComputeUnits { get; } - - /// - /// Gets the number of lanes in a SIMD wave on the current device (also known as "wavefront size" or "warp width"). - /// - public uint WavefrontSize { get; } - - /// - /// Gets the underlying wrapped by the current instance. - /// - internal ID3D12Device* D3D12Device => this.d3D12Device; - - /// - internal void AllocateShaderResourceViewDescriptorHandles( - out D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandle, - out D3D12_GPU_DESCRIPTOR_HANDLE d3d12GpuDescriptorHandle) - { - this.shaderResourceViewDescriptorAllocator.Allocate(out d3d12CpuDescriptorHandle, out d3d12GpuDescriptorHandle); - } - - /// - /// The type of command allocator to rent. - internal ComPtr GetCommandAllocator(D3D12_COMMAND_LIST_TYPE d3d12CommandListType) - { - return d3d12CommandListType switch - { - D3D12_COMMAND_LIST_TYPE_COMPUTE => this.computeCommandAllocatorPool.GetCommandAllocator(this.d3D12Device, this.d3D12ComputeFence), - D3D12_COMMAND_LIST_TYPE_COPY => this.computeCommandAllocatorPool.GetCommandAllocator(this.d3D12Device, this.d3D12CopyFence), - _ => throw null! - }; - } - - /// - /// Sets the descriptor heap for a given instance. - /// - /// The input instance to use. - internal void SetDescriptorHeapForCommandList(ID3D12GraphicsCommandList* d3D12GraphicsCommandList) - { - ID3D12DescriptorHeap* d3D12DescriptorHeap = this.shaderResourceViewDescriptorAllocator.D3D12DescriptorHeap; - - d3D12GraphicsCommandList->SetDescriptorHeaps(1, &d3D12DescriptorHeap); - } - - /// - /// Executes a given command list and waits for the operation to be completed. - /// - /// The input to execute. - internal void ExecuteCommandList(ref CommandList2 commandList) - { - ref readonly ID3D12CommandAllocatorPool commandAllocatorPool = ref Unsafe.NullRef(); - ID3D12CommandQueue* d3D12CommandQueue; - ID3D12Fence* d3D12Fence; - ulong d3D12FenceValue; - - // Get the target command queue, fence and pool for the list type - switch (commandList.D3d12CommandListType) - { - case D3D12_COMMAND_LIST_TYPE_COMPUTE: - commandAllocatorPool = ref this.computeCommandAllocatorPool; - d3D12CommandQueue = this.d3D12ComputeCommandQueue; - d3D12Fence = this.d3D12ComputeFence; - d3D12FenceValue = this.nextD3D12ComputeFenceValue++; - break; - case D3D12_COMMAND_LIST_TYPE_COPY: - commandAllocatorPool = ref this.copyCommandAllocatorPool; - d3D12CommandQueue = this.d3D12CopyCommandQueue; - d3D12Fence = this.d3D12CopyFence; - d3D12FenceValue = this.nextD3D12CopyFenceValue++; - break; - default: throw null!; - } - - // Execute the command list and signal to the target fence - d3D12CommandQueue->ExecuteCommandLists(1, commandList.GetD3D12CommandListAddressOf()); - - d3D12CommandQueue->Signal(d3D12Fence, d3D12FenceValue).Assert(); - - // If the fence value hasn't been reached, wait until the operation completes - if (d3D12FenceValue > d3D12Fence->GetCompletedValue()) - { - d3D12Fence->SetEventOnCompletion(d3D12FenceValue, default).Assert(); - } - - // Enqueue the command allocator pool so that it can be reused later - commandAllocatorPool.Enqueue(commandList.DetachD3D12CommandAllocator()); - } - - /// - protected override void OnDispose() - { - this.d3D12Device.Dispose(); - this.d3D12ComputeCommandQueue.Dispose(); - this.d3D12CopyCommandQueue.Dispose(); - this.d3D12ComputeFence.Dispose(); - this.d3D12CopyFence.Dispose(); - this.computeCommandAllocatorPool.Dispose(); - this.copyCommandAllocatorPool.Dispose(); - this.shaderResourceViewDescriptorAllocator.Dispose(); - } - } -} diff --git a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs index b09990a0..bf8ca58f 100644 --- a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs @@ -1,46 +1,134 @@ -using System.Collections.Generic; +using System; +using System.Diagnostics; using System.Diagnostics.Contracts; -using Vortice.Direct3D; -using Vortice.Direct3D12; -using Vortice.DXGI; +using TerraFX.Interop; +using FX = TerraFX.Interop.Windows; +using HRESULT = System.Int32; namespace ComputeSharp.Graphics.Helpers { /// - /// A with methods to inspect the available devices on the current machine + /// A with methods to inspect the available devices on the current machine. /// internal static class DeviceHelper { /// - /// Gets a collection of all the supported devices on the current machine + /// Gets whether or not there is a default device available, without creating it. /// - /// The collection of objects with support for DX12.1 + /// Whether or not there is a device supporting at least DX12.0. [Pure] - public static IReadOnlyList<(ID3D12Device, AdapterDescription)> QueryAllSupportedDevices() + public static unsafe bool IsDefaultDeviceAvailable() { - if (!DXGI.CreateDXGIFactory1(out IDXGIFactory1 factory).Success) return new (ID3D12Device, AdapterDescription)[0]; - try + DXGI_ADAPTER_DESC1 dxgiDescription1; + + return TryGetDefaultDevice(null, &dxgiDescription1); + } + + /// + /// Gets the default instance. + /// + /// The default instance supporting at least DX12.0. + /// Thrown when a default device is not available. + public static unsafe GraphicsDevice GetDefaultDevice() + { + using ComPtr d3d12device = default; + + DXGI_ADAPTER_DESC1 dxgiDescription1; + + if (TryGetDefaultDevice(d3d12device.GetAddressOf(), &dxgiDescription1)) { - List<(ID3D12Device, AdapterDescription)> devices = new List<(ID3D12Device, AdapterDescription)>(); + return new GraphicsDevice(d3d12device.Move(), &dxgiDescription1); + } - int i = 0; + static GraphicsDevice Throw() + { + throw new NotSupportedException("There isn't a supported GPU device on the current machine"); + } - while (factory.EnumAdapters1(i++, out IDXGIAdapter1? adapter).Success && !(adapter is null)) + return Throw(); + } + + /// + /// Tries to check or create a default object. + /// + /// A pointer to the object to create, or . + /// A pointer to the value for the device found. + /// Whether a default device was found with the requested feature level. + public static unsafe bool TryGetDefaultDevice(ID3D12Device** d3d12device, DXGI_ADAPTER_DESC1* dxgiDescription1) + { + using ComPtr dxgiFactory4 = default; + + Guid dxgiFactory4Guid = FX.IID_IDXGIFactory4; + + EnableDebugMode(); + + FX.CreateDXGIFactory2(IDXGIFactoryCreationFlags, &dxgiFactory4Guid, dxgiFactory4.GetVoidAddressOf()).Assert(); + + uint i = 0; + + while (true) + { + using ComPtr dxgiAdapter1 = default; + + HRESULT enumAdapters1Result = dxgiFactory4.Get()->EnumAdapters1(i++, dxgiAdapter1.GetAddressOf()); + + if (enumAdapters1Result == FX.DXGI_ERROR_NOT_FOUND) { - if (adapter.Description.DedicatedVideoMemory == 0) continue; - - if (D3D12.D3D12CreateDevice(adapter, FeatureLevel.Level_12_0, out ID3D12Device device).Success) - { - devices.Add((device, adapter.Description)); - } + return false; } - return devices; + enumAdapters1Result.Assert(); + + dxgiAdapter1.Get()->GetDesc1(dxgiDescription1).Assert(); + + if (dxgiDescription1->DedicatedVideoMemory == 0) continue; + + Guid d3d12DeviceGuid = FX.IID_ID3D12Device; + + HRESULT createDeviceResult = FX.D3D12CreateDevice( + dxgiAdapter1.Upcast().Get(), + D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_12_0, + &d3d12DeviceGuid, + (void**)d3d12device); + + if (FX.SUCCEEDED(createDeviceResult)) + { + return true; + } } - finally + } + + /// + /// The creation flags for instances. + /// + private const uint IDXGIFactoryCreationFlags = +#if DEBUG + FX.DXGI_CREATE_FACTORY_DEBUG; +#else + 0; +#endif + + /// + /// Enables the debug layer for DirectX APIs. + /// + [Conditional("DEBUG")] + private static unsafe void EnableDebugMode() + { + using ComPtr d3D12Debug = default; + using ComPtr d3D12Debug1 = default; + + Guid d3D12DebugGuid = FX.IID_ID3D12Debug; + + FX.D3D12GetDebugInterface(&d3D12DebugGuid, d3D12Debug.GetVoidAddressOf()).Assert(); + + d3D12Debug.Get()->EnableDebugLayer(); + + Guid d3D12Debug1Guid = FX.IID_ID3D12Debug1; + + if (FX.SUCCEEDED(d3D12Debug.CopyTo(d3D12Debug1.GetAddressOf()))) { - // Explicit using statement - factory?.Dispose(); + d3D12Debug1.Get()->SetEnableGPUBasedValidation(FX.TRUE); + d3D12Debug1.Get()->SetEnableSynchronizedCommandQueueValidation(FX.TRUE); } } } diff --git a/src/ComputeSharp.Graphics/Helpers/DeviceHelper2.cs b/src/ComputeSharp.Graphics/Helpers/DeviceHelper2.cs deleted file mode 100644 index dea096a2..00000000 --- a/src/ComputeSharp.Graphics/Helpers/DeviceHelper2.cs +++ /dev/null @@ -1,135 +0,0 @@ -using System; -using System.Diagnostics; -using System.Diagnostics.Contracts; -using TerraFX.Interop; -using FX = TerraFX.Interop.Windows; -using HRESULT = System.Int32; - -namespace ComputeSharp.Graphics.Helpers -{ - /// - /// A with methods to inspect the available devices on the current machine. - /// - internal static class DeviceHelper2 - { - /// - /// Gets whether or not there is a default device available, without creating it. - /// - /// Whether or not there is a device supporting at least DX12.0. - [Pure] - public static unsafe bool IsDefaultDeviceAvailable() - { - DXGI_ADAPTER_DESC1 dxgiDescription1; - - return TryGetDefaultDevice(null, &dxgiDescription1); - } - - /// - /// Gets the default instance. - /// - /// The default instance supporting at least DX12.0. - /// Thrown when a default device is not available. - public static unsafe GraphicsDevice2 GetDefaultDevice() - { - using ComPtr d3d12device = default; - - DXGI_ADAPTER_DESC1 dxgiDescription1; - - if (TryGetDefaultDevice(d3d12device.GetAddressOf(), &dxgiDescription1)) - { - return new GraphicsDevice2(d3d12device.Move(), &dxgiDescription1); - } - - static GraphicsDevice2 Throw() - { - throw new NotSupportedException("There isn't a supported GPU device on the current machine"); - } - - return Throw(); - } - - /// - /// Tries to check or create a default object. - /// - /// A pointer to the object to create, or . - /// A pointer to the value for the device found. - /// Whether a default device was found with the requested feature level. - public static unsafe bool TryGetDefaultDevice(ID3D12Device** d3d12device, DXGI_ADAPTER_DESC1* dxgiDescription1) - { - using ComPtr dxgiFactory4 = default; - - Guid dxgiFactory4Guid = FX.IID_IDXGIFactory4; - - EnableDebugMode(); - - FX.CreateDXGIFactory2(IDXGIFactoryCreationFlags, &dxgiFactory4Guid, dxgiFactory4.GetVoidAddressOf()).Assert(); - - uint i = 0; - - while (true) - { - using ComPtr dxgiAdapter1 = default; - - HRESULT enumAdapters1Result = dxgiFactory4.Get()->EnumAdapters1(i++, dxgiAdapter1.GetAddressOf()); - - if (enumAdapters1Result == FX.DXGI_ERROR_NOT_FOUND) - { - return false; - } - - enumAdapters1Result.Assert(); - - dxgiAdapter1.Get()->GetDesc1(dxgiDescription1).Assert(); - - if (dxgiDescription1->DedicatedVideoMemory == 0) continue; - - Guid d3d12DeviceGuid = FX.IID_ID3D12Device; - - HRESULT createDeviceResult = FX.D3D12CreateDevice( - dxgiAdapter1.Upcast().Get(), - D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_12_0, - &d3d12DeviceGuid, - (void**)d3d12device); - - if (FX.SUCCEEDED(createDeviceResult)) - { - return true; - } - } - } - - /// - /// The creation flags for instances. - /// - private const uint IDXGIFactoryCreationFlags = -#if DEBUG - FX.DXGI_CREATE_FACTORY_DEBUG; -#else - 0; -#endif - - /// - /// Enables the debug layer for DirectX APIs. - /// - [Conditional("DEBUG")] - private static unsafe void EnableDebugMode() - { - using ComPtr d3D12Debug = default; - using ComPtr d3D12Debug1 = default; - - Guid d3D12DebugGuid = FX.IID_ID3D12Debug; - - FX.D3D12GetDebugInterface(&d3D12DebugGuid, d3D12Debug.GetVoidAddressOf()).Assert(); - - d3D12Debug.Get()->EnableDebugLayer(); - - Guid d3D12Debug1Guid = FX.IID_ID3D12Debug1; - - if (FX.SUCCEEDED(d3D12Debug.CopyTo(d3D12Debug1.GetAddressOf()))) - { - d3D12Debug1.Get()->SetEnableGPUBasedValidation(FX.TRUE); - d3D12Debug1.Get()->SetEnableSynchronizedCommandQueueValidation(FX.TRUE); - } - } - } -} diff --git a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj index dd53abda..c4e61ed8 100644 --- a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj +++ b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj @@ -10,7 +10,6 @@ - diff --git a/src/ComputeSharp.Shaders/ShaderRunner2{T}.cs b/src/ComputeSharp.Shaders/ShaderRunner2{T}.cs deleted file mode 100644 index f1a4d0d1..00000000 --- a/src/ComputeSharp.Shaders/ShaderRunner2{T}.cs +++ /dev/null @@ -1,204 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Runtime.CompilerServices; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Commands; -using ComputeSharp.Shaders.Extensions; -using ComputeSharp.Shaders.Renderer; -using ComputeSharp.Shaders.Renderer.Models; -using ComputeSharp.Shaders.Translation; -using ComputeSharp.Shaders.Translation.Interop; -using ComputeSharp.Shaders.Translation.Models; -using TerraFX.Interop; -using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; - -namespace ComputeSharp.Shaders -{ - /// - /// A with helper methods to support . - /// This type is primarily needed to avoid having fields being repeated per generic instantiation. - /// - internal static class ShaderRunner2 - { - /// - /// A thread-safe map of reusable GPU buffers for captured locals. - /// - [ThreadStatic] - private static ConditionalWeakTable>? variablesBuffers; - - /// - /// Gets the reusable instance for a shader invocation. - /// - /// The to use to run the shader. - /// The reusable instance to populate. - [Pure] - public static ConstantBuffer2 GetVariablesBuffer(GraphicsDevice2 device) - { - ConditionalWeakTable> map = variablesBuffers ??= new(); - - return map.GetValue(device, gpu => new ConstantBuffer2(gpu, 4096)); - } - } - - /// - /// A responsible for performing all the necessary operations to compile and run a compute shader. - /// - /// The type of compute shader to run. - internal static class ShaderRunner2 - where T : struct, IComputeShader - { - /// - /// The mapping used to cache and reuse compiled shaders. - /// - private static readonly Dictionary> ShadersCache = new(); - - /// - /// Compiles and runs the input shader on a target instance, with the specified parameters. - /// - /// 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 input instance representing the compute shader to run. - public static void Run(GraphicsDevice2 device, int x, int y, int z, in T shader) - { - // Calculate the optimized thread num values - int threadsX, threadsY = 1, threadsZ = 1; - if (y == 1 && z == 1) threadsX = (int)device.WavefrontSize; - else if (z == 1) threadsX = threadsY = 8; - else threadsX = threadsY = threadsZ = 4; - - Run(device, x, y, z, threadsX, threadsY, threadsZ, shader); - } - - /// - /// Compiles and runs the input shader on a target instance, with the specified parameters. - /// - /// 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 Run( - GraphicsDevice2 device, - int x, int y, int z, - int threadsX, int threadsY, int threadsZ, - in T shader) - { - // Create the shader key - ShaderKey key = new(ShaderHashCodeProvider.GetHashCode(shader), threadsX, threadsY, threadsZ); - CachedShader2 shaderData; - PipelineData? pipelineData; - - lock (ShadersCache) - { - // Get or preload the shader - if (!ShadersCache.TryGetValue(key, out shaderData)) - { - LoadShader(threadsX, threadsY, threadsZ, shader, out shaderData); - - // Cache for later use - ShadersCache.Add(key, shaderData); - } - - // Create the reusable pipeline state - if (!shaderData.CachedPipelines.TryGetValue(device, out pipelineData)) - { - CreatePipelineData(device, shaderData, out pipelineData); - } - } - - // Create the commands list and set the pipeline state - using CommandList2 commandList = new(device, D3D12_COMMAND_LIST_TYPE_COMPUTE); - - commandList.SetPipelineData(pipelineData); - - // Extract the dispatch data for the shader invocation - using DispatchData2 dispatchData = shaderData.Loader.GetDispatchData(shader, x, y, z); - - // Load the captured buffers - ReadOnlySpan resources = dispatchData.Resources; - - for (int i = 0; i < resources.Length; i++) - { - commandList.SetComputeRootDescriptorTable(i + 1, resources[i]); - } - - // Initialize the loop targets and the captured values - ConstantBuffer2 variablesBuffer = ShaderRunner2.GetVariablesBuffer(device); - - variablesBuffer.SetData(dispatchData.Variables); - - commandList.SetComputeRootDescriptorTable(0, variablesBuffer.D3D12GpuDescriptorHandle); - - // Calculate the dispatch values - int - groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1), - groupsY = Math.DivRem(y, threadsY, out int modY) + (modY == 0 ? 0 : 1), - groupsZ = Math.DivRem(z, threadsZ, out int modZ) + (modZ == 0 ? 0 : 1); - - // Dispatch and wait for completion - commandList.Dispatch(groupsX, groupsY, groupsZ); - commandList.ExecuteAndWaitForCompletion(); - } - - /// - /// 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 void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader2 shaderData) - { - // Load the input shader - ShaderLoader2 shaderLoader = ShaderLoader2.Load(shader); - - // Render the loaded shader - string shaderSource = ShaderRenderer.Instance.Render(new ShaderInfo - { - BuffersList = shaderLoader.HslsBuffersInfo, - FieldsList = shaderLoader.FieldsInfo, - NumThreadsX = threadsX, - NumThreadsY = threadsY, - NumThreadsZ = threadsZ, - ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName, - ShaderBody = shaderLoader.MethodBody, - FunctionsList = shaderLoader.FunctionsInfo, - LocalFunctionsList = shaderLoader.LocalFunctionsInfo - }); - - // Compile the loaded shader to HLSL bytecode - IDxcBlobObject shaderBytecode = new(ShaderCompiler2.CompileShader(shaderSource)); - - // Get the cached shader data - shaderData = new CachedShader2(shaderLoader, shaderBytecode); - } - - /// - /// 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. - [MethodImpl(MethodImplOptions.NoInlining)] - private static unsafe void CreatePipelineData(GraphicsDevice2 device, in CachedShader2 shaderData, out PipelineData pipelineData) - { - using ComPtr d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12DescriptorRanges1); - - D3D12_SHADER_BYTECODE d3D12ShaderBytecode = new((ID3DBlob*)shaderData.Bytecode.DxcBlob); - - using ComPtr d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), d3D12ShaderBytecode); - - pipelineData = new PipelineData(d3D12RootSignature.Move(), d3D12PipelineState.Move()); - - shaderData.CachedPipelines.Add(device, pipelineData); - } - } -} diff --git a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs index 7d1a6e81..9586974d 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs @@ -3,14 +3,15 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Graphics.Commands; +using ComputeSharp.Shaders.Extensions; using ComputeSharp.Shaders.Renderer; using ComputeSharp.Shaders.Renderer.Models; using ComputeSharp.Shaders.Translation; +using ComputeSharp.Shaders.Translation.Interop; using ComputeSharp.Shaders.Translation.Models; -using Vortice.Direct3D12; -using CommandList = ComputeSharp.Graphics.Commands.CommandList; -using PipelineState = ComputeSharp.Graphics.Commands.PipelineState; +using TerraFX.Interop; +using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; namespace ComputeSharp.Shaders { @@ -21,45 +22,50 @@ namespace ComputeSharp.Shaders internal static class ShaderRunner { /// - /// A thread-safe map of reusable GPU buffers for captured locals + /// A thread-safe map of reusable GPU buffers for captured locals. /// [ThreadStatic] private static ConditionalWeakTable>? variablesBuffers; /// - /// Gets the reusable instance for a shader invocation + /// Gets the reusable instance for a shader invocation. /// - /// The to use to run the shader - /// The reusable instance to populate + /// The to use to run the shader. + /// The reusable instance to populate. [Pure] public static ConstantBuffer GetVariablesBuffer(GraphicsDevice device) { - var map = variablesBuffers ??= new ConditionalWeakTable>(); + ConditionalWeakTable> map = variablesBuffers ??= new(); return map.GetValue(device, gpu => new ConstantBuffer(gpu, 4096)); } } /// - /// A responsible for performing all the necessary operations to compile and run a compute shader + /// A responsible for performing all the necessary operations to compile and run a compute shader. /// - /// The type of compute shader to run + /// The type of compute shader to run. internal static class ShaderRunner where T : struct, IComputeShader { /// - /// Compiles and runs the input shader on a target instance, with the specified parameters + /// The mapping used to cache and reuse compiled shaders. /// - /// 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 input instance representing the compute shader to run + private static readonly Dictionary> ShadersCache = new(); + + /// + /// Compiles and runs the input shader on a target instance, with the specified parameters. + /// + /// 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 input instance representing the compute shader to run. public static void Run(GraphicsDevice device, int x, int y, int z, in T shader) { // Calculate the optimized thread num values int threadsX, threadsY = 1, threadsZ = 1; - if (y == 1 && z == 1) threadsX = device.WavefrontSize; + if (y == 1 && z == 1) threadsX = (int)device.WavefrontSize; else if (z == 1) threadsX = threadsY = 8; else threadsX = threadsY = threadsZ = 4; @@ -67,21 +73,16 @@ namespace ComputeSharp.Shaders } /// - /// The mapping used to cache and reuse compiled shaders + /// Compiles and runs the input shader on a target instance, with the specified parameters. /// - private static readonly Dictionary> ShadersCache = new Dictionary>(); - - /// - /// Compiles and runs the input shader on a target instance, with the specified parameters - /// - /// 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 + /// 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 Run( GraphicsDevice device, int x, int y, int z, @@ -89,9 +90,9 @@ namespace ComputeSharp.Shaders in T shader) { // Create the shader key - ShaderKey key = new ShaderKey(ShaderHashCodeProvider.GetHashCode(shader), threadsX, threadsY, threadsZ); + ShaderKey key = new(ShaderHashCodeProvider.GetHashCode(shader), threadsX, threadsY, threadsZ); CachedShader shaderData; - PipelineState? pipelineState; + PipelineData? pipelineData; lock (ShadersCache) { @@ -105,21 +106,23 @@ namespace ComputeSharp.Shaders } // Create the reusable pipeline state - if (!shaderData.CachedPipelines.TryGetValue(device, out pipelineState)) + if (!shaderData.CachedPipelines.TryGetValue(device, out pipelineData)) { - CreatePipelineState(device, shaderData, out pipelineState); + CreatePipelineData(device, shaderData, out pipelineData); } } // Create the commands list and set the pipeline state - using CommandList commandList = new CommandList(device, CommandListType.Compute); - commandList.SetPipelineState(pipelineState); + using CommandList commandList = new(device, D3D12_COMMAND_LIST_TYPE_COMPUTE); + + commandList.SetPipelineData(pipelineData); // Extract the dispatch data for the shader invocation using DispatchData dispatchData = shaderData.Loader.GetDispatchData(shader, x, y, z); // Load the captured buffers - Span resources = dispatchData.Resources; + ReadOnlySpan resources = dispatchData.Resources; + for (int i = 0; i < resources.Length; i++) { commandList.SetComputeRootDescriptorTable(i + 1, resources[i]); @@ -127,8 +130,10 @@ namespace ComputeSharp.Shaders // Initialize the loop targets and the captured values ConstantBuffer variablesBuffer = ShaderRunner.GetVariablesBuffer(device); + variablesBuffer.SetData(dispatchData.Variables); - commandList.SetComputeRootDescriptorTable(0, variablesBuffer); + + commandList.SetComputeRootDescriptorTable(0, variablesBuffer.D3D12GpuDescriptorHandle); // Calculate the dispatch values int @@ -142,13 +147,13 @@ namespace ComputeSharp.Shaders } /// - /// Loads a shader with the specified parameters + /// 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 + /// 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 void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader shaderData) { @@ -158,41 +163,42 @@ namespace ComputeSharp.Shaders // Render the loaded shader string shaderSource = ShaderRenderer.Instance.Render(new ShaderInfo { - BuffersList = shaderLoader.BuffersList, - FieldsList = shaderLoader.FieldsList, + BuffersList = shaderLoader.HslsBuffersInfo, + FieldsList = shaderLoader.FieldsInfo, NumThreadsX = threadsX, NumThreadsY = threadsY, NumThreadsZ = threadsZ, ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName, ShaderBody = shaderLoader.MethodBody, - FunctionsList = shaderLoader.FunctionsList, - LocalFunctionsList = shaderLoader.LocalFunctionsList + FunctionsList = shaderLoader.FunctionsInfo, + LocalFunctionsList = shaderLoader.LocalFunctionsInfo }); // Compile the loaded shader to HLSL bytecode - ShaderBytecode shaderBytecode = ShaderCompiler.CompileShader(shaderSource); + IDxcBlobObject shaderBytecode = new(ShaderCompiler.CompileShader(shaderSource)); // Get the cached shader data shaderData = new CachedShader(shaderLoader, shaderBytecode); } /// - /// Creates and caches a instance for a given shader + /// 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 to use to run the shader. + /// The instance with the data on the loaded shader. + /// The resulting instance to use to run the shader. [MethodImpl(MethodImplOptions.NoInlining)] - private static void CreatePipelineState(GraphicsDevice device, in CachedShader shaderData, out PipelineState pipelineState) + private static unsafe void CreatePipelineData(GraphicsDevice device, in CachedShader shaderData, out PipelineData pipelineData) { - // Create the root signature for the pipeline and get the pipeline state - RootSignatureDescription1 rootSignatureDescription = new RootSignatureDescription1(RootSignatureFlags.None, shaderData.Loader.RootParameters); - VersionedRootSignatureDescription versionedRootSignatureDescription = new VersionedRootSignatureDescription(rootSignatureDescription); - ID3D12RootSignature rootSignature = device.CreateRootSignature(versionedRootSignatureDescription); - pipelineState = new PipelineState(device, rootSignature, shaderData.Bytecode); + using ComPtr d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12DescriptorRanges1); - // Cache the pipeline state for the target device - shaderData.CachedPipelines.Add(device, pipelineState); + D3D12_SHADER_BYTECODE d3D12ShaderBytecode = new((ID3DBlob*)shaderData.Bytecode.DxcBlob); + + using ComPtr d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), d3D12ShaderBytecode); + + pipelineData = new PipelineData(d3D12RootSignature.Move(), d3D12PipelineState.Move()); + + shaderData.CachedPipelines.Add(device, pipelineData); } } } diff --git a/src/ComputeSharp.Shaders/Translation/Models/CachedShader2{T}.cs b/src/ComputeSharp.Shaders/Translation/Models/CachedShader2{T}.cs index 2e87756c..9c65823a 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/CachedShader2{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/CachedShader2{T}.cs @@ -9,13 +9,13 @@ namespace ComputeSharp.Shaders.Translation.Models /// A that contains info on a cached shader. /// /// The type of compute shader in use. - internal readonly struct CachedShader2 + internal readonly struct CachedShader where T : struct, IComputeShader { /// - /// The instance with the shader metadata. + /// The instance with the shader metadata. /// - public readonly ShaderLoader2 Loader; + public readonly ShaderLoader Loader; /// /// The compiled shader bytecode. @@ -25,14 +25,14 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// The map of cached instances for each GPU in use. /// - public readonly ConditionalWeakTable CachedPipelines; + public readonly ConditionalWeakTable CachedPipelines; /// /// Creates a new instance with the specified parameters. /// /// The instance with the shader metadata. /// The compiled shader bytecode. - public CachedShader2(ShaderLoader2 loader, IDxcBlobObject bytecode) + public CachedShader(ShaderLoader loader, IDxcBlobObject bytecode) { Loader = loader; Bytecode = bytecode; diff --git a/src/ComputeSharp.Shaders/Translation/Models/CachedShader{T}.cs b/src/ComputeSharp.Shaders/Translation/Models/CachedShader{T}.cs deleted file mode 100644 index c92a96e4..00000000 --- a/src/ComputeSharp.Shaders/Translation/Models/CachedShader{T}.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System.Runtime.CompilerServices; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Commands; -using Vortice.Direct3D12; - -namespace ComputeSharp.Shaders.Translation.Models -{ - /// - /// A that contains info on a cached shader - /// - /// The type of compute shader in use - internal readonly struct CachedShader - where T : struct, IComputeShader - { - /// - /// The instance with the shader metadata - /// - public readonly ShaderLoader Loader; - - /// - /// The compiled shader bytecode - /// - public readonly ShaderBytecode Bytecode; - - /// - /// The map of cached instances for each GPU in use. - /// - public readonly ConditionalWeakTable CachedPipelines; - - /// - /// Creates a new instance with the specified parameters - /// - /// The instance with the shader metadata - /// The compiled shader bytecode - public CachedShader(ShaderLoader loader, ShaderBytecode bytecode) - { - Loader = loader; - Bytecode = bytecode; - CachedPipelines = new ConditionalWeakTable(); - } - } -} diff --git a/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs index 31aa6754..2f40566e 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs @@ -3,80 +3,86 @@ using System.Buffers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ComputeSharp.Graphics.Buffers.Abstract; +using TerraFX.Interop; namespace ComputeSharp.Shaders.Translation.Models { /// - /// A that contains all the captured data to dispatch a shader + /// A that contains all the captured data to dispatch a shader. /// internal readonly ref struct DispatchData { /// - /// The array with the captured buffers + /// The array with the captured buffers. /// - private readonly GraphicsResource[] ResourcesArray; + private readonly D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray; /// - /// The number of instances in + /// The number of instances in . /// - private readonly int ResourcesCount; + private readonly int resourcesCount; /// - /// The array with all the captured variables, with proper padding + /// The array with all the captured variables, with proper padding. /// - private readonly byte[] VariablesArray; + private readonly byte[] variablesArray; /// - /// The actual size in bytes to use from + /// The actual size in bytes to use from . /// - private readonly int VariablesByteSize; + private readonly int variablesByteSize; /// - /// Creates a new instance with the specified parameters + /// Creates a new instance with the specified parameters. /// - /// The array with the captured buffers - /// The number of instances in - /// The array with all the captured variables, with proper padding - /// The actual size in bytes to use from - public DispatchData(GraphicsResource[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize) + /// The array with the captured buffers. + /// The number of instances in . + /// The array with all the captured variables, with proper padding. + /// The actual size in bytes to use from . + public DispatchData(D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize) { - ResourcesArray = resourcesArray; - VariablesArray = variablesArray; - ResourcesCount = resourcesCount; - VariablesByteSize = variablesByteSize; + this.resourcesArray = resourcesArray; + this.variablesArray = variablesArray; + this.resourcesCount = resourcesCount; + this.variablesByteSize = variablesByteSize; } /// - /// Gets a with all the captured buffers + /// Gets a with all the captured buffers. /// - public Span Resources - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => ResourcesArray.AsSpan(0, ResourcesCount); - } - - /// - /// Gets a with the padded data representing all the captured variables - /// - public Span Variables + public ReadOnlySpan Resources { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - ref Int4 r = ref Unsafe.As(ref VariablesArray[0]); - bool mod = (VariablesByteSize & 15) > 0; - int length = VariablesByteSize / 4 + Unsafe.As(ref mod); - return MemoryMarshal.CreateSpan(ref r, length); + ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray); + + return MemoryMarshal.CreateReadOnlySpan(ref r0, this.resourcesCount); } } /// - /// Implements the method and returns the rented buffers + /// Gets a with the padded data representing all the captured variables. /// + public ReadOnlySpan Variables + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + ref byte r0 = ref MemoryMarshal.GetArrayDataReference(this.variablesArray); + ref Int4 r1 = ref Unsafe.As(ref r0); + bool mod = (this.variablesByteSize & 15) > 0; + int length = variablesByteSize / 4 + Unsafe.As(ref mod); + + return MemoryMarshal.CreateReadOnlySpan(ref r1, length); + } + } + + /// public void Dispose() { - ArrayPool.Shared.Return(ResourcesArray, true); - ArrayPool.Shared.Return(VariablesArray); + ArrayPool.Shared.Return(this.resourcesArray); + ArrayPool.Shared.Return(this.variablesArray); } } } diff --git a/src/ComputeSharp.Shaders/Translation/Models/DispatchData2.cs b/src/ComputeSharp.Shaders/Translation/Models/DispatchData2.cs deleted file mode 100644 index 0034c4fd..00000000 --- a/src/ComputeSharp.Shaders/Translation/Models/DispatchData2.cs +++ /dev/null @@ -1,88 +0,0 @@ -using System; -using System.Buffers; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using ComputeSharp.Graphics.Buffers.Abstract; -using TerraFX.Interop; - -namespace ComputeSharp.Shaders.Translation.Models -{ - /// - /// A that contains all the captured data to dispatch a shader. - /// - internal readonly ref struct DispatchData2 - { - /// - /// The array with the captured buffers. - /// - private readonly D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray; - - /// - /// The number of instances in . - /// - private readonly int resourcesCount; - - /// - /// The array with all the captured variables, with proper padding. - /// - private readonly byte[] variablesArray; - - /// - /// The actual size in bytes to use from . - /// - private readonly int variablesByteSize; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The array with the captured buffers. - /// The number of instances in . - /// The array with all the captured variables, with proper padding. - /// The actual size in bytes to use from . - public DispatchData2(D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize) - { - this.resourcesArray = resourcesArray; - this.variablesArray = variablesArray; - this.resourcesCount = resourcesCount; - this.variablesByteSize = variablesByteSize; - } - - /// - /// Gets a with all the captured buffers. - /// - public ReadOnlySpan Resources - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray); - - return MemoryMarshal.CreateReadOnlySpan(ref r0, this.resourcesCount); - } - } - - /// - /// Gets a with the padded data representing all the captured variables. - /// - public ReadOnlySpan Variables - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - ref byte r0 = ref MemoryMarshal.GetArrayDataReference(this.variablesArray); - ref Int4 r1 = ref Unsafe.As(ref r0); - bool mod = (this.variablesByteSize & 15) > 0; - int length = variablesByteSize / 4 + Unsafe.As(ref mod); - - return MemoryMarshal.CreateReadOnlySpan(ref r1, length); - } - } - - /// - public void Dispose() - { - ArrayPool.Shared.Return(this.resourcesArray); - ArrayPool.Shared.Return(this.variablesArray); - } - } -} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs index f7f45eab..95413d0e 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs @@ -1,42 +1,140 @@ -using System.Diagnostics.Contracts; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; using ComputeSharp.Exceptions; -using Vortice.Direct3D12; -using Vortice.Dxc; +using ComputeSharp.Graphics.Helpers; +using TerraFX.Interop; +using FX = TerraFX.Interop.Windows; namespace ComputeSharp.Shaders.Translation { /// - /// A that uses the APIs to compile compute shaders + /// A that uses the DXC APIs to compile compute shaders. /// - internal static class ShaderCompiler + internal static unsafe class ShaderCompiler { /// - /// The instance to use to create the bytecode for HLSL sources + /// The instance to use to create the bytecode for HLSL sources. /// - private static readonly IDxcLibrary Library = Dxc.CreateDxcLibrary(); + private static readonly ComPtr DxcCompiler; /// - /// Compiles a new HLSL shader from the input source code + /// The instance to use to work with . /// - /// The HLSL source code to compile - /// The bytecode for the compiled shader - [Pure] - public static ShaderBytecode CompileShader(string source) + private static readonly ComPtr DxcLibrary; + + /// + /// The instance used to compile shaders with . + /// + private static readonly ComPtr DxcIncludeHandler; + + /// + /// Initializes , and + /// + static ShaderCompiler() { - var result = DxcCompiler.Compile(DxcShaderStage.ComputeShader, source, "CSMain", string.Empty, new DxcCompilerOptions { ShaderModel = DxcShaderModel.Model6_1 }); + using ComPtr dxcCompiler = default; + using ComPtr dxcLibrary = default; + using ComPtr dxcIncludeHandler = default; - // Get the compiled bytecode in case of success - if (result.GetStatus() == 0) + Guid dxcCompilerCLGuid = FX.CLSID_DxcCompiler; + Guid dxcCompilerGuid = FX.IID_IDxcCompiler; + Guid dxcLibraryCLGuid = FX.CLSID_DxcLibrary; + Guid dxcLibraryGuid = FX.IID_IDxcLibrary; + + FX.DxcCreateInstance(&dxcCompilerCLGuid, &dxcCompilerGuid, dxcCompiler.GetVoidAddressOf()).Assert(); + FX.DxcCreateInstance(&dxcLibraryCLGuid, &dxcLibraryGuid, dxcLibrary.GetVoidAddressOf()).Assert(); + + dxcLibrary.Get()->CreateIncludeHandler(dxcIncludeHandler.GetAddressOf()).Assert(); + + DxcCompiler = dxcCompiler; + DxcLibrary = dxcLibrary; + DxcIncludeHandler = dxcIncludeHandler; + } + + /// + /// Compiles a new HLSL shader from the input source code. + /// + /// The HLSL source code to compile. + /// The bytecode for the compiled shader. + [Pure] + public static ComPtr CompileShader(ReadOnlySpan source) + { + using ComPtr dxcBlobEncoding = default; + using ComPtr dxcOperationResult = default; + using ComPtr dxcBlobBytecode = default; + + // Get the encoded blob from the source code + fixed (char* p = source) { - IDxcBlob blob = result.GetResult(); - byte[] bytecode = Dxc.GetBytesFromBlob(blob); - - return bytecode; + DxcLibrary.Get()->CreateBlobWithEncodingOnHeapCopy( + p, + (uint)source.Length * 2, + 1200, + dxcBlobEncoding.GetAddressOf()).Assert(); } - // Compile error - string resultText = Dxc.GetStringFromBlob(Library, result.GetErrors()); - throw new HlslCompilationException(resultText); + // Try to compile the new compute shader + fixed (char* entryPoint = "CSMain") + fixed (char* shaderProfile = "cs_6_1") + fixed (char* optimization = "-O3") + { + char nullTerminator = '\0'; + + DxcCompiler.Get()->Compile( + dxcBlobEncoding.Upcast().Get(), + (ushort*)&nullTerminator, + (ushort*)entryPoint, + (ushort*)shaderProfile, + (ushort**)&optimization, + 1, + null, + 0, + DxcIncludeHandler.Get(), + dxcOperationResult.GetAddressOf()).Assert(); + } + + int status; + + dxcOperationResult.Get()->GetStatus(&status).Assert(); + + // The compilation was successful, so we can extract the shader bytecode + if (status == 0) + { + dxcOperationResult.Get()->GetResult(dxcBlobBytecode.GetAddressOf()).Assert(); + + return dxcBlobBytecode.Move(); + } + + return ThrowHslsCompilationException(dxcOperationResult); + } + + /// + /// Throws an exception when a shader compilation fails. + /// + /// The input (faulting) operation. + /// This method always throws and never actually returs. + [DoesNotReturn] + [MethodImpl(MethodImplOptions.NoInlining)] + private static ComPtr ThrowHslsCompilationException(ComPtr dxcOperationResult) + { + using ComPtr dxcBlobEncodingError = default; + + dxcOperationResult.Get()->GetErrorBuffer(dxcBlobEncodingError.GetAddressOf()).Assert(); + + using ComPtr dxcBlobUtf16Error = default; + + DxcLibrary.Get()->GetBlobAsUtf16( + dxcBlobEncodingError.Upcast().Get(), + dxcBlobUtf16Error.Upcast().GetAddressOf()).Assert(); + + string message = new string( + (char*)dxcBlobUtf16Error.Get()->GetStringPointer(), + 0, + checked((int)dxcBlobUtf16Error.Get()->GetStringLength())); + + throw new HlslCompilationException(message); } } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCompiler2.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler2.cs deleted file mode 100644 index 7e741b92..00000000 --- a/src/ComputeSharp.Shaders/Translation/ShaderCompiler2.cs +++ /dev/null @@ -1,140 +0,0 @@ -using System; -using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.Contracts; -using System.Runtime.CompilerServices; -using ComputeSharp.Exceptions; -using ComputeSharp.Graphics.Helpers; -using TerraFX.Interop; -using FX = TerraFX.Interop.Windows; - -namespace ComputeSharp.Shaders.Translation -{ - /// - /// A that uses the DXC APIs to compile compute shaders. - /// - internal static unsafe class ShaderCompiler2 - { - /// - /// The instance to use to create the bytecode for HLSL sources. - /// - private static readonly ComPtr DxcCompiler; - - /// - /// The instance to use to work with . - /// - private static readonly ComPtr DxcLibrary; - - /// - /// The instance used to compile shaders with . - /// - private static readonly ComPtr DxcIncludeHandler; - - /// - /// Initializes , and - /// - static ShaderCompiler2() - { - using ComPtr dxcCompiler = default; - using ComPtr dxcLibrary = default; - using ComPtr dxcIncludeHandler = default; - - Guid dxcCompilerCLGuid = FX.CLSID_DxcCompiler; - Guid dxcCompilerGuid = FX.IID_IDxcCompiler; - Guid dxcLibraryCLGuid = FX.CLSID_DxcLibrary; - Guid dxcLibraryGuid = FX.IID_IDxcLibrary; - - FX.DxcCreateInstance(&dxcCompilerCLGuid, &dxcCompilerGuid, dxcCompiler.GetVoidAddressOf()).Assert(); - FX.DxcCreateInstance(&dxcLibraryCLGuid, &dxcLibraryGuid, dxcLibrary.GetVoidAddressOf()).Assert(); - - dxcLibrary.Get()->CreateIncludeHandler(dxcIncludeHandler.GetAddressOf()).Assert(); - - DxcCompiler = dxcCompiler; - DxcLibrary = dxcLibrary; - DxcIncludeHandler = dxcIncludeHandler; - } - - /// - /// Compiles a new HLSL shader from the input source code. - /// - /// The HLSL source code to compile. - /// The bytecode for the compiled shader. - [Pure] - public static ComPtr CompileShader(ReadOnlySpan source) - { - using ComPtr dxcBlobEncoding = default; - using ComPtr dxcOperationResult = default; - using ComPtr dxcBlobBytecode = default; - - // Get the encoded blob from the source code - fixed (char* p = source) - { - DxcLibrary.Get()->CreateBlobWithEncodingOnHeapCopy( - p, - (uint)source.Length * 2, - 1200, - dxcBlobEncoding.GetAddressOf()).Assert(); - } - - // Try to compile the new compute shader - fixed (char* entryPoint = "CSMain") - fixed (char* shaderProfile = "cs_6_1") - fixed (char* optimization = "-O3") - { - char nullTerminator = '\0'; - - DxcCompiler.Get()->Compile( - dxcBlobEncoding.Upcast().Get(), - (ushort*)&nullTerminator, - (ushort*)entryPoint, - (ushort*)shaderProfile, - (ushort**)&optimization, - 1, - null, - 0, - DxcIncludeHandler.Get(), - dxcOperationResult.GetAddressOf()).Assert(); - } - - int status; - - dxcOperationResult.Get()->GetStatus(&status).Assert(); - - // The compilation was successful, so we can extract the shader bytecode - if (status == 0) - { - dxcOperationResult.Get()->GetResult(dxcBlobBytecode.GetAddressOf()).Assert(); - - return dxcBlobBytecode.Move(); - } - - return ThrowHslsCompilationException(dxcOperationResult); - } - - /// - /// Throws an exception when a shader compilation fails. - /// - /// The input (faulting) operation. - /// This method always throws and never actually returs. - [DoesNotReturn] - [MethodImpl(MethodImplOptions.NoInlining)] - private static ComPtr ThrowHslsCompilationException(ComPtr dxcOperationResult) - { - using ComPtr dxcBlobEncodingError = default; - - dxcOperationResult.Get()->GetErrorBuffer(dxcBlobEncodingError.GetAddressOf()).Assert(); - - using ComPtr dxcBlobUtf16Error = default; - - DxcLibrary.Get()->GetBlobAsUtf16( - dxcBlobEncodingError.Upcast().Get(), - dxcBlobUtf16Error.Upcast().GetAddressOf()).Assert(); - - string message = new string( - (char*)dxcBlobUtf16Error.Get()->GetStringPointer(), - 0, - checked((int)dxcBlobUtf16Error.Get()->GetStringLength())); - - throw new HlslCompilationException(message); - } - } -} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader2{T}.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader2{T}.IL.cs deleted file mode 100644 index efdb2d9b..00000000 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader2{T}.IL.cs +++ /dev/null @@ -1,144 +0,0 @@ -using System; -using System.Buffers; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Reflection; -using System.Reflection.Emit; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using ComputeSharp.Graphics.Buffers; -using ComputeSharp.Shaders.Mappings; -using ComputeSharp.Shaders.Translation.Models; -using TerraFX.Interop; - -namespace ComputeSharp.Shaders.Translation -{ - /// - internal sealed partial class ShaderLoader2 - { - /// - /// A that loads all the captured members from a shader instance. - /// - /// The shader instance to load the data from. - /// A reference to the buffer with all the captured instances. - /// A reference to the buffer to use to store all the captured value types. - private delegate void DispatchDataLoader(in T shader, ref D3D12_GPU_DESCRIPTOR_HANDLE r0, ref byte r1); - - /// - /// The number of captured graphics resources (buffers). - /// - private int totalResourceCount; - - /// - /// The size in bytes of the buffer with the captured variables. - /// - /// Initially set to 3 values for X, Y and Z threads counts. - private int totalVariablesByteSize = 3 * sizeof(int); - - /// - /// The cached instance to load dispatch data before execution. - /// - private DispatchDataLoader? dispatchDataLoader; - - /// - /// The of instances mapping the captured variables in the current shader. - /// - private readonly List capturedMembers = new(); - - /// - /// Gets a new instance with all the captured data for the current shader instance. - /// - /// The input instance representing the compute shader to run. - /// 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. - [Pure] - public DispatchData2 GetDispatchData(in T shader, int x, int y, int z) - { - // Resources and variables buffers - D3D12_GPU_DESCRIPTOR_HANDLE[] resources = ArrayPool.Shared.Rent(this.totalResourceCount); - byte[] variables = ArrayPool.Shared.Rent(this.totalVariablesByteSize); - - ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(resources); - ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables); - - // Set the x, y and z counters - Unsafe.As(ref r1) = x; - Unsafe.Add(ref Unsafe.As(ref r1), 1) = y; - Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; - - // Invoke the dynamic method to extract the captured data - this.dispatchDataLoader!(shader, ref r0, ref r1); - - return new DispatchData2(resources, this.totalResourceCount, variables, this.totalVariablesByteSize); - } - - /// - /// Builds a new instance that loads the dispatch data for the current shader type. - /// - private void BuildDispatchDataLoader() - { - this.dispatchDataLoader = DynamicMethod.New(il => - { - foreach (ReadableMember member in this.capturedMembers) - { - if (HlslKnownTypes.IsKnownBufferType(member.MemberType)) - { - // Load the offset address into the resource buffers - il.Emit(OpCodes.Ldarg_1); - - if (totalResourceCount > 0) - { - il.EmitAddOffset(this.totalResourceCount); - } - - il.Emit(OpCodes.Ldarg_0); - il.EmitReadMember(member); - - // Access Buffer.D3D12GpuDescriptorHandle - FieldInfo gpuDescriptorInfo = member.MemberType.GetField( - nameof(Buffer2.D3D12GpuDescriptorHandle), - BindingFlags.NonPublic | BindingFlags.Instance)!; - - il.EmitReadMember(gpuDescriptorInfo); - il.EmitStoreToAddress(member.MemberType); - - this.totalResourceCount++; - } - else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) || - HlslKnownTypes.IsKnownVectorType(member.MemberType)) - { - // Calculate the right offset with 16-bytes padding (HLSL constant buffer) - int size = member.MemberType == typeof(bool) - ? sizeof(uint) - : Marshal.SizeOf(member.MemberType); // bool is 4 bytes in HLSL - - if (this.totalVariablesByteSize % 16 > 16 - size) - { - this.totalVariablesByteSize += 16 - this.totalVariablesByteSize % 16; - } - - // Load the target address into the variables buffer - il.Emit(OpCodes.Ldarg_2); - il.EmitAddOffset(totalVariablesByteSize); - - this.totalVariablesByteSize += size; - } - else throw new InvalidOperationException($"Invalid captured member of type {member.MemberType}"); - - // Load the reference to the input delegate if the member is not static - if (!member.IsStatic) - { - il.Emit(OpCodes.Ldarg_0); - } - - // Read the current member and store it to the target address - il.EmitReadMember(member); - il.EmitStoreToAddress(member.MemberType); - } - - il.Emit(OpCodes.Ret); - }); - } - } -} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader2{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader2{T}.cs deleted file mode 100644 index 480a7ec7..00000000 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader2{T}.cs +++ /dev/null @@ -1,355 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Text.RegularExpressions; -using ComputeSharp.Graphics.Extensions; -using ComputeSharp.Shaders.Mappings; -using ComputeSharp.Shaders.Renderer.Models.Fields; -using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract; -using ComputeSharp.Shaders.Renderer.Models.Functions; -using ComputeSharp.Shaders.Translation.Enums; -using ComputeSharp.Shaders.Translation.Models; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using TerraFX.Interop; -using static TerraFX.Interop.D3D12_DESCRIPTOR_RANGE_TYPE; -using ParameterInfo = ComputeSharp.Shaders.Renderer.Models.Functions.ParameterInfo; - -#pragma warning disable CS8618 // Non-nullable field is uninitialized - -namespace ComputeSharp.Shaders.Translation -{ - /// - /// A responsible for loading and processing shaders of a given type. - /// - /// The type of compute shader currently in use. - internal sealed partial class ShaderLoader2 - where T : struct, IComputeShader - { - /// - /// The number of constant buffers to define in the shader. - /// - private uint constantBuffersCount; - - /// - /// The number of readonly buffers to define in the shader. - /// - private uint readOnlyBuffersCount; - - /// - /// The number of read write buffers to define in the shader. - /// - private uint readWriteBuffersCount; - - /// - /// The of items that are required to load the captured values. - /// - private readonly List d3D12DescriptorRanges1 = new(); - - /// - /// The with the items for the shader fields. - /// - private readonly List hlslBuffersInfo = new(); - - /// - /// The with the items for the shader fields. - /// - private readonly List fieldsInfo = new(); - - /// - /// The with the items for the shader functions. - /// - private readonly List functionsInfo = new(); - - /// - /// The with the items for the shader local functions. - /// - private readonly List localFunctionsInfo = new(); - - /// - /// Creates a new instance. - /// - private ShaderLoader2() - { - } - - /// - /// Gets a with the loaded items for the shader. - /// - public ReadOnlySpan D3D12DescriptorRanges1 - { - get => CollectionsMarshal.AsSpan(this.d3D12DescriptorRanges1); - } - - /// - /// Gets the name of the variable used as input for the shader method. - /// - public string ThreadsIdsVariableName { get; private set; } - - /// - /// Gets the generated source code for the method in the current shader. - /// - public string MethodBody { get; private set; } - - /// - /// Gets the collection of items for the shader fields. - /// - public IReadOnlyList HslsBuffersInfo => this.hlslBuffersInfo; - - /// - /// Gets the collection of items for the shader fields. - /// - public IReadOnlyList FieldsInfo => this.fieldsInfo; - - /// - /// Gets the collection of items for the shader. - /// - public IReadOnlyList FunctionsInfo => this.functionsInfo; - - /// - /// Gets the collection of items for the shader. - /// - public IReadOnlyList LocalFunctionsInfo => this.localFunctionsInfo; - - /// - /// Loads and processes an input shadeer - /// - /// The instance to use to build the shader - /// A new instance representing the input shader - [Pure] - public static ShaderLoader2 Load(in T shader) - { - ShaderLoader2 @this = new ShaderLoader2(); - - // Reading members through reflection requires an object parameter, - // so here we're just boxing the input shader once to avoid allocating - // it multiple times in the managed heap while processing the shader. - object box = shader; - - @this.LoadFieldsInfo(box); - @this.LoadMethodSource(box); - @this.BuildDispatchDataLoader(); - - return @this; - } - - /// - /// Loads the fields info for the current shader being loaded - /// - /// The boxed instance to use to build the shader - private void LoadFieldsInfo(object shader) - { - IReadOnlyList shaderFields = typeof(T).GetFields( - BindingFlags.Instance | - BindingFlags.Static | - BindingFlags.Public | - BindingFlags.NonPublic).ToArray(); - - if (shaderFields.Count == 0) throw new InvalidOperationException("Empty shader body"); - - // Descriptor for the buffer for captured scalar/vector variables - D3D12_DESCRIPTOR_RANGE1.Init( - out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1, - D3D12_DESCRIPTOR_RANGE_TYPE_CBV, - 1, - this.constantBuffersCount++); - - this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); - - // Inspect the captured fields - foreach (FieldInfo fieldInfo in shaderFields) - { - LoadFieldInfo(shader, fieldInfo); - } - } - - /// - /// Loads a specified and adds it to the shader model - /// - /// The boxed instance to use to build the shader - /// The target to load - /// The optional explicit name to use for the field - private void LoadFieldInfo(object shader, ReadableMember memberInfo, string? name = null) - { - Type fieldType = memberInfo.MemberType; - string fieldName = HlslKnownKeywords.GetMappedName(name ?? memberInfo.Name); - - // Constant buffer - if (HlslKnownTypes.IsConstantBufferType(fieldType)) - { - D3D12_DESCRIPTOR_RANGE1.Init( - out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1, - D3D12_DESCRIPTOR_RANGE_TYPE_CBV, - 1, - this.constantBuffersCount++); - - this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); - - this.capturedMembers.Add(memberInfo); - - string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); - - this.hlslBuffersInfo.Add(new ConstantBufferFieldInfo(fieldType, typeName, fieldName, (int)this.constantBuffersCount)); - } - else if (HlslKnownTypes.IsReadOnlyBufferType(fieldType)) - { - // Root parameter for a readonly buffer - D3D12_DESCRIPTOR_RANGE1.Init( - out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1, - D3D12_DESCRIPTOR_RANGE_TYPE_SRV, - 1, - this.readOnlyBuffersCount++); - - this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); - - this.capturedMembers.Add(memberInfo); - - string typeName = HlslKnownTypes.GetMappedName(fieldType); - - this.hlslBuffersInfo.Add(new ReadOnlyBufferFieldInfo(fieldType, typeName, fieldName, (int)this.readOnlyBuffersCount)); - } - else if (HlslKnownTypes.IsReadWriteBufferType(fieldType)) - { - // Root parameter for a read write buffer - D3D12_DESCRIPTOR_RANGE1.Init( - out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1, - D3D12_DESCRIPTOR_RANGE_TYPE_UAV, - 1, - this.readWriteBuffersCount++); - - this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); - - this.capturedMembers.Add(memberInfo); - - string typeName = HlslKnownTypes.GetMappedName(fieldType); - - this.hlslBuffersInfo.Add(new ReadWriteBufferFieldInfo(fieldType, typeName, fieldName, (int)this.readWriteBuffersCount)); - } - else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType)) - { - this.capturedMembers.Add(memberInfo); - - string typeName = HlslKnownTypes.GetMappedName(fieldType); - - this.fieldsInfo.Add(new CapturedFieldInfo(fieldType, typeName, fieldName)); - } - else if (fieldType.IsDelegate() && - memberInfo.GetValue(shader) is Delegate func && - (func.Method.IsStatic || func.Method.DeclaringType!.IsStatelessDelegateContainer()) && - (HlslKnownTypes.IsKnownScalarType(func.Method.ReturnType) || HlslKnownTypes.IsKnownVectorType(func.Method.ReturnType)) && - fieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) || - HlslKnownTypes.IsKnownVectorType(type))) - { - // Captured static delegates with a return type - LoadStaticMethodSource(shader, fieldName, func.Method); - } - else throw new ArgumentException($"Invalid captured variable of type {fieldType} with name \"{memberInfo.Name}\""); - } - - /// - /// Loads the entry method for the current shader being loaded - /// - /// The boxed instance to use to build the shader - private void LoadMethodSource(object shader) - { - // Decompile the shader method - MethodInfo methodInfo = typeof(T).GetMethod(nameof(IComputeShader.Execute))!; - MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Execute, out MethodDeclarationSyntax root, out SemanticModel semanticModel); - - // Rewrite the shader method (eg. to fix the type declarations) - ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, typeof(T)); - root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root); - - // Extract the implicit local functions - var locals = root.DescendantNodes().OfType().ToArray(); - root = root.RemoveNodes(locals, SyntaxRemoveOptions.KeepNoTrivia)!; - foreach (var local in locals) - { - string alignedLocal = local.ToFullString().RemoveLeftPadding().Trim(' ', '\r', '\n'); - alignedLocal = Regex.Replace(alignedLocal, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value); - alignedLocal = HlslKnownKeywords.GetMappedText(alignedLocal); - - this.localFunctionsInfo.Add(new LocalFunctionInfo(alignedLocal)); - } - - // Register the captured static members - foreach (var member in syntaxRewriter.StaticMembers) - { - LoadFieldInfo(shader, member.Value, member.Key); - } - - // Register the captured static methods - foreach (var method in syntaxRewriter.StaticMethods) - { - LoadStaticMethodSource(shader, method.Key, method.Value); - } - - // Get the thread ids identifier name and shader method body - ThreadsIdsVariableName = root.ParameterList.Parameters.First().Identifier.Text; - MethodBody = root.Body!.ToFullString(); - - // Additional preprocessing - MethodBody = Regex.Replace(MethodBody, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value); - MethodBody = MethodBody.TrimEnd('\n', '\r', ' '); - MethodBody = HlslKnownKeywords.GetMappedText(MethodBody); - } - - /// - /// Loads additional static methods used by the shader - /// - /// The boxed instance to use to build the shader - /// The HLSL name of the new method to load - /// The instance for the method to load - private void LoadStaticMethodSource(object shader, string name, MethodInfo methodInfo) - { - // Decompile the target method - MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Static, out MethodDeclarationSyntax root, out SemanticModel semanticModel); - - // Rewrite the method - ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, methodInfo.DeclaringType!); - root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root); - - // Register the captured static members - foreach (var member in syntaxRewriter.StaticMembers) - { - LoadFieldInfo(shader, member.Value, member.Key); - } - - // Register the captured static methods - foreach (var method in syntaxRewriter.StaticMethods) - { - LoadStaticMethodSource(shader, method.Key, method.Value); - } - - // Get the function parameters - IReadOnlyList parameters = ( - from parameter in root.ParameterList.Parameters.Select((p, i) => (Node: p, Index: i)) - let modifiers = parameter.Node.Modifiers - let type = parameter.Node.Type!.ToFullString() - let parameterName = parameter.Node.Identifier.ToFullString() - let last = parameter.Index == root.ParameterList.Parameters.Count - 1 - select new ParameterInfo(modifiers, type, parameterName, last)).ToArray(); - - // Get the function body - string body = root.Body!.ToFullString(); - body = Regex.Replace(body, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value); - body = body.TrimEnd('\n', '\r', ' '); - body = HlslKnownKeywords.GetMappedText(body); - - // Get the final function info instance - FunctionInfo functionInfo = new FunctionInfo( - methodInfo.ReturnType, - $"{methodInfo.DeclaringType!.FullName}{Type.Delimiter}{methodInfo.Name}", - string.Join(", ", methodInfo.GetParameters().Select(p => $"{p.ParameterType.ToFriendlyString()} {p.Name}")), - root.ReturnType.ToString(), - name, - parameters, - body); - - this.functionsInfo.Add(functionInfo); - } - } -} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs index 24814bdf..4faec8a8 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs @@ -2,12 +2,14 @@ using System.Buffers; using System.Collections.Generic; using System.Diagnostics.Contracts; +using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Graphics.Buffers; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Translation.Models; +using TerraFX.Interop; namespace ComputeSharp.Shaders.Translation { @@ -15,46 +17,50 @@ namespace ComputeSharp.Shaders.Translation internal sealed partial class ShaderLoader { /// - /// The number of captured graphics resources (buffers) + /// A that loads all the captured members from a shader instance. /// - private int _ResourcesCount; + /// The shader instance to load the data from. + /// A reference to the buffer with all the captured instances. + /// A reference to the buffer to use to store all the captured value types. + private delegate void DispatchDataLoader(in T shader, ref D3D12_GPU_DESCRIPTOR_HANDLE r0, ref byte r1); /// - /// The size in bytes of the buffer with the captured variables + /// The number of captured graphics resources (buffers). /// - private int _VariablesByteSize = 3 * sizeof(int); // X, Y and Z threads count - - // The cached loader method - private DispatchDataLoader? _DispatchDataLoader; + private int totalResourceCount; /// - /// The of instances mapping the captured variables in the current shader + /// The size in bytes of the buffer with the captured variables. /// - private readonly List _CapturedMembers = new List(); + /// Initially set to 3 values for X, Y and Z threads counts. + private int totalVariablesByteSize = 3 * sizeof(int); /// - /// A that loads all the captured members from a shader instance + /// The cached instance to load dispatch data before execution. /// - /// The shader instance to load the data from - /// A reference to the buffer with all the captured instances - /// A reference to the buffer to use to store all the captured value types - private delegate void DispatchDataLoader(in T shader, ref GraphicsResource r0, ref byte r1); + private DispatchDataLoader? dispatchDataLoader; /// - /// Gets a new instance with all the captured data for the current shader instance + /// The of instances mapping the captured variables in the current shader. /// - /// The input instance representing the compute shader to run - /// 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 + private readonly List capturedMembers = new(); + + /// + /// Gets a new instance with all the captured data for the current shader instance. + /// + /// The input instance representing the compute shader to run. + /// 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. [Pure] public DispatchData GetDispatchData(in T shader, int x, int y, int z) { // Resources and variables buffers - GraphicsResource[] resources = ArrayPool.Shared.Rent(_ResourcesCount); - byte[] variables = ArrayPool.Shared.Rent(_VariablesByteSize); - ref GraphicsResource r0 = ref resources[0]; - ref byte r1 = ref variables[0]; + D3D12_GPU_DESCRIPTOR_HANDLE[] resources = ArrayPool.Shared.Rent(this.totalResourceCount); + byte[] variables = ArrayPool.Shared.Rent(this.totalVariablesByteSize); + + ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(resources); + ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables); // Set the x, y and z counters Unsafe.As(ref r1) = x; @@ -62,42 +68,69 @@ namespace ComputeSharp.Shaders.Translation Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; // Invoke the dynamic method to extract the captured data - _DispatchDataLoader!(shader, ref r0, ref r1); + this.dispatchDataLoader!(shader, ref r0, ref r1); - return new DispatchData(resources, _ResourcesCount, variables, _VariablesByteSize); + return new DispatchData(resources, this.totalResourceCount, variables, this.totalVariablesByteSize); } /// - /// Builds a new instance that loads the dispatch data for the current shader type + /// Builds a new instance that loads the dispatch data for the current shader type. /// private void BuildDispatchDataLoader() { - _DispatchDataLoader = DynamicMethod.New(il => + this.dispatchDataLoader = DynamicMethod.New(il => { - foreach (ReadableMember member in _CapturedMembers) + foreach (ReadableMember member in this.capturedMembers) { if (HlslKnownTypes.IsKnownBufferType(member.MemberType)) { // Load the offset address into the resource buffers il.Emit(OpCodes.Ldarg_1); - if (_ResourcesCount > 0) il.EmitAddOffset(_ResourcesCount); - _ResourcesCount++; + + if (totalResourceCount > 0) + { + il.EmitAddOffset(this.totalResourceCount); + } + + il.Emit(OpCodes.Ldarg_0); + il.EmitReadMember(member); + + // Access Buffer.D3D12GpuDescriptorHandle + FieldInfo gpuDescriptorInfo = member.MemberType.GetField( + nameof(Buffer.D3D12GpuDescriptorHandle), + BindingFlags.NonPublic | BindingFlags.Instance)!; + + il.EmitReadMember(gpuDescriptorInfo); + il.EmitStoreToAddress(member.MemberType); + + this.totalResourceCount++; } - else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) || HlslKnownTypes.IsKnownVectorType(member.MemberType)) + else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) || + HlslKnownTypes.IsKnownVectorType(member.MemberType)) { // Calculate the right offset with 16-bytes padding (HLSL constant buffer) - int size = member.MemberType == typeof(bool) ? sizeof(uint) : Marshal.SizeOf(member.MemberType); // bool is 4 bytes in HLSL - if (_VariablesByteSize % 16 > 16 - size) _VariablesByteSize += 16 - _VariablesByteSize % 16; + int size = member.MemberType == typeof(bool) + ? sizeof(uint) + : Marshal.SizeOf(member.MemberType); // bool is 4 bytes in HLSL + + if (this.totalVariablesByteSize % 16 > 16 - size) + { + this.totalVariablesByteSize += 16 - this.totalVariablesByteSize % 16; + } // Load the target address into the variables buffer il.Emit(OpCodes.Ldarg_2); - il.EmitAddOffset(_VariablesByteSize); - _VariablesByteSize += size; + il.EmitAddOffset(totalVariablesByteSize); + + this.totalVariablesByteSize += size; } else throw new InvalidOperationException($"Invalid captured member of type {member.MemberType}"); // Load the reference to the input delegate if the member is not static - if (!member.IsStatic) il.Emit(OpCodes.Ldarg_0); + if (!member.IsStatic) + { + il.Emit(OpCodes.Ldarg_0); + } // Read the current member and store it to the target address il.EmitReadMember(member); diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 355f0350..b6aad4c0 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; +using System.Runtime.InteropServices; using System.Text.RegularExpressions; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Shaders.Mappings; @@ -13,7 +14,8 @@ using ComputeSharp.Shaders.Translation.Enums; using ComputeSharp.Shaders.Translation.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Vortice.Direct3D12; +using TerraFX.Interop; +using static TerraFX.Interop.D3D12_DESCRIPTOR_RANGE_TYPE; using ParameterInfo = ComputeSharp.Shaders.Renderer.Models.Functions.ParameterInfo; #pragma warning disable CS8618 // Non-nullable field is uninitialized @@ -21,81 +23,96 @@ using ParameterInfo = ComputeSharp.Shaders.Renderer.Models.Functions.ParameterIn namespace ComputeSharp.Shaders.Translation { /// - /// A responsible for loading and processing shaders of a given type + /// A responsible for loading and processing shaders of a given type. /// - /// The type of compute shader currently in use + /// The type of compute shader currently in use. internal sealed partial class ShaderLoader where T : struct, IComputeShader { /// - /// Creates a new instance + /// The number of constant buffers to define in the shader. /// - private ShaderLoader() { } + private uint constantBuffersCount; /// - /// The number of constant buffers to define in the shader + /// The number of readonly buffers to define in the shader. /// - private int _ConstantBuffersCount; + private uint readOnlyBuffersCount; /// - /// The number of readonly buffers to define in the shader + /// The number of read write buffers to define in the shader. /// - private int _ReadOnlyBuffersCount; + private uint readWriteBuffersCount; /// - /// The number of read write buffers to define in the shader + /// The of items that are required to load the captured values. /// - private int _ReadWriteBuffersCount; + private readonly List d3D12DescriptorRanges1 = new(); /// - /// The of items that are required to load the captured values + /// The with the items for the shader fields. /// - private readonly List DescriptorRanges = new List(); - - private RootParameter1[]? _RootParameters; + private readonly List hlslBuffersInfo = new(); /// - /// Gets the array for the current shader + /// The with the items for the shader fields. /// - public RootParameter1[] RootParameters => _RootParameters ??= DescriptorRanges.Select(range => new RootParameter1(new RootDescriptorTable1(range), ShaderVisibility.All)).ToArray(); - - private readonly List _BuffersList = new List(); + private readonly List fieldsInfo = new(); /// - /// Gets the collection of items for the shader fields + /// The with the items for the shader functions. /// - public IReadOnlyList BuffersList => _BuffersList; - - private readonly List _FieldsList = new List(); + private readonly List functionsInfo = new(); /// - /// Gets the collection of items for the shader fields + /// The with the items for the shader local functions. /// - public IReadOnlyList FieldsList => _FieldsList; + private readonly List localFunctionsInfo = new(); /// - /// Gets the name of the variable used as input for the shader method + /// Creates a new instance. + /// + private ShaderLoader() + { + } + + /// + /// Gets a with the loaded items for the shader. + /// + public ReadOnlySpan D3D12DescriptorRanges1 + { + get => CollectionsMarshal.AsSpan(this.d3D12DescriptorRanges1); + } + + /// + /// Gets the name of the variable used as input for the shader method. /// public string ThreadsIdsVariableName { get; private set; } /// - /// Gets the generated source code for the method in the current shader + /// Gets the generated source code for the method in the current shader. /// public string MethodBody { get; private set; } - private readonly List _FunctionsList = new List(); + /// + /// Gets the collection of items for the shader fields. + /// + public IReadOnlyList HslsBuffersInfo => this.hlslBuffersInfo; /// - /// Gets the collection of items for the shader + /// Gets the collection of items for the shader fields. /// - public IReadOnlyList FunctionsList => _FunctionsList; - - private readonly List _LocalFunctionsList = new List(); + public IReadOnlyList FieldsInfo => this.fieldsInfo; /// - /// Gets the collection of items for the shader + /// Gets the collection of items for the shader. /// - public IReadOnlyList LocalFunctionsList => _LocalFunctionsList; + public IReadOnlyList FunctionsInfo => this.functionsInfo; + + /// + /// Gets the collection of items for the shader. + /// + public IReadOnlyList LocalFunctionsInfo => this.localFunctionsInfo; /// /// Loads and processes an input shadeer @@ -107,9 +124,9 @@ namespace ComputeSharp.Shaders.Translation { ShaderLoader @this = new ShaderLoader(); - /* Reading members through reflection requires an object parameter, - * so here we're just boxing the input shader once to avoid allocating - * it multiple times in the managed heap while processing the shader. */ + // Reading members through reflection requires an object parameter, + // so here we're just boxing the input shader once to avoid allocating + // it multiple times in the managed heap while processing the shader. object box = shader; @this.LoadFieldsInfo(box); @@ -134,7 +151,13 @@ namespace ComputeSharp.Shaders.Translation if (shaderFields.Count == 0) throw new InvalidOperationException("Empty shader body"); // Descriptor for the buffer for captured scalar/vector variables - DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount++)); + D3D12_DESCRIPTOR_RANGE1.Init( + out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1, + D3D12_DESCRIPTOR_RANGE_TYPE_CBV, + 1, + this.constantBuffersCount++); + + this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); // Inspect the captured fields foreach (FieldInfo fieldInfo in shaderFields) @@ -157,39 +180,61 @@ namespace ComputeSharp.Shaders.Translation // Constant buffer if (HlslKnownTypes.IsConstantBufferType(fieldType)) { - DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount)); + D3D12_DESCRIPTOR_RANGE1.Init( + out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1, + D3D12_DESCRIPTOR_RANGE_TYPE_CBV, + 1, + this.constantBuffersCount++); - _CapturedMembers.Add(memberInfo); + this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); + + this.capturedMembers.Add(memberInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); - _BuffersList.Add(new ConstantBufferFieldInfo(fieldType, typeName, fieldName, _ConstantBuffersCount++)); + + this.hlslBuffersInfo.Add(new ConstantBufferFieldInfo(fieldType, typeName, fieldName, (int)this.constantBuffersCount)); } else if (HlslKnownTypes.IsReadOnlyBufferType(fieldType)) { // Root parameter for a readonly buffer - DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ShaderResourceView, 1, _ReadOnlyBuffersCount)); + D3D12_DESCRIPTOR_RANGE1.Init( + out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1, + D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + 1, + this.readOnlyBuffersCount++); - _CapturedMembers.Add(memberInfo); + this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); + + this.capturedMembers.Add(memberInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); - _BuffersList.Add(new ReadOnlyBufferFieldInfo(fieldType, typeName, fieldName, _ReadOnlyBuffersCount++)); + + this.hlslBuffersInfo.Add(new ReadOnlyBufferFieldInfo(fieldType, typeName, fieldName, (int)this.readOnlyBuffersCount)); } else if (HlslKnownTypes.IsReadWriteBufferType(fieldType)) { // Root parameter for a read write buffer - DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.UnorderedAccessView, 1, _ReadWriteBuffersCount)); + D3D12_DESCRIPTOR_RANGE1.Init( + out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1, + D3D12_DESCRIPTOR_RANGE_TYPE_UAV, + 1, + this.readWriteBuffersCount++); - _CapturedMembers.Add(memberInfo); + this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); + + this.capturedMembers.Add(memberInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); - _BuffersList.Add(new ReadWriteBufferFieldInfo(fieldType, typeName, fieldName, _ReadWriteBuffersCount++)); + + this.hlslBuffersInfo.Add(new ReadWriteBufferFieldInfo(fieldType, typeName, fieldName, (int)this.readWriteBuffersCount)); } else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType)) { - _CapturedMembers.Add(memberInfo); + this.capturedMembers.Add(memberInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); - _FieldsList.Add(new CapturedFieldInfo(fieldType, typeName, fieldName)); + + this.fieldsInfo.Add(new CapturedFieldInfo(fieldType, typeName, fieldName)); } else if (fieldType.IsDelegate() && memberInfo.GetValue(shader) is Delegate func && @@ -227,7 +272,7 @@ namespace ComputeSharp.Shaders.Translation alignedLocal = Regex.Replace(alignedLocal, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value); alignedLocal = HlslKnownKeywords.GetMappedText(alignedLocal); - _LocalFunctionsList.Add(new LocalFunctionInfo(alignedLocal)); + this.localFunctionsInfo.Add(new LocalFunctionInfo(alignedLocal)); } // Register the captured static members @@ -304,7 +349,7 @@ namespace ComputeSharp.Shaders.Translation parameters, body); - _FunctionsList.Add(functionInfo); + this.functionsInfo.Add(functionInfo); } } } diff --git a/src/ComputeSharp/ComputeSharp.nuspec b/src/ComputeSharp/ComputeSharp.nuspec index 3f708d4d..5dbb15d9 100644 --- a/src/ComputeSharp/ComputeSharp.nuspec +++ b/src/ComputeSharp/ComputeSharp.nuspec @@ -2,7 +2,7 @@ ComputeSharp - 1.4.1 + 2.0.0 ComputeSharp Sergio Pedri Sergio Pedri @@ -10,19 +10,16 @@ https://github.com/Sergio0694/ComputeSharp https://i.imgur.com/ntvmD6P.png false - A .NET Standard 2.1 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders + A .NET 5 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders New interlocked intrinsics APIs, performance and memory optimizations Copyright (c) 2020 Sergio Pedri dotnet net netcore netstandard csharp library graphics shader hlsl compute gpu - - - + - diff --git a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs index 7bd3d7e2..97ddd81e 100644 --- a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs +++ b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs @@ -4,17 +4,17 @@ using ComputeSharp.Shaders; namespace ComputeSharp { /// - /// A that contains extension methods for the type, used to run compute shaders + /// A that contains extension methods for the type, used to run compute shaders. /// - public static class GraphicsDeviceExtensions + public static class GraphicsDevice2Extensions { /// - /// Compiles and runs the input shader on a target instance, with the specified parameters + /// Compiles and 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 input instance representing the compute shader to run + /// 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 input instance representing the compute shader to run. public static void For(this GraphicsDevice device, int x, in T shader) where T : struct, IComputeShader { @@ -22,13 +22,13 @@ namespace ComputeSharp } /// - /// Compiles and runs the input shader on a target instance, with the specified parameters + /// Compiles and 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 input instance representing the compute shader to run + /// 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 input instance representing the compute shader to run. public static void For(this GraphicsDevice device, int x, int y, in T shader) where T : struct, IComputeShader { @@ -36,14 +36,14 @@ namespace ComputeSharp } /// - /// Compiles and runs the input shader on a target instance, with the specified parameters + /// Compiles and 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 input instance representing the compute shader to run + /// 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 input instance representing the compute shader to run. public static void For(this GraphicsDevice device, int x, int y, int z, in T shader) where T : struct, IComputeShader { @@ -51,17 +51,17 @@ namespace ComputeSharp } /// - /// Compiles and runs the input shader on a target instance, with the specified parameters + /// Compiles and 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 + /// 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, diff --git a/src/ComputeSharp/Gpu.cs b/src/ComputeSharp/Gpu.cs index 26ae6399..debe671c 100644 --- a/src/ComputeSharp/Gpu.cs +++ b/src/ComputeSharp/Gpu.cs @@ -1,55 +1,30 @@ using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Linq; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Helpers; -using Vortice.Direct3D12; -using Vortice.DXGI; namespace ComputeSharp { /// - /// A that acts as an entry-point for all the library APIs, exposing the available GPU devices + /// A that acts as an entry-point for all the library APIs, exposing the available GPU devices. /// public static class Gpu { /// - /// Initializes the field and property + /// The instance used to produce the default device for . /// - static Gpu() - { - Devices = DeviceHelper.QueryAllSupportedDevices(); - IsSupported = Devices.Any(); - - if (IsSupported) - { - _Default = new GraphicsDevice(Devices[0].Device, Devices[0].Description); - } - } + private static readonly Lazy DefaultFactory = new(DeviceHelper.GetDefaultDevice); /// - /// The loaded collection of supported devices and descriptions + /// Gets whether or not the APIs can be used on the + /// current machine (ie. if there is at least a supported GPU device). /// - private static readonly IReadOnlyList<(ID3D12Device Device, AdapterDescription Description)> Devices; - - private static readonly GraphicsDevice? _Default; + public static bool IsSupported => DeviceHelper.IsDefaultDeviceAvailable(); /// - /// Gets the default instance for the current machine + /// Gets the default instance for the current machine. /// - public static GraphicsDevice Default => _Default ?? throw new NotSupportedException("There isn't a supported GPU device on the current machine"); - - /// - /// Gets whether or not the APIs can be used on the current machine (ie. if there is at least a supported GPU device) - /// - public static bool IsSupported { get; } - - /// - /// Enumerates all the available objects on the current machine - /// - /// A sequence of supported objects that can be used to run compute shaders - [Pure] - public static IEnumerable EnumerateDevices() => Devices.Select(device => new GraphicsDevice(device.Device, device.Description)); + /// Thrown when a default device is not available. + /// Make sure to check before accessing this property. + public static GraphicsDevice Default => DefaultFactory.Value; } } diff --git a/src/ComputeSharp/Gpu2.cs b/src/ComputeSharp/Gpu2.cs deleted file mode 100644 index 85454fad..00000000 --- a/src/ComputeSharp/Gpu2.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Helpers; - -namespace ComputeSharp -{ - /// - /// A that acts as an entry-point for all the library APIs, exposing the available GPU devices. - /// - public static class Gpu2 - { - /// - /// The instance used to produce the default device for . - /// - private static readonly Lazy DefaultFactory = new(DeviceHelper2.GetDefaultDevice); - - /// - /// Gets whether or not the APIs can be used on the - /// current machine (ie. if there is at least a supported GPU device). - /// - public static bool IsSupported => DeviceHelper2.IsDefaultDeviceAvailable(); - - /// - /// Gets the default instance for the current machine. - /// - /// Thrown when a default device is not available. - /// Make sure to check before accessing this property. - public static GraphicsDevice2 Default => DefaultFactory.Value; - } -}