From 4d0bab3890fe915d3a66e9552e51948be33ca712 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 29 Aug 2022 00:52:04 +0200 Subject: [PATCH 01/17] Add TransferTexture1D type --- .../UnsupportedTextureTypeException.cs | 11 + src/ComputeSharp/Graphics/GraphicsDevice.cs | 34 +++ .../Abstract/TransferTexture1D{T}.cs | 207 ++++++++++++++++++ .../Abstract/TransferTexture2D{T}.cs | 2 +- .../Abstract/TransferTexture3D{T}.cs | 2 +- 5 files changed, 254 insertions(+), 2 deletions(-) create mode 100644 src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture1D{T}.cs diff --git a/src/ComputeSharp/Graphics/Exceptions/UnsupportedTextureTypeException.cs b/src/ComputeSharp/Graphics/Exceptions/UnsupportedTextureTypeException.cs index 0558e6f8..bc4f9353 100644 --- a/src/ComputeSharp/Graphics/Exceptions/UnsupportedTextureTypeException.cs +++ b/src/ComputeSharp/Graphics/Exceptions/UnsupportedTextureTypeException.cs @@ -33,6 +33,7 @@ public sealed class UnsupportedTextureTypeException : NotSupportedException builder.AppendLine(rank switch { + 1 => $"{nameof(GraphicsDevice.IsReadOnlyTexture1DSupportedForType)}() or {nameof(GraphicsDevice)}.{nameof(GraphicsDevice.IsReadWriteTexture1DSupportedForType)}().", 2 => $"{nameof(GraphicsDevice.IsReadOnlyTexture2DSupportedForType)}() or {nameof(GraphicsDevice)}.{nameof(GraphicsDevice.IsReadWriteTexture2DSupportedForType)}().", 3 => $"{nameof(GraphicsDevice.IsReadOnlyTexture3DSupportedForType)}() or {nameof(GraphicsDevice)}.{nameof(GraphicsDevice.IsReadWriteTexture3DSupportedForType)}().", _ => ThrowHelper.ThrowArgumentException("Invalid texture rank.") @@ -43,6 +44,16 @@ public sealed class UnsupportedTextureTypeException : NotSupportedException return new(builder.ToString()); } + /// + /// Throws a new instance from the specified parameters. + /// + /// The type of values in the texture that couldn't be created. + internal static void ThrowForTexture1D() + where T : unmanaged + { + throw Create(1, typeof(T)); + } + /// /// Throws a new instance from the specified parameters. /// diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index ea9edbc0..71895039 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -261,6 +261,40 @@ public sealed unsafe partial class GraphicsDevice : NativeObject return d3D12OptionsData.DoublePrecisionFloatShaderOps; } + /// + /// Checks whether the current device supports the creation of + /// resources for a specified type . + /// + /// The type of values to check support for. + /// Whether instances can be created by the current device. + public bool IsReadOnlyTexture1DSupportedForType() + where T : unmanaged + { + using var _0 = GetReferenceTrackingLease(); + + ThrowIfDeviceLost(); + + return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE1D); + } + + /// + /// Checks whether the current device supports the creation of + /// resources for a specified type . + /// + /// The type of values to check support for. + /// Whether instances can be created by the current device. + public bool IsReadWriteTexture1DSupportedForType() + where T : unmanaged + { + using var _0 = GetReferenceTrackingLease(); + + ThrowIfDeviceLost(); + + return this.d3D12Device.Get()->IsDxgiFormatSupported( + DXGIFormatHelper.GetForType(), + D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW); + } + /// /// Checks whether the current device supports the creation of /// resources for a specified type . diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture1D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture1D{T}.cs new file mode 100644 index 00000000..63058466 --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture1D{T}.cs @@ -0,0 +1,207 @@ +using System; +using System.Buffers; +using System.Runtime.CompilerServices; +using CommunityToolkit.Diagnostics; +using ComputeSharp.Exceptions; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.Graphics.Helpers; +using ComputeSharp.Interop; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using static TerraFX.Interop.DirectX.D3D12_FORMAT_SUPPORT1; +using ResourceType = ComputeSharp.Graphics.Resources.Enums.ResourceType; + +namespace ComputeSharp.Resources; + +/// +/// A representing a typed 1D texture stored on on CPU memory, that can be used to transfer data to/from the GPU. +/// +/// The type of items stored on the texture. +public unsafe abstract class TransferTexture1D : NativeObject, IGraphicsResource, IMemoryOwner + where T : unmanaged +{ +#if NET6_0_OR_GREATER + /// + /// The instance used to retrieve . + /// + private ComPtr allocation; +#endif + + /// + /// The instance currently mapped. + /// + private ComPtr d3D12Resource; + + /// + /// The pointer to the start of the mapped buffer data. + /// + private readonly T* mappedData; + + /// + /// The description for the current resource. + /// + private readonly D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprint; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The associated with the current instance. + /// The width of the texture. + /// The resource type for the current texture. + /// The allocation mode to use for the new resource. + private protected TransferTexture1D(GraphicsDevice device, int width, ResourceType resourceType, AllocationMode allocationMode) + { + Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE1D_U_DIMENSION); + + using var _0 = device.GetReferenceTrackingLease(); + + device.ThrowIfDeviceLost(); + + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE1D)) + { + UnsupportedTextureTypeException.ThrowForTexture1D(); + } + + GraphicsDevice = device; + + device.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + out this.d3D12PlacedSubresourceFootprint, + out _, + out ulong totalSizeInBytes); + +#if NET6_0_OR_GREATER + this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, totalSizeInBytes); + this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); +#else + this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, totalSizeInBytes, device.IsCacheCoherentUMA); +#endif + + device.RegisterAllocatedResource(); + + this.mappedData = (T*)this.d3D12Resource.Get()->Map().Pointer; + + this.d3D12Resource.Get()->SetName(this); + } + + /// + public GraphicsDevice GraphicsDevice { get; } + + /// + /// Gets the width of the current texture. + /// + public int Width => (int)this.d3D12PlacedSubresourceFootprint.Footprint.Width; + + /// + /// Gets the instance currently mapped. + /// + internal ID3D12Resource* D3D12Resource => this.d3D12Resource; + + /// + /// Gets the value for the current resource. + /// + internal ref readonly D3D12_PLACED_SUBRESOURCE_FOOTPRINT D3D12PlacedSubresourceFootprint => ref this.d3D12PlacedSubresourceFootprint; + + /// + public Memory Memory + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + using var _0 = GetReferenceTrackingLease(); + + return new MemoryManager(this).Memory; + } + } + + /// + public Span Span + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + using var _0 = GetReferenceTrackingLease(); + + return new(this.mappedData, Width); + } + } + + /// + private protected sealed override void OnDispose() + { + this.d3D12Resource.Dispose(); +#if NET6_0_OR_GREATER + this.allocation.Dispose(); +#endif + + if (GraphicsDevice is GraphicsDevice device) + { + device.UnregisterAllocatedResource(); + } + } + + /// + /// Throws a if the target device doesn't match the current one. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void ThrowIfDeviceMismatch(GraphicsDevice device) + { + if (GraphicsDevice != device) + { + GraphicsDeviceMismatchException.Throw(this, device); + } + } + + /// + /// A implementation wrapping a instance. + /// + private sealed class MemoryManager : MemoryManager + { + /// + /// The in use. + /// + private readonly TransferTexture1D buffer; + + /// + /// Creates a new instance for a given buffer. + /// + /// The in use. + public MemoryManager(TransferTexture1D buffer) + { + this.buffer = buffer; + } + + /// + public override Memory Memory + { + get => CreateMemory(this.buffer.Width); + } + + /// + public override Span GetSpan() + { + return this.buffer.Span; + } + + /// + public override MemoryHandle Pin(int elementIndex = 0) + { + Guard.IsEqualTo(elementIndex, 0); + + using var _0 = this.buffer.GetReferenceTrackingLease(); + + return new(this.buffer.mappedData); + } + + /// + public override void Unpin() + { + } + + /// + protected override void Dispose(bool disposing) + { + } + } +} diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs index 61c0c892..05bc33e4 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs @@ -44,8 +44,8 @@ public unsafe abstract class TransferTexture2D : NativeObject, IGraphicsResou /// Creates a new instance with the specified parameters. /// /// The associated with the current instance. - /// The height of the texture. /// The width of the texture. + /// The height of the texture. /// The resource type for the current texture. /// The allocation mode to use for the new resource. private protected TransferTexture2D(GraphicsDevice device, int width, int height, ResourceType resourceType, AllocationMode allocationMode) diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs index 5f310119..701399b1 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs @@ -44,8 +44,8 @@ public unsafe abstract class TransferTexture3D : NativeObject, IGraphicsResou /// Creates a new instance with the specified parameters. /// /// The associated with the current instance. - /// The height of the texture. /// The width of the texture. + /// The height of the texture. /// The depth of the texture. /// The resource type for the current texture. /// The allocation mode to use for the new resource. From 0b6d2b0ddf14e8d63fb4ad4c3586043fa86b3c8e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 29 Aug 2022 00:58:59 +0200 Subject: [PATCH 02/17] Add readback and upload transfer texture 1D types --- .../Debug/TransferTexture1DDebugView{T}.cs | 26 +++++++++++++++ .../Resources/ReadBackTexture1D{T}.cs | 33 +++++++++++++++++++ .../Graphics/Resources/UploadTexture1D{T}.cs | 33 +++++++++++++++++++ 3 files changed, 92 insertions(+) create mode 100644 src/ComputeSharp/Graphics/Resources/Debug/TransferTexture1DDebugView{T}.cs create mode 100644 src/ComputeSharp/Graphics/Resources/ReadBackTexture1D{T}.cs create mode 100644 src/ComputeSharp/Graphics/Resources/UploadTexture1D{T}.cs diff --git a/src/ComputeSharp/Graphics/Resources/Debug/TransferTexture1DDebugView{T}.cs b/src/ComputeSharp/Graphics/Resources/Debug/TransferTexture1DDebugView{T}.cs new file mode 100644 index 00000000..7b277889 --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/Debug/TransferTexture1DDebugView{T}.cs @@ -0,0 +1,26 @@ +using System.Diagnostics; + +namespace ComputeSharp.Resources.Debug; + +/// +/// A debug proxy used to display items in a instance. +/// +/// The type of items to display. +internal sealed class TransferTexture1DDebugView + where T : unmanaged +{ + /// + /// Initializes a new instance of the class with the specified parameters. + /// + /// The input instance with the items to display. + public TransferTexture1DDebugView(TransferTexture1D? texture) + { + Items = texture?.Span.ToArray(); + } + + /// + /// Gets the items to display for the current instance. + /// + [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] + public T[]? Items { get; } +} diff --git a/src/ComputeSharp/Graphics/Resources/ReadBackTexture1D{T}.cs b/src/ComputeSharp/Graphics/Resources/ReadBackTexture1D{T}.cs new file mode 100644 index 00000000..7ee3a5f9 --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/ReadBackTexture1D{T}.cs @@ -0,0 +1,33 @@ +using System.Diagnostics; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Resources; +using ComputeSharp.Resources.Debug; + +namespace ComputeSharp; + +/// +/// A representing a typed 1D texture stored on CPU memory, that can be used to transfer back from the GPU. +/// +/// The type of items stored on the texture. +[DebuggerTypeProxy(typeof(TransferTexture1DDebugView<>))] +[DebuggerDisplay("{ToString(),raw}")] +public sealed class ReadBackTexture1D : TransferTexture1D + where T : unmanaged +{ + /// + /// Creates a new instance with the specified parameters. + /// + /// The associated with the current instance. + /// The width of the texture. + /// The allocation mode to use for the new resource. + internal ReadBackTexture1D(GraphicsDevice device, int width, AllocationMode allocationMode) + : base(device, width, ResourceType.ReadBack, allocationMode) + { + } + + /// + public override string ToString() + { + return $"ComputeSharp.ReadBackTexture1D<{typeof(T)}>[{Width}]"; + } +} diff --git a/src/ComputeSharp/Graphics/Resources/UploadTexture1D{T}.cs b/src/ComputeSharp/Graphics/Resources/UploadTexture1D{T}.cs new file mode 100644 index 00000000..53f6a43d --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/UploadTexture1D{T}.cs @@ -0,0 +1,33 @@ +using System.Diagnostics; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Resources; +using ComputeSharp.Resources.Debug; + +namespace ComputeSharp; + +/// +/// A representing a typed 1D texture stored on CPU memory, that can be used to transfer data to the GPU. +/// +/// The type of items stored on the texture. +[DebuggerTypeProxy(typeof(TransferTexture1DDebugView<>))] +[DebuggerDisplay("{ToString(),raw}")] +public sealed class UploadTexture1D : TransferTexture1D + where T : unmanaged +{ + /// + /// Creates a new instance with the specified parameters. + /// + /// The associated with the current instance. + /// The width of the texture. + /// The allocation mode to use for the new resource. + internal UploadTexture1D(GraphicsDevice device, int width, AllocationMode allocationMode) + : base(device, width, ResourceType.Upload, allocationMode) + { + } + + /// + public override string ToString() + { + return $"ComputeSharp.UploadTexture1D<{typeof(T)}>[{Width}]"; + } +} From 61d85829cbb503c5958cc9015d9bddafaf98464c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 29 Aug 2022 01:13:24 +0200 Subject: [PATCH 03/17] Add Texture1D type --- .../GraphicsDeviceMismatchException.cs | 24 + .../Extensions/Interop/AllocatorExtensions.cs | 51 ++ .../Interop/ID3D12DeviceExtensions.cs | 92 +++ .../Resources/Abstract/Texture1D{T}.cs | 598 ++++++++++++++++++ .../Resources/Abstract/Texture2D{T}.cs | 2 +- .../Resources/Abstract/Texture3D{T}.cs | 2 +- 6 files changed, 767 insertions(+), 2 deletions(-) create mode 100644 src/ComputeSharp/Graphics/Resources/Abstract/Texture1D{T}.cs diff --git a/src/ComputeSharp/Graphics/Exceptions/GraphicsDeviceMismatchException.cs b/src/ComputeSharp/Graphics/Exceptions/GraphicsDeviceMismatchException.cs index 6283a35b..2569600e 100644 --- a/src/ComputeSharp/Graphics/Exceptions/GraphicsDeviceMismatchException.cs +++ b/src/ComputeSharp/Graphics/Exceptions/GraphicsDeviceMismatchException.cs @@ -55,6 +55,18 @@ public sealed class GraphicsDeviceMismatchException : InvalidOperationException throw Create(buffer, buffer.GraphicsDevice, device); } + /// + /// Throws a new instance from the specified parameters. + /// + /// The type of values in the input buffer. + /// The input that was used. + /// The target instance that was used. + internal static void Throw(Texture1D texture, GraphicsDevice device) + where T : unmanaged + { + throw Create(texture, texture.GraphicsDevice, device); + } + /// /// Throws a new instance from the specified parameters. /// @@ -91,6 +103,18 @@ public sealed class GraphicsDeviceMismatchException : InvalidOperationException throw Create(buffer, buffer.GraphicsDevice, device); } + /// + /// Throws a new instance from the specified parameters. + /// + /// The type of values in the input buffer. + /// The input that was used. + /// The target instance that was used. + internal static void Throw(TransferTexture1D texture, GraphicsDevice device) + where T : unmanaged + { + throw Create(texture, texture.GraphicsDevice, device); + } + /// /// Throws a new instance from the specified parameters. /// diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/AllocatorExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/AllocatorExtensions.cs index fd451d38..c765cd21 100644 --- a/src/ComputeSharp/Graphics/Extensions/Interop/AllocatorExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/Interop/AllocatorExtensions.cs @@ -90,6 +90,57 @@ internal static unsafe class AllocatorExtensions return allocation.Move(); } + /// + /// Creates a resource for a given 1D texture type. + /// + /// The instance in use. + /// The instance to use, if any. + /// The resource type currently in use. + /// The allocation mode to use for the new resource. + /// The value to use. + /// The width of the texture resource. + /// The default value for the resource. + /// An reference for the current object. + public static ComPtr CreateResource( + this ref D3D12MA_Allocator allocator, + D3D12MA_Pool* pool, + ResourceType resourceType, + AllocationMode allocationMode, + DXGI_FORMAT dxgiFormat, + uint width, + out D3D12_RESOURCE_STATES d3D12ResourceStates) + { + D3D12MA_ALLOCATION_FLAGS allocationFlags = allocationMode == AllocationMode.Default ? D3D12MA_ALLOCATION_FLAG_NONE : D3D12MA_ALLOCATION_FLAG_COMMITTED; + D3D12_RESOURCE_FLAGS d3D12ResourceFlags; + + (d3D12ResourceFlags, d3D12ResourceStates) = resourceType switch + { + ResourceType.ReadOnly => (D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COMMON), + ResourceType.ReadWrite => (D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + _ => ThrowHelper.ThrowArgumentException<(D3D12_RESOURCE_FLAGS, D3D12_RESOURCE_STATES)>() + }; + + using ComPtr allocation = default; + + D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex1D(dxgiFormat, width, mipLevels: 1, flags: d3D12ResourceFlags); + + D3D12MA_ALLOCATION_DESC allocationDesc = default; + allocationDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT; + allocationDesc.Flags = allocationFlags; + allocationDesc.CustomPool = pool; + + allocator.CreateResource( + &allocationDesc, + &d3D12ResourceDescription, + d3D12ResourceStates, + null, + allocation.GetAddressOf(), + null, + null).Assert(); + + return allocation.Move(); + } + /// /// Creates a resource for a given 2D texture type. /// diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12DeviceExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12DeviceExtensions.cs index 74ce050d..4bf28a0a 100644 --- a/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12DeviceExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12DeviceExtensions.cs @@ -117,6 +117,66 @@ internal static unsafe class ID3D12DeviceExtensions return d3D12Resource.Move(); } + /// + /// Creates a committed resource for a given 1D texture type. + /// + /// The instance in use. + /// The resource type currently in use. + /// The value to use. + /// The width of the texture resource. + /// Indicates whether or not the current device has a cache coherent UMA architecture. + /// The default value for the resource. + /// An reference for the current texture. + public static ComPtr CreateCommittedResource( + this ref ID3D12Device d3D12Device, + ResourceType resourceType, + DXGI_FORMAT dxgiFormat, + uint width, + bool isCacheCoherentUMA, + out D3D12_RESOURCE_STATES d3D12ResourceStates) + { + D3D12_RESOURCE_FLAGS d3D12ResourceFlags; + + (d3D12ResourceFlags, d3D12ResourceStates) = resourceType switch + { + ResourceType.ReadOnly => (D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COMMON), + ResourceType.ReadWrite => (D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + _ => ThrowHelper.ThrowArgumentException<(D3D12_RESOURCE_FLAGS, D3D12_RESOURCE_STATES)>() + }; + + using ComPtr d3D12Resource = default; + + D3D12_HEAP_PROPERTIES d3D12HeapProperties; + d3D12HeapProperties.CreationNodeMask = 1; + d3D12HeapProperties.VisibleNodeMask = 1; + + if (isCacheCoherentUMA) + { + d3D12HeapProperties.Type = D3D12_HEAP_TYPE_CUSTOM; + d3D12HeapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; + d3D12HeapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; + } + else + { + d3D12HeapProperties.Type = D3D12_HEAP_TYPE_DEFAULT; + d3D12HeapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; + d3D12HeapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; + } + + D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex1D(dxgiFormat, width, mipLevels: 1, flags: d3D12ResourceFlags); + + d3D12Device.CreateCommittedResource( + &d3D12HeapProperties, + D3D12_HEAP_FLAG_NONE, + &d3D12ResourceDescription, + d3D12ResourceStates, + null, + Windows.__uuidof(), + d3D12Resource.GetVoidAddressOf()).Assert(); + + return d3D12Resource.Move(); + } + /// /// Creates a committed resource for a given 2D texture type. /// @@ -551,6 +611,38 @@ internal static unsafe class ID3D12DeviceExtensions return d3D12GraphicsCommandList.Move(); } + /// + /// Gets the layout data for a target resource. + /// + /// The target to use to get the layout info. + /// The value to use. + /// The width of the texture resource. + /// The resulting layout info for the resource. + /// The size in bytes of each row in the resource. + /// The total number of bytes for the resource. + public static void GetCopyableFootprint( + this ref ID3D12Device d3D12Device, + DXGI_FORMAT dxgiFormat, + uint width, + out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprint, + out ulong rowSizeInBytes, + out ulong totalSizeInBytes) + { + D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex1D(dxgiFormat, width); + ulong a; + ulong b; + + fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* p = &d3D12PlacedSubresourceFootprint) + { + uint _; + + d3D12Device.GetCopyableFootprints(&d3D12ResourceDescription, 0, 1, 0, p, &_, &a, &b); + } + + rowSizeInBytes = a; + totalSizeInBytes = b; + } + /// /// Gets the layout data for a target resource. /// diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture1D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture1D{T}.cs new file mode 100644 index 00000000..daf616b7 --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture1D{T}.cs @@ -0,0 +1,598 @@ +using System; +using System.Runtime.CompilerServices; +using CommunityToolkit.Diagnostics; +using ComputeSharp.__Internals; +using ComputeSharp.Exceptions; +using ComputeSharp.Graphics.Commands; +using ComputeSharp.Graphics.Commands.Interop; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.Graphics.Helpers; +using ComputeSharp.Graphics.Resources.Helpers; +using ComputeSharp.Graphics.Resources.Interop; +using ComputeSharp.Interop; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE; +using static TerraFX.Interop.DirectX.D3D12_RESOURCE_STATES; +using static TerraFX.Interop.DirectX.D3D12_SRV_DIMENSION; +using static TerraFX.Interop.DirectX.D3D12_UAV_DIMENSION; +using ResourceType = ComputeSharp.Graphics.Resources.Enums.ResourceType; + +#pragma warning disable CS0618 + +namespace ComputeSharp.Resources; + +/// +/// A representing a typed 1D texture stored on GPU memory. +/// +/// The type of items stored on the texture. +public unsafe abstract class Texture1D : NativeObject, IGraphicsResource, GraphicsResourceHelper.IGraphicsResource + where T : unmanaged +{ +#if NET6_0_OR_GREATER + /// + /// The instance used to retrieve . + /// + private ComPtr allocation; +#endif + + /// + /// The instance currently mapped. + /// + private ComPtr d3D12Resource; + + /// + /// The instance for the current resource. + /// + private readonly ID3D12ResourceDescriptorHandles d3D12ResourceDescriptorHandles; + + /// + /// The value to use for copy operations. + /// + private readonly D3D12_COMMAND_LIST_TYPE d3D12CommandListType; + + /// + /// The description for the current resource. + /// + private readonly D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprint; + + /// + /// The current value for the current resource. + /// + private D3D12_RESOURCE_STATES d3D12ResourceState; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The associated with the current instance. + /// The width of the texture. + /// The resource type for the current texture. + /// The allocation mode to use for the new resource. + /// The format support for the current texture type. + private protected Texture1D(GraphicsDevice device, int width, ResourceType resourceType, AllocationMode allocationMode, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) + { + Guard.IsBetweenOrEqualTo(width, 1, D3D12.D3D12_REQ_TEXTURE1D_U_DIMENSION); + + using var _0 = device.GetReferenceTrackingLease(); + + device.ThrowIfDeviceLost(); + + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), d3D12FormatSupport)) + { + UnsupportedTextureTypeException.ThrowForTexture1D(); + } + + GraphicsDevice = device; + +#if NET6_0_OR_GREATER + this.allocation = device.Allocator->CreateResource( + device.Pool, + resourceType, + allocationMode, + DXGIFormatHelper.GetForType(), + (uint)width, + out this.d3D12ResourceState); + + this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); +#else + this.d3D12Resource = device.D3D12Device->CreateCommittedResource( + resourceType, + DXGIFormatHelper.GetForType(), + (uint)width, + device.IsCacheCoherentUMA, + out this.d3D12ResourceState); +#endif + + this.d3D12CommandListType = this.d3D12ResourceState == D3D12_RESOURCE_STATE_COMMON + ? D3D12_COMMAND_LIST_TYPE_COPY + : D3D12_COMMAND_LIST_TYPE_COMPUTE; + + device.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + out this.d3D12PlacedSubresourceFootprint, + out _, + out _); + + device.RegisterAllocatedResource(); + device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); + + switch (resourceType) + { + case ResourceType.ReadOnly: + device.D3D12Device->CreateShaderResourceView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_SRV_DIMENSION_TEXTURE1D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + break; + case ResourceType.ReadWrite: + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE1D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + device.D3D12Device->CreateUnorderedAccessView(this.d3D12Resource.Get(), DXGIFormatHelper.GetForType(), D3D12_UAV_DIMENSION_TEXTURE1D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); + break; + } + + this.d3D12Resource.Get()->SetName(this); + } + + /// + public GraphicsDevice GraphicsDevice { get; } + + /// + /// Gets the width of the current texture. + /// + public int Width => (int)this.d3D12PlacedSubresourceFootprint.Footprint.Width; + + /// + /// Gets the instance currently mapped. + /// + internal ID3D12Resource* D3D12Resource => this.d3D12Resource; + + /// + /// Gets the instance for the current resource. + /// + internal D3D12_GPU_DESCRIPTOR_HANDLE D3D12GpuDescriptorHandle => this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; + + /// + /// Reads the contents of the specified range from the current instance and writes them into a target memory area. + /// + /// The target memory area to write data to. + /// The size of the target memory area to write data to. + /// The horizontal offset in the source texture. + /// The width of the memory area to copy. + internal void CopyTo(ref T destination, int size, int sourceOffsetX, int width) + { + Guard.IsInRange(sourceOffsetX, 0, Width); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); + Guard.IsGreaterThanOrEqualTo(size, width); + + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + GraphicsDevice.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintDestination, + out ulong rowSizeInBytes, + out ulong totalSizeInBytes); + +#if NET6_0_OR_GREATER + using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( + GraphicsDevice.Pool, + ResourceType.ReadBack, + AllocationMode.Default, + totalSizeInBytes); + + using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); +#else + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( + ResourceType.ReadBack, + totalSizeInBytes, + GraphicsDevice.IsCacheCoherentUMA); +#endif + + using (CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType)) + { + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + } + + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: d3D12Resource.Get(), + &d3D12PlacedSubresourceFootprintDestination, + destinationX: 0, + destinationY: 0, + destinationZ: 0, + d3D12ResourceSource: D3D12Resource, + sourceX: (uint)sourceOffsetX, + sourceY: 0, + sourceZ: 0, + (uint)width, + height: 1, + depth: 1); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); + } + + using ID3D12ResourceMap resource = d3D12Resource.Get()->Map(); + + fixed (void* destinationPointer = &destination) + { + Buffer.MemoryCopy( + source: resource.Pointer, + destination: destinationPointer, + destinationSizeInBytes: rowSizeInBytes, + sourceBytesToCopy: rowSizeInBytes); + } + } + + /// + /// Reads the contents of the specified range from the current instance and writes them into a target instance. + /// + /// The target instance to write data to. + /// The horizontal offset within . + /// The horizontal offset in the source texture. + /// The width of the memory area to copy. + internal void CopyTo(Texture1D destination, int sourceOffsetX, int destinationOffsetX, int width) + { + Guard.IsInRange(sourceOffsetX, 0, Width); + Guard.IsInRange(destinationOffsetX, 0, destination.Width); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(width, 1, destination.Width); + Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); + + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = destination.GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + + D3D12_COMMAND_LIST_TYPE d3D12CommandListType = + this.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE || + destination.d3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE + ? D3D12_COMMAND_LIST_TYPE_COMPUTE + : D3D12_COMMAND_LIST_TYPE_COPY; + + using CommandList copyCommandList = new(GraphicsDevice, d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, destination.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + } + + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: destination.D3D12Resource, + (uint)destinationOffsetX, + destinationY: 0, + destinationZ: 0, + d3D12ResourceSource: D3D12Resource, + (uint)sourceOffsetX, + sourceY: 0, + sourceZ: 0, + (uint)width, + height: 1, + depth: 1); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(destination.D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, destination.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); + } + + /// + /// Reads the contents of the specified range from the current instance and writes them into a target instance. + /// + /// The target instance to write data to. + /// The horizontal offset in the source texture. + /// The horizontal offset within . + /// The width of the memory area to copy. + internal void CopyTo(ReadBackTexture1D destination, int sourceOffsetX, int destinationOffsetX, int width) + { + Guard.IsInRange(sourceOffsetX, 0, Width); + Guard.IsInRange(destinationOffsetX, 0, destination.Width); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(width, 1, destination.Width); + Guard.IsBetweenOrEqualTo(destinationOffsetX + width, 1, destination.Width, nameof(destinationOffsetX)); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, Width, nameof(sourceOffsetX)); + + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = destination.GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + destination.ThrowIfDeviceMismatch(GraphicsDevice); + + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); + } + + fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintDestination = &destination.D3D12PlacedSubresourceFootprint) + { + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: destination.D3D12Resource, + d3D12PlacedSubresourceFootprintDestination, + (uint)destinationOffsetX, + destinationY: 0, + destinationZ: 0, + d3D12ResourceSource: D3D12Resource, + (uint)sourceOffsetX, + sourceY: 0, + sourceZ: 0, + (uint)width, + height: 1, + depth: 1); + } + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_SOURCE, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); + } + + /// + /// Writes the contents of a given memory area to a specified area of the current instance. + /// + /// The input memory area to read data from. + /// The size of the memory area to read data from. + /// The horizontal offset in the destination texture. + /// The width of the memory area to write to. + internal void CopyFrom(ref T source, int size, int destinationOffsetX, int width) + { + Guard.IsInRange(destinationOffsetX, 0, Width); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); + Guard.IsGreaterThanOrEqualTo(size, width); + + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + GraphicsDevice.D3D12Device->GetCopyableFootprint( + DXGIFormatHelper.GetForType(), + (uint)width, + out D3D12_PLACED_SUBRESOURCE_FOOTPRINT d3D12PlacedSubresourceFootprintSource, + out ulong rowSizeInBytes, + out ulong totalSizeInBytes); + +#if NET6_0_OR_GREATER + using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( + GraphicsDevice.Pool, + ResourceType.Upload, + AllocationMode.Default, + totalSizeInBytes); + + using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); +#else + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( + ResourceType.Upload, + totalSizeInBytes, + GraphicsDevice.IsCacheCoherentUMA); +#endif + + using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) + fixed (void* sourcePointer = &source) + { + Buffer.MemoryCopy( + source: sourcePointer, + destination: resource.Pointer, + destinationSizeInBytes: rowSizeInBytes, + sourceBytesToCopy: rowSizeInBytes); + } + + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + } + + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: D3D12Resource, + destinationX: (uint)destinationOffsetX, + destinationY: 0, + destinationZ: 0, + d3D12ResourceSource: d3D12Resource.Get(), + &d3D12PlacedSubresourceFootprintSource, + sourceX: 0, + sourceY: 0, + sourceZ: 0, + (uint)width, + height: 1, + depth: 1); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); + } + + /// + /// Writes the contents of a given instance to a specified area of the current instance. + /// + /// The input instance to read data from. + /// The horizontal offset within . + /// The horizontal offset in the destination texture. + /// The width of the memory area to write to. + internal void CopyFrom(UploadTexture1D source, int sourceOffsetX, int destinationOffsetX, int width) + { + Guard.IsInRange(sourceOffsetX, 0, source.Width); + Guard.IsInRange(destinationOffsetX, 0, Width); + Guard.IsBetweenOrEqualTo(width, 1, Width); + Guard.IsBetweenOrEqualTo(width, 1, source.Width); + Guard.IsLessThanOrEqualTo(sourceOffsetX + width, source.Width, nameof(sourceOffsetX)); + Guard.IsLessThanOrEqualTo(destinationOffsetX + width, Width, nameof(destinationOffsetX)); + + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + using var _2 = source.GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + source.ThrowIfDeviceMismatch(GraphicsDevice); + + using CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType); + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, this.d3D12ResourceState, D3D12_RESOURCE_STATE_COPY_DEST); + } + + fixed (D3D12_PLACED_SUBRESOURCE_FOOTPRINT* d3D12PlacedSubresourceFootprintSource = &source.D3D12PlacedSubresourceFootprint) + { + copyCommandList.D3D12GraphicsCommandList->CopyTextureRegion( + d3D12ResourceDestination: D3D12Resource, + (uint)destinationOffsetX, + destinationY: 0, + destinationZ: 0, + d3D12ResourceSource: source.D3D12Resource, + d3D12PlacedSubresourceFootprintSource, + (uint)sourceOffsetX, + sourceY: 0, + sourceZ: 0, + (uint)width, + height: 1, + depth: 1); + } + + if (copyCommandList.D3D12CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE) + { + copyCommandList.D3D12GraphicsCommandList->TransitionBarrier(D3D12Resource, D3D12_RESOURCE_STATE_COPY_DEST, this.d3D12ResourceState); + } + + copyCommandList.ExecuteAndWaitForCompletion(); + } + + /// + private protected override void OnDispose() + { + this.d3D12Resource.Dispose(); +#if NET6_0_OR_GREATER + this.allocation.Dispose(); +#endif + + if (GraphicsDevice is GraphicsDevice device) + { + device.UnregisterAllocatedResource(); + device.ReturnShaderResourceViewDescriptorHandles(in this.d3D12ResourceDescriptorHandles); + } + } + + /// + /// Throws an if the current resource is not in a readonly state. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected void ThrowIfIsNotInReadOnlyState() + { + if (this.d3D12ResourceState == D3D12_RESOURCE_STATE_UNORDERED_ACCESS) + { + static void Throw() + { + throw new InvalidOperationException( + "The texture is not currently in readonly mode. This API can only be used when creating a compute graph with " + + "the ComputeContext type, and after having used ComputeContext.Transition() to change the state of the texture."); + } + + Throw(); + } + } + + /// + /// Throws a if the target device doesn't match the current one. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void ThrowIfDeviceMismatch(GraphicsDevice device) + { + if (GraphicsDevice != device) + { + GraphicsDeviceMismatchException.Throw(this, device); + } + } + + /// + internal (D3D12_GPU_DESCRIPTOR_HANDLE Gpu, D3D12_CPU_DESCRIPTOR_HANDLE Cpu) ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device, out bool isNormalized) + { + using var _0 = GetReferenceTrackingLease(); + + ThrowIfDeviceMismatch(device); + + isNormalized = DXGIFormatHelper.IsNormalizedType(); + + return (this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandleNonShaderVisible); + } + + /// + internal ID3D12Resource* ValidateAndGetID3D12Resource(GraphicsDevice device, out Lease lease) + { + lease = GetReferenceTrackingLease(); + + ThrowIfDeviceMismatch(device); + + return D3D12Resource; + } + + /// + internal (D3D12_RESOURCE_STATES Before, D3D12_RESOURCE_STATES After) ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource, out Lease lease) + { + lease = GetReferenceTrackingLease(); + + ThrowIfDeviceMismatch(device); + + D3D12_RESOURCE_STATES d3D12ResourceStatesBefore = this.d3D12ResourceState; + D3D12_RESOURCE_STATES d3D12ResourceStatesAfter = ResourceStateHelper.GetD3D12ResourceStates(resourceState); + + this.d3D12ResourceState = d3D12ResourceStatesAfter; + + d3D12Resource = D3D12Resource; + + return (d3D12ResourceStatesBefore, d3D12ResourceStatesAfter); + } + + /// + D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) + { + using var _0 = GetReferenceTrackingLease(); + + ThrowIfDeviceMismatch(device); + + return D3D12GpuDescriptorHandle; + } + + /// + (D3D12_GPU_DESCRIPTOR_HANDLE, D3D12_CPU_DESCRIPTOR_HANDLE) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device, out bool isNormalized) + { + return ValidateAndGetGpuAndCpuDescriptorHandlesForClear(device, out isNormalized); + } + + /// + ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device, out Lease lease) + { + return ValidateAndGetID3D12Resource(device, out lease); + } + + /// + (D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource, out Lease lease) + { + return ValidateAndGetID3D12ResourceAndTransitionStates(device, resourceState, out d3D12Resource, out lease); + } +} diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs index 8527dc70..65d237f1 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs @@ -65,8 +65,8 @@ public unsafe abstract class Texture2D : NativeObject, IGraphicsResource, Gra /// Creates a new instance with the specified parameters. /// /// The associated with the current instance. - /// The height of the texture. /// The width of the texture. + /// The height of the texture. /// The resource type for the current texture. /// The allocation mode to use for the new resource. /// The format support for the current texture type. diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs index 7871b946..8f36b574 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs @@ -65,8 +65,8 @@ public unsafe abstract class Texture3D : NativeObject, IGraphicsResource, Gra /// Creates a new instance with the specified parameters. /// /// The associated with the current instance. - /// The height of the texture. /// The width of the texture. + /// The height of the texture. /// The depth of the texture. /// The resource type for the current texture. /// The allocation mode to use for the new resource. From 3e8d751b28a1e0e0e12b82aa98c67d69e460169f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 29 Aug 2022 01:14:37 +0200 Subject: [PATCH 04/17] Add Read[Only|Write]Texture1D types --- .../Resources/Debug/Texture1DDebugView{T}.cs | 33 +++++++++++++++ .../Resources/ReadOnlyTexture1D{T}.cs | 42 +++++++++++++++++++ .../Resources/ReadWriteTexture1D{T}.cs | 42 +++++++++++++++++++ 3 files changed, 117 insertions(+) create mode 100644 src/ComputeSharp/Graphics/Resources/Debug/Texture1DDebugView{T}.cs create mode 100644 src/ComputeSharp/Graphics/Resources/ReadOnlyTexture1D{T}.cs create mode 100644 src/ComputeSharp/Graphics/Resources/ReadWriteTexture1D{T}.cs diff --git a/src/ComputeSharp/Graphics/Resources/Debug/Texture1DDebugView{T}.cs b/src/ComputeSharp/Graphics/Resources/Debug/Texture1DDebugView{T}.cs new file mode 100644 index 00000000..a36c242d --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/Debug/Texture1DDebugView{T}.cs @@ -0,0 +1,33 @@ +using System.Diagnostics; + +namespace ComputeSharp.Resources.Debug; + +/// +/// A debug proxy used to display items in a instance. +/// +/// The type of items to display. +internal sealed class Texture1DDebugView + where T : unmanaged +{ + /// + /// Initializes a new instance of the class with the specified parameters. + /// + /// The input instance with the items to display. + public Texture1DDebugView(Texture1D? texture) + { + if (texture is not null) + { + T[] items = new T[texture.Width]; + + texture.CopyTo(ref items[0], items.Length, 0, texture.Width); + + Items = items; + } + } + + /// + /// Gets the items to display for the current instance. + /// + [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] + public T[]? Items { get; } +} diff --git a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture1D{T}.cs b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture1D{T}.cs new file mode 100644 index 00000000..2ebbb317 --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture1D{T}.cs @@ -0,0 +1,42 @@ +using System.Diagnostics; +using ComputeSharp.Exceptions; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Resources; +using ComputeSharp.Resources.Debug; +using static TerraFX.Interop.DirectX.D3D12_FORMAT_SUPPORT1; + +namespace ComputeSharp; + +/// +/// A representing a typed readonly 1D texture stored on GPU memory. +/// +/// The type of items stored on the texture. +[DebuggerTypeProxy(typeof(Texture1DDebugView<>))] +[DebuggerDisplay("{ToString(),raw}")] +public sealed class ReadOnlyTexture1D : Texture1D + where T : unmanaged +{ + /// + /// Creates a new instance with the specified parameters. + /// + /// The associated with the current instance. + /// The width of the texture. + /// The allocation mode to use for the new resource. + internal ReadOnlyTexture1D(GraphicsDevice device, int width, AllocationMode allocationMode) + : base(device, width, ResourceType.ReadOnly, allocationMode, D3D12_FORMAT_SUPPORT1_TEXTURE1D) + { + } + + /// + /// Gets a single value from the current readonly texture. + /// + /// The horizontal offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref readonly T this[int x] => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture1D)}[{typeof(int)}]"); + + /// + public override string ToString() + { + return $"ComputeSharp.ReadOnlyTexture1D<{typeof(T)}>[{Width}]"; + } +} diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture1D{T}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture1D{T}.cs new file mode 100644 index 00000000..4cd863ad --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture1D{T}.cs @@ -0,0 +1,42 @@ +using System.Diagnostics; +using ComputeSharp.Exceptions; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Resources; +using ComputeSharp.Resources.Debug; +using static TerraFX.Interop.DirectX.D3D12_FORMAT_SUPPORT1; + +namespace ComputeSharp; + +/// +/// A representing a typed read write 1D texture stored on GPU memory. +/// +/// The type of items stored on the texture. +[DebuggerTypeProxy(typeof(Texture1DDebugView<>))] +[DebuggerDisplay("{ToString(),raw}")] +public sealed partial class ReadWriteTexture1D : Texture1D + where T : unmanaged +{ + /// + /// Creates a new instance with the specified parameters. + /// + /// The associated with the current instance. + /// The width of the texture. + /// The allocation mode to use for the new resource. + internal ReadWriteTexture1D(GraphicsDevice device, int width, AllocationMode allocationMode) + : base(device, width, ResourceType.ReadWrite, allocationMode, D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) + { + } + + /// + /// Gets a single value from the current writeable texture. + /// + /// The horizontal offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref T this[int x] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture1D)}[{typeof(int)}]"); + + /// + public override string ToString() + { + return $"ComputeSharp.ReadWriteTexture1D<{typeof(T)}>[{Width}]"; + } +} From 0d924830d9ef5c4027b52340a1e9c2a9eaacfa4f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 29 Aug 2022 01:16:28 +0200 Subject: [PATCH 05/17] Add interfaces for 1D texture types --- .../IReadOnlyNormalizedTexture1D{TPixel}.cs | 29 +++++++++++++++++++ .../Interfaces/IReadOnlyTexture1D{T}.cs | 29 +++++++++++++++++++ .../IReadWriteNormalizedTexture1D{TPixel}.cs | 22 ++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyNormalizedTexture1D{TPixel}.cs create mode 100644 src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture1D{T}.cs create mode 100644 src/ComputeSharp/Graphics/Resources/Interfaces/IReadWriteNormalizedTexture1D{TPixel}.cs diff --git a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyNormalizedTexture1D{TPixel}.cs b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyNormalizedTexture1D{TPixel}.cs new file mode 100644 index 00000000..eda6c900 --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyNormalizedTexture1D{TPixel}.cs @@ -0,0 +1,29 @@ +namespace ComputeSharp; + +/// +/// An interface representing a typed readonly 1D texture containing normalized pixel data stored on GPU memory. +/// This interface can only be used to wrap instances. +/// +/// The type of normalized pixels used on the GPU side. +public interface IReadOnlyNormalizedTexture1D : IGraphicsResource + where TPixel : unmanaged +{ + /// + /// Gets the width of the current texture. + /// + int Width { get; } + + /// + /// Gets a single value from the current readonly texture. + /// + /// The horizontal offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + ref readonly TPixel this[int x] { get; } + + /// + /// Retrieves a single value from the current readonly texture with linear sampling. + /// + /// The horizontal normalized offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + ref readonly TPixel Sample(float u); +} diff --git a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture1D{T}.cs b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture1D{T}.cs new file mode 100644 index 00000000..14ae0c64 --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture1D{T}.cs @@ -0,0 +1,29 @@ +namespace ComputeSharp; + +/// +/// An interface representing a typed readonly 1D texture containing raw data stored on GPU memory. +/// This interface can only be used to wrap instances. +/// +/// The type of raw data used on the GPU side. +public interface IReadOnlyTexture1D : IGraphicsResource + where T : unmanaged +{ + /// + /// Gets the width of the current texture. + /// + int Width { get; } + + /// + /// Gets a single value from the current readonly texture. + /// + /// The horizontal offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + ref readonly T this[int x] { get; } + + /// + /// Retrieves a single value from the current readonly texture with linear sampling. + /// + /// The horizontal normalized offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + ref readonly T Sample(float u); +} diff --git a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadWriteNormalizedTexture1D{TPixel}.cs b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadWriteNormalizedTexture1D{TPixel}.cs new file mode 100644 index 00000000..0d65f74d --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadWriteNormalizedTexture1D{TPixel}.cs @@ -0,0 +1,22 @@ +namespace ComputeSharp; + +/// +/// An interface representing a typed writeable 1D texture containing normalized pixel data stored on GPU memory. +/// This interface can only be used to wrap instances. +/// +/// The type of normalized pixels used on the GPU side. +public interface IReadWriteNormalizedTexture1D : IGraphicsResource + where TPixel : unmanaged +{ + /// + /// Gets the width of the current texture. + /// + int Width { get; } + + /// + /// Gets a single value from the current writeable texture. + /// + /// The horizontal offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + ref TPixel this[int x] { get; } +} From da3712950387fb67e4e6f35b5d02b19147eb919f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 29 Aug 2022 01:22:14 +0200 Subject: [PATCH 06/17] Add normalized 1D texture types --- .../Resources/ReadOnlyTexture1D{T,TPixel}.cs | 43 ++++++ .../ReadWriteTexture1D{T,TPixel}.ReadOnly.cs | 146 ++++++++++++++++++ .../Resources/ReadWriteTexture1D{T,TPixel}.cs | 40 +++++ .../ReadWriteTexture1D{T}.ReadOnly.cs | 146 ++++++++++++++++++ 4 files changed, 375 insertions(+) create mode 100644 src/ComputeSharp/Graphics/Resources/ReadOnlyTexture1D{T,TPixel}.cs create mode 100644 src/ComputeSharp/Graphics/Resources/ReadWriteTexture1D{T,TPixel}.ReadOnly.cs create mode 100644 src/ComputeSharp/Graphics/Resources/ReadWriteTexture1D{T,TPixel}.cs create mode 100644 src/ComputeSharp/Graphics/Resources/ReadWriteTexture1D{T}.ReadOnly.cs diff --git a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture1D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture1D{T,TPixel}.cs new file mode 100644 index 00000000..53315a0a --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture1D{T,TPixel}.cs @@ -0,0 +1,43 @@ +using System.Diagnostics; +using ComputeSharp.Exceptions; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Resources; +using ComputeSharp.Resources.Debug; +using static TerraFX.Interop.DirectX.D3D12_FORMAT_SUPPORT1; + +namespace ComputeSharp; + +/// +/// A representing a typed readonly 1D texture stored on GPU memory. +/// +/// The type of items stored on the texture. +/// The type of pixels used on the GPU side. +[DebuggerTypeProxy(typeof(Texture1DDebugView<>))] +[DebuggerDisplay("{ToString(),raw}")] +public sealed class ReadOnlyTexture1D : Texture1D, IReadOnlyNormalizedTexture1D + where T : unmanaged, IPixel + where TPixel : unmanaged +{ + /// + /// Creates a new instance with the specified parameters. + /// + /// The associated with the current instance. + /// The width of the texture. + /// The allocation mode to use for the new resource. + internal ReadOnlyTexture1D(GraphicsDevice device, int width, AllocationMode allocationMode) + : base(device, width, ResourceType.ReadOnly, allocationMode, D3D12_FORMAT_SUPPORT1_TEXTURE1D) + { + } + + /// + public ref readonly TPixel this[int x] => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture1D)}[{typeof(int)}]"); + + /// + public ref readonly TPixel Sample(float u) => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture1D)}.{nameof(Sample)}({typeof(float)})"); + + /// + public override string ToString() + { + return $"ComputeSharp.ReadOnlyTexture1D<{typeof(T)}, {typeof(TPixel)}>[{Width}]"; + } +} diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture1D{T,TPixel}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture1D{T,TPixel}.ReadOnly.cs new file mode 100644 index 00000000..7ed9ac15 --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture1D{T,TPixel}.ReadOnly.cs @@ -0,0 +1,146 @@ +using System; +using System.Runtime.CompilerServices; +using ComputeSharp.__Internals; +using ComputeSharp.Exceptions; +using ComputeSharp.Graphics.Commands.Interop; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.Graphics.Helpers; +using ComputeSharp.Interop; +using TerraFX.Interop.DirectX; +using static TerraFX.Interop.DirectX.D3D12_SRV_DIMENSION; + +#pragma warning disable CS0618 + +namespace ComputeSharp; + +/// +partial class ReadWriteTexture1D +{ + /// + /// The wrapping instance, if available. + /// + private ReadOnly? readOnlyWrapper; + + /// + internal IReadOnlyNormalizedTexture1D AsReadOnly() + { + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + ThrowIfIsNotInReadOnlyState(); + + ReadOnly? readOnlyWrapper = this.readOnlyWrapper; + + if (readOnlyWrapper is not null) + { + return readOnlyWrapper; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static ReadOnly InitializeWrapper(ReadWriteTexture1D texture) + { + return texture.readOnlyWrapper = new(texture); + } + + return InitializeWrapper(this); + } + + /// + private protected override void OnDispose() + { + base.OnDispose(); + + this.readOnlyWrapper?.Dispose(); + } + + /// + /// A wrapper for a resource that has been temporarily transitioned to readonly. + /// + private sealed unsafe class ReadOnly : NativeObject, IReadOnlyNormalizedTexture1D, GraphicsResourceHelper.IGraphicsResource + { + /// + /// The owning instance being wrapped. + /// + private readonly ReadWriteTexture1D owner; + + /// + /// The instance for the current resource. + /// + private readonly ID3D12ResourceDescriptorHandles d3D12ResourceDescriptorHandles; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The owning instance to wrap. + public ReadOnly(ReadWriteTexture1D owner) + { + owner.DangerousAddRef(); + + this.owner = owner; + + owner.GraphicsDevice.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); + + owner.GraphicsDevice.D3D12Device->CreateShaderResourceView(owner.D3D12Resource, DXGIFormatHelper.GetForType(), D3D12_SRV_DIMENSION_TEXTURE1D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + } + + /// + public ref readonly TPixel this[int x] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture1D.ReadOnly)}[{typeof(int)}]"); + + /// + public ref readonly TPixel Sample(float u) => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture1D.ReadOnly)}.{nameof(Sample)}({typeof(float)})"); + + /// + public int Width => this.owner.Width; + + /// + public GraphicsDevice GraphicsDevice => this.owner.GraphicsDevice; + + /// + D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) + { + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); + + this.owner.ThrowIfDeviceMismatch(device); + + return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; + } + + /// + (D3D12_GPU_DESCRIPTOR_HANDLE, D3D12_CPU_DESCRIPTOR_HANDLE) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device, out bool isNormalized) + { + throw new NotSupportedException("This operation cannot be performaned on a readonly wrapper."); + } + + /// + ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device, out Lease lease) + { + lease = GetReferenceTrackingLease(); + + using var _1 = this.owner.GetReferenceTrackingLease(); + + this.owner.ThrowIfDeviceMismatch(device); + + return this.owner.D3D12Resource; + } + + /// + (D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource, out Lease lease) + { + throw new NotSupportedException("This operation cannot be performaned on a readonly wrapper."); + } + + /// + private protected override void OnDispose() + { + this.owner.DangerousRelease(); + + if (this.owner.GraphicsDevice is GraphicsDevice device) + { + device.ReturnShaderResourceViewDescriptorHandles(in this.d3D12ResourceDescriptorHandles); + } + } + } +} diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture1D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture1D{T,TPixel}.cs new file mode 100644 index 00000000..b40d5b82 --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture1D{T,TPixel}.cs @@ -0,0 +1,40 @@ +using System.Diagnostics; +using ComputeSharp.Exceptions; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Resources; +using ComputeSharp.Resources.Debug; +using static TerraFX.Interop.DirectX.D3D12_FORMAT_SUPPORT1; + +namespace ComputeSharp; + +/// +/// A representing a typed read write 1D texture stored on GPU memory. +/// +/// The type of items stored on the texture. +/// The type of pixels used on the GPU side. +[DebuggerTypeProxy(typeof(Texture1DDebugView<>))] +[DebuggerDisplay("{ToString(),raw}")] +public sealed partial class ReadWriteTexture1D : Texture1D, IReadWriteNormalizedTexture1D + where T : unmanaged, IPixel + where TPixel : unmanaged +{ + /// + /// Creates a new instance with the specified parameters. + /// + /// The associated with the current instance. + /// The width of the texture. + /// The allocation mode to use for the new resource. + internal ReadWriteTexture1D(GraphicsDevice device, int width, AllocationMode allocationMode) + : base(device, width, ResourceType.ReadWrite, allocationMode, D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) + { + } + + /// + public ref TPixel this[int x] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture2D)}[{typeof(int)}]"); + + /// + public override string ToString() + { + return $"ComputeSharp.ReadWriteTexture1D<{typeof(T)}, {typeof(TPixel)}>[{Width}]"; + } +} diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture1D{T}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture1D{T}.ReadOnly.cs new file mode 100644 index 00000000..4f03c9b9 --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture1D{T}.ReadOnly.cs @@ -0,0 +1,146 @@ +using System; +using System.Runtime.CompilerServices; +using ComputeSharp.__Internals; +using ComputeSharp.Exceptions; +using ComputeSharp.Graphics.Commands.Interop; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.Graphics.Helpers; +using ComputeSharp.Interop; +using TerraFX.Interop.DirectX; +using static TerraFX.Interop.DirectX.D3D12_SRV_DIMENSION; + +#pragma warning disable CS0618 + +namespace ComputeSharp; + +/// +partial class ReadWriteTexture1D +{ + /// + /// The wrapping instance, if available. + /// + private ReadOnly? readOnlyWrapper; + + /// + public IReadOnlyTexture1D AsReadOnly() + { + using var _0 = GraphicsDevice.GetReferenceTrackingLease(); + using var _1 = GetReferenceTrackingLease(); + + GraphicsDevice.ThrowIfDeviceLost(); + + ThrowIfIsNotInReadOnlyState(); + + ReadOnly? readOnlyWrapper = this.readOnlyWrapper; + + if (readOnlyWrapper is not null) + { + return readOnlyWrapper; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static ReadOnly InitializeWrapper(ReadWriteTexture1D texture) + { + return texture.readOnlyWrapper = new(texture); + } + + return InitializeWrapper(this); + } + + /// + private protected override void OnDispose() + { + base.OnDispose(); + + this.readOnlyWrapper?.Dispose(); + } + + /// + /// A wrapper for a resource that has been temporarily transitioned to readonly. + /// + private sealed unsafe class ReadOnly : NativeObject, IReadOnlyTexture1D, GraphicsResourceHelper.IGraphicsResource + { + /// + /// The owning instance being wrapped. + /// + private readonly ReadWriteTexture1D owner; + + /// + /// The instance for the current resource. + /// + private readonly ID3D12ResourceDescriptorHandles d3D12ResourceDescriptorHandles; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The owning instance to wrap. + public ReadOnly(ReadWriteTexture1D owner) + { + owner.DangerousAddRef(); + + this.owner = owner; + + owner.GraphicsDevice.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); + + owner.GraphicsDevice.D3D12Device->CreateShaderResourceView(owner.D3D12Resource, DXGIFormatHelper.GetForType(), D3D12_SRV_DIMENSION_TEXTURE1D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + } + + /// + public ref readonly T this[int x] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture1D.ReadOnly)}[{typeof(int)}]"); + + /// + public ref readonly T Sample(float u) => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture1D.ReadOnly)}.{nameof(Sample)}({typeof(float)})"); + + /// + public int Width => this.owner.Width; + + /// + public GraphicsDevice GraphicsDevice => this.owner.GraphicsDevice; + + /// + D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) + { + using var _0 = GetReferenceTrackingLease(); + using var _1 = this.owner.GetReferenceTrackingLease(); + + this.owner.ThrowIfDeviceMismatch(device); + + return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; + } + + /// + (D3D12_GPU_DESCRIPTOR_HANDLE, D3D12_CPU_DESCRIPTOR_HANDLE) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device, out bool isNormalized) + { + throw new NotSupportedException("This operation cannot be performaned on a readonly wrapper."); + } + + /// + ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device, out Lease lease) + { + lease = GetReferenceTrackingLease(); + + using var _1 = this.owner.GetReferenceTrackingLease(); + + this.owner.ThrowIfDeviceMismatch(device); + + return this.owner.D3D12Resource; + } + + /// + (D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource, out Lease lease) + { + throw new NotSupportedException("This operation cannot be performaned on a readonly wrapper."); + } + + /// + private protected override void OnDispose() + { + this.owner.DangerousRelease(); + + if (this.owner.GraphicsDevice is GraphicsDevice device) + { + device.ReturnShaderResourceViewDescriptorHandles(in this.d3D12ResourceDescriptorHandles); + } + } + } +} From dbebf47a685f4ab9d51dd0cd33a846fb6873d8f8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 29 Aug 2022 01:31:37 +0200 Subject: [PATCH 07/17] Add InteropServices APIs for 1D textures --- .../Graphics/Interop/InteropServices.cs | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/ComputeSharp/Graphics/Interop/InteropServices.cs b/src/ComputeSharp/Graphics/Interop/InteropServices.cs index 5427cb64..f2847c0e 100644 --- a/src/ComputeSharp/Graphics/Interop/InteropServices.cs +++ b/src/ComputeSharp/Graphics/Interop/InteropServices.cs @@ -57,6 +57,24 @@ public static unsafe class InteropServices buffer.D3D12Resource->QueryInterface(riid, ppvObject).Assert(); } + /// + /// Gets the underlying COM object for a given resource, as a specified interface. This method invokes + /// IUnknown::QueryInterface. + /// + /// The type of items stored on the texture. + /// The input instance in use. + /// A reference to the interface identifier (IID) of the resource interface being queried for. + /// The address of a pointer to an interface with the IID specified in . + /// The instance has been disposed. + /// Thrown if the IUnknown::QueryInterface call doesn't return S_OK. + public static void GetID3D12Resource(Texture1D texture, Guid* riid, void** ppvObject) + where T : unmanaged + { + using var _0 = texture.GetReferenceTrackingLease(); + + texture.D3D12Resource->QueryInterface(riid, ppvObject).Assert(); + } + /// /// Gets the underlying COM object for a given resource, as a specified interface. This method invokes /// IUnknown::QueryInterface. @@ -187,6 +205,27 @@ public static unsafe class InteropServices return buffer.D3D12Resource->QueryInterface(riid, ppvObject); } + /// + /// Tries to get the underlying COM object for a given resource, as a specified interface. This method invokes + /// IUnknown::QueryInterface. + /// + /// The type of items stored on the texture. + /// The input instance in use. + /// A reference to the interface identifier (IID) of the resource interface being queried for. + /// The address of a pointer to an interface with the IID specified in . + /// + /// S_OK if the interface is supported, and E_NOINTERFACE otherwise. + /// If ppvObject (the address) is nullptr, then this method returns E_POINTER. + /// + /// The instance has been disposed. + public static int TryGetID3D12Resource(Texture1D texture, Guid* riid, void** ppvObject) + where T : unmanaged + { + using var _0 = texture.GetReferenceTrackingLease(); + + return texture.D3D12Resource->QueryInterface(riid, ppvObject); + } + /// /// Tries to get the underlying COM object for a given resource, as a specified interface. This method invokes /// IUnknown::QueryInterface. From 892e5f17f753abffc597ac36f59604dea5f12b43 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 29 Aug 2022 01:31:46 +0200 Subject: [PATCH 08/17] Add GraphicsResourceHelper APIs for 1D textures --- .../__Internals/GraphicsResourceHelper.cs | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) diff --git a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs index fd4dea7c..1bc7e9f6 100644 --- a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs @@ -76,6 +76,119 @@ public static class GraphicsResourceHelper return *(ulong*)&d3D12GpuDescriptorHandle; } + /// + /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The type of values stored in the input texture. + /// The input instance to check. + /// The target instance in use. + /// The GPU descriptor handle for the texture. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ulong ValidateAndGetGpuDescriptorHandle(ReadOnlyTexture1D texture, GraphicsDevice device) + where T : unmanaged + { + Guard.IsNotNull(texture); + + using var _0 = texture.GetReferenceTrackingLease(); + + texture.ThrowIfDeviceMismatch(device); + + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; + + return *(ulong*)&d3D12GpuDescriptorHandle; + } + + /// + /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The type of values stored in the input texture. + /// The input instance to check. + /// The target instance in use. + /// The GPU descriptor handle for the texture. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ulong ValidateAndGetGpuDescriptorHandle(ReadWriteTexture1D texture, GraphicsDevice device) + where T : unmanaged + { + Guard.IsNotNull(texture); + + using var _0 = texture.GetReferenceTrackingLease(); + + texture.ThrowIfDeviceMismatch(device); + + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = texture.D3D12GpuDescriptorHandle; + + return *(ulong*)&d3D12GpuDescriptorHandle; + } + + /// + /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The type of values stored in the input texture. + /// The input instance to check. + /// The target instance in use. + /// The GPU descriptor handle for the texture. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadOnlyTexture1D texture, GraphicsDevice device) + where T : unmanaged + { + Guard.IsNotNull(texture); + + if (texture is IGraphicsResource resource) + { + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = resource.ValidateAndGetGpuDescriptorHandle(device); + + return *(ulong*)&d3D12GpuDescriptorHandle; + } + + return ThrowHelper.ThrowArgumentException("The input texture is not a valid instance."); + } + + /// + /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The type of normalized values stored in the input texture. + /// The input instance to check. + /// The target instance in use. + /// The GPU descriptor handle for the texture. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadOnlyNormalizedTexture1D texture, GraphicsDevice device) + where TPixel : unmanaged + { + Guard.IsNotNull(texture); + + if (texture is IGraphicsResource resource) + { + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = resource.ValidateAndGetGpuDescriptorHandle(device); + + return *(ulong*)&d3D12GpuDescriptorHandle; + } + + return ThrowHelper.ThrowArgumentException("The input texture is not a valid instance."); + } + + /// + /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The type of normalized values stored in the input texture. + /// The input instance to check. + /// The target instance in use. + /// The GPU descriptor handle for the texture. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadWriteNormalizedTexture1D texture, GraphicsDevice device) + where TPixel : unmanaged + { + Guard.IsNotNull(texture); + + if (texture is IGraphicsResource resource) + { + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = resource.ValidateAndGetGpuDescriptorHandle(device); + + return *(ulong*)&d3D12GpuDescriptorHandle; + } + + return ThrowHelper.ThrowArgumentException("The input texture is not a valid instance."); + } + /// /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. /// From 8c5ce3a1d79112d26356393692ec0633ff4e504e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 29 Aug 2022 01:58:51 +0200 Subject: [PATCH 09/17] Add extensions for 1D textures --- .../GraphicsDeviceExtensions.Resources.cs | 412 +++++++++++++ .../Extensions/ReadBackTexture1DExtensions.cs | 60 ++ .../ReadWriteTexture1DExtensions.cs | 144 +++++ .../Extensions/Texture1DExtensions.cs | 544 ++++++++++++++++++ .../Extensions/UploadTexture1DExtensions.cs | 60 ++ .../Extensions/ComputeContextExtensions.cs | 235 +++++++- 6 files changed, 1454 insertions(+), 1 deletion(-) create mode 100644 src/ComputeSharp/Graphics/Extensions/ReadBackTexture1DExtensions.cs create mode 100644 src/ComputeSharp/Graphics/Extensions/ReadWriteTexture1DExtensions.cs create mode 100644 src/ComputeSharp/Graphics/Extensions/Texture1DExtensions.cs create mode 100644 src/ComputeSharp/Graphics/Extensions/UploadTexture1DExtensions.cs diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Resources.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Resources.cs index b8e91f45..0e2c8834 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Resources.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Resources.cs @@ -160,6 +160,196 @@ partial class GraphicsDeviceExtensions return readWriteBuffer; } + /// + /// Allocates a new readonly 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The width of the texture. + /// The allocation mode to use for the new resource. + /// A zeroed instance of size []. + public static ReadOnlyTexture1D AllocateReadOnlyTexture1D(this GraphicsDevice device, int width, AllocationMode allocationMode = AllocationMode.Default) + where T : unmanaged + { + Guard.IsNotNull(device); + + return new(device, width, allocationMode); + } + + /// + /// Allocates a new readonly 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The width of the texture. + /// A instance with the contents of the input array. + public static ReadOnlyTexture1D AllocateReadOnlyTexture1D(this GraphicsDevice device, T[] source, int width) + where T : unmanaged + { + Guard.IsNotNull(device); + Guard.IsNotNull(source); + + return device.AllocateReadOnlyTexture1D(source.AsSpan(0, width)); + } + + /// + /// Allocates a new readonly 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The starting offset within to read data from. + /// The width of the texture. + /// A instance with the contents of the input array. + public static ReadOnlyTexture1D AllocateReadOnlyTexture1D(this GraphicsDevice device, T[] source, int offset, int width) + where T : unmanaged + { + Guard.IsNotNull(device); + Guard.IsNotNull(source); + + return device.AllocateReadOnlyTexture1D(source.AsSpan(offset, width)); + } + + /// + /// Allocates a new readonly 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// A read write instance with the contents of the input array. + public static ReadOnlyTexture1D AllocateReadOnlyTexture1D(this GraphicsDevice device, T[] source) + where T : unmanaged + { + Guard.IsNotNull(device); + Guard.IsNotNull(source); + + ReadOnlyTexture1D texture = new(device, source.Length, AllocationMode.Default); + + texture.CopyFrom(source); + + return texture; + } + + /// + /// Allocates a new readonly 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The input with the data to copy on the allocated texture. + /// A instance with the contents of the input . + public static ReadOnlyTexture1D AllocateReadOnlyTexture1D(this GraphicsDevice device, ReadOnlySpan source) + where T : unmanaged + { + Guard.IsNotNull(device); + + ReadOnlyTexture1D texture = new(device, source.Length, AllocationMode.Default); + + texture.CopyFrom(source); + + return texture; + } + + /// + /// Allocates a new readonly 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The width of the texture. + /// The allocation mode to use for the new resource. + /// A zeroed instance of size []. + public static ReadOnlyTexture1D AllocateReadOnlyTexture1D(this GraphicsDevice device, int width, AllocationMode allocationMode = AllocationMode.Default) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + Guard.IsNotNull(device); + + return new(device, width, allocationMode); + } + + /// + /// Allocates a new readonly 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The width of the texture. + /// A instance with the contents of the input array. + public static ReadOnlyTexture1D AllocateReadOnlyTexture1D(this GraphicsDevice device, T[] source, int width) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + Guard.IsNotNull(device); + Guard.IsNotNull(source); + + return device.AllocateReadOnlyTexture1D(source.AsSpan(0, width)); + } + + /// + /// Allocates a new readonly 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The starting offset within to read data from. + /// The width of the texture. + /// A instance with the contents of the input array. + public static ReadOnlyTexture1D AllocateReadOnlyTexture1D(this GraphicsDevice device, T[] source, int offset, int width) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + Guard.IsNotNull(device); + Guard.IsNotNull(source); + + return device.AllocateReadOnlyTexture1D(source.AsSpan(offset, width)); + } + + /// + /// Allocates a new readonly 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// A read write instance with the contents of the input array. + public static ReadOnlyTexture1D AllocateReadOnlyTexture1D(this GraphicsDevice device, T[] source) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + Guard.IsNotNull(device); + Guard.IsNotNull(source); + + ReadOnlyTexture1D texture = new(device, source.Length, AllocationMode.Default); + + texture.CopyFrom(source); + + return texture; + } + + /// + /// Allocates a new readonly 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input with the data to copy on the allocated texture. + /// A instance with the contents of the input . + public static ReadOnlyTexture1D AllocateReadOnlyTexture1D(this GraphicsDevice device, ReadOnlySpan source) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + Guard.IsNotNull(device); + + ReadOnlyTexture1D texture = new(device, source.Length, AllocationMode.Default); + + texture.CopyFrom(source); + + return texture; + } + /// /// Allocates a new readonly 2D texture with the specified parameters. /// @@ -651,6 +841,196 @@ partial class GraphicsDeviceExtensions return readWriteBuffer; } + /// + /// Allocates a new writeable 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The width of the texture. + /// The allocation mode to use for the new resource. + /// A zeroed instance of size []. + public static ReadWriteTexture1D AllocateReadWriteTexture1D(this GraphicsDevice device, int width, AllocationMode allocationMode = AllocationMode.Default) + where T : unmanaged + { + Guard.IsNotNull(device); + + return new(device, width, allocationMode); + } + + /// + /// Allocates a new writeable 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The width of the texture. + /// A instance with the contents of the input array. + public static ReadWriteTexture1D AllocateReadWriteTexture1D(this GraphicsDevice device, T[] source, int width) + where T : unmanaged + { + Guard.IsNotNull(device); + Guard.IsNotNull(source); + + return device.AllocateReadWriteTexture1D(source.AsSpan(0, width)); + } + + /// + /// Allocates a new writeable 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The starting offset within to read data from. + /// The width of the texture. + /// A instance with the contents of the input array. + public static ReadWriteTexture1D AllocateReadWriteTexture1D(this GraphicsDevice device, T[] source, int offset, int width) + where T : unmanaged + { + Guard.IsNotNull(device); + Guard.IsNotNull(source); + + return device.AllocateReadWriteTexture1D(source.AsSpan(offset, width)); + } + + /// + /// Allocates a new writeable 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// A read write instance with the contents of the input array. + public static ReadWriteTexture1D AllocateReadWriteTexture1D(this GraphicsDevice device, T[] source) + where T : unmanaged + { + Guard.IsNotNull(device); + Guard.IsNotNull(source); + + ReadWriteTexture1D texture = new(device, source.Length, AllocationMode.Default); + + texture.CopyFrom(source); + + return texture; + } + + /// + /// Allocates a new writeable 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The input with the data to copy on the allocated texture. + /// A instance with the contents of the input . + public static ReadWriteTexture1D AllocateReadWriteTexture1D(this GraphicsDevice device, ReadOnlySpan source) + where T : unmanaged + { + Guard.IsNotNull(device); + + ReadWriteTexture1D texture = new(device, source.Length, AllocationMode.Default); + + texture.CopyFrom(source); + + return texture; + } + + /// + /// Allocates a new writeable 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The width of the texture. + /// The allocation mode to use for the new resource. + /// A zeroed instance of size []. + public static ReadWriteTexture1D AllocateReadWriteTexture1D(this GraphicsDevice device, int width, AllocationMode allocationMode = AllocationMode.Default) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + Guard.IsNotNull(device); + + return new(device, width, allocationMode); + } + + /// + /// Allocates a new writeable 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The width of the texture. + /// A instance with the contents of the input array. + public static ReadWriteTexture1D AllocateReadWriteTexture1D(this GraphicsDevice device, T[] source, int width) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + Guard.IsNotNull(device); + Guard.IsNotNull(source); + + return device.AllocateReadWriteTexture1D(source.AsSpan(0, width)); + } + + /// + /// Allocates a new writeable 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The starting offset within to read data from. + /// The width of the texture. + /// A instance with the contents of the input array. + public static ReadWriteTexture1D AllocateReadWriteTexture1D(this GraphicsDevice device, T[] source, int offset, int width) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + Guard.IsNotNull(device); + Guard.IsNotNull(source); + + return device.AllocateReadWriteTexture1D(source.AsSpan(offset, width)); + } + + /// + /// Allocates a new writeable 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// A read write instance with the contents of the input array. + public static ReadWriteTexture1D AllocateReadWriteTexture1D(this GraphicsDevice device, T[] source) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + Guard.IsNotNull(device); + Guard.IsNotNull(source); + + ReadWriteTexture1D texture = new(device, source.Length, AllocationMode.Default); + + texture.CopyFrom(source); + + return texture; + } + + /// + /// Allocates a new writeable 1D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input with the data to copy on the allocated texture. + /// A instance with the contents of the input . + public static ReadWriteTexture1D AllocateReadWriteTexture1D(this GraphicsDevice device, ReadOnlySpan source) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + Guard.IsNotNull(device); + + ReadWriteTexture1D texture = new(device, source.Length, AllocationMode.Default); + + texture.CopyFrom(source); + + return texture; + } + /// /// Allocates a new writeable 2D texture with the specified parameters. /// @@ -1084,6 +1464,22 @@ partial class GraphicsDeviceExtensions return new(device, length, allocationMode); } + /// + /// Allocates a new upload 1D texture with the specified parameters. + /// + /// The type of items to store in the buffer. + /// The instance to use to allocate the buffer. + /// The width of the texture. + /// The allocation mode to use for the new resource. + /// A instance of size []. + public static UploadTexture1D AllocateUploadTexture1D(this GraphicsDevice device, int width, AllocationMode allocationMode = AllocationMode.Default) + where T : unmanaged + { + Guard.IsNotNull(device); + + return new(device, width, allocationMode); + } + /// /// Allocates a new upload 2D texture with the specified parameters. /// @@ -1136,6 +1532,22 @@ partial class GraphicsDeviceExtensions return new(device, length, allocationMode); } + /// + /// Allocates a new readback 1D texture with the specified parameters. + /// + /// The type of items to store in the buffer. + /// The instance to use to allocate the buffer. + /// The width of the texture. + /// The allocation mode to use for the new resource. + /// A instance of size []. + public static ReadBackTexture1D AllocateReadBackTexture1D(this GraphicsDevice device, int width, AllocationMode allocationMode = AllocationMode.Default) + where T : unmanaged + { + Guard.IsNotNull(device); + + return new(device, width, allocationMode); + } + /// /// Allocates a new readback 2D texture with the specified parameters. /// diff --git a/src/ComputeSharp/Graphics/Extensions/ReadBackTexture1DExtensions.cs b/src/ComputeSharp/Graphics/Extensions/ReadBackTexture1DExtensions.cs new file mode 100644 index 00000000..1c22347a --- /dev/null +++ b/src/ComputeSharp/Graphics/Extensions/ReadBackTexture1DExtensions.cs @@ -0,0 +1,60 @@ +using CommunityToolkit.Diagnostics; +using ComputeSharp.Resources; + +namespace ComputeSharp; + +/// +/// A that contains extension methods for the type. +/// +public static class ReadBackTexture1DExtensions +{ + /// + /// Reads the contents of a instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The target instance to write data to. + /// The input instance to read data from. + public static void CopyFrom(this ReadBackTexture1D destination, Texture1D source) + where T : unmanaged + { + Guard.IsNotNull(destination); + Guard.IsNotNull(source); + + source.CopyTo(destination, 0, 0, source.Width); + } + + /// + /// Reads the contents of a instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The target instance to write data to. + /// The input instance to read data from. + /// The horizontal offset in the source texture. + /// The width of the memory area to copy. + public static void CopyFrom(this ReadBackTexture1D destination, Texture1D source, int sourceOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(destination); + Guard.IsNotNull(source); + + source.CopyTo(destination, sourceOffsetX, 0, width); + } + + /// + /// Reads the contents of a instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The target instance to write data to. + /// The input instance to read data from. + /// The horizontal offset in the source texture. + /// The horizontal offset in the destination texture. + /// The width of the memory area to copy. + public static void CopyFrom(this ReadBackTexture1D destination, Texture1D source, int sourceOffsetX, int destinationOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(destination); + Guard.IsNotNull(source); + + source.CopyTo(destination, sourceOffsetX, destinationOffsetX, width); + } +} diff --git a/src/ComputeSharp/Graphics/Extensions/ReadWriteTexture1DExtensions.cs b/src/ComputeSharp/Graphics/Extensions/ReadWriteTexture1DExtensions.cs new file mode 100644 index 00000000..5c540d7e --- /dev/null +++ b/src/ComputeSharp/Graphics/Extensions/ReadWriteTexture1DExtensions.cs @@ -0,0 +1,144 @@ +using System; +using CommunityToolkit.Diagnostics; + +namespace ComputeSharp; + +/// +/// A that contains extension methods for the and types. +/// +public static class ReadWriteTexture1DExtensions +{ + /// + /// Retrieves a wrapping instance for the input resource. + /// + /// The input instance to create a wrapper for. + /// An instance wrapping the current resource. + /// + /// The returned instance can be used in a shader to enable texture sampling. + /// + /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so, + /// use , + /// and specify . After that, this method can be used to get a readonly wrapper for + /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader + /// being dispatched through that same , as it will not work if the texture changes state later on. + /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same + /// API as before but specifying . Failing to do so results in undefined behavior. + /// + /// + /// Thrown if the current instance or its associated device are disposed. + /// Thrown if the current instance is not in a readonly state. + public static IReadOnlyTexture1D AsReadOnly(this ReadWriteTexture1D texture) + { + Guard.IsNotNull(texture); + + return texture.AsReadOnly(); + } + + /// + /// Retrieves a wrapping instance for the input resource. + /// + /// The input instance to create a wrapper for. + /// An instance wrapping the current resource. + /// + /// The returned instance can be used in a shader to enable texture sampling. + /// + /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so, + /// use , + /// and specify . After that, this method can be used to get a readonly wrapper for + /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader + /// being dispatched through that same , as it will not work if the texture changes state later on. + /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same + /// API as before but specifying . Failing to do so results in undefined behavior. + /// + /// + /// Thrown if the current instance or its associated device are disposed. + /// Thrown if the current instance is not in a readonly state. + public static IReadOnlyTexture1D AsReadOnly(this ReadWriteTexture1D texture) + { + Guard.IsNotNull(texture); + + return texture.AsReadOnly(); + } + + /// + /// Retrieves a wrapping instance for the input resource. + /// + /// The input instance to create a wrapper for. + /// An instance wrapping the current resource. + /// + /// The returned instance can be used in a shader to enable texture sampling. + /// + /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so, + /// use , + /// and specify . After that, this method can be used to get a readonly wrapper for + /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader + /// being dispatched through that same , as it will not work if the texture changes state later on. + /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same + /// API as before but specifying . Failing to do so results in undefined behavior. + /// + /// + /// Thrown if the current instance or its associated device are disposed. + /// Thrown if the current instance is not in a readonly state. + public static IReadOnlyTexture1D AsReadOnly(this ReadWriteTexture1D texture) + { + Guard.IsNotNull(texture); + + return texture.AsReadOnly(); + } + + /// + /// Retrieves a wrapping instance for the input resource. + /// + /// The input instance to create a wrapper for. + /// An instance wrapping the current resource. + /// + /// The returned instance can be used in a shader to enable texture sampling. + /// + /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so, + /// use , + /// and specify . After that, this method can be used to get a readonly wrapper for + /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader + /// being dispatched through that same , as it will not work if the texture changes state later on. + /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same + /// API as before but specifying . Failing to do so results in undefined behavior. + /// + /// + /// Thrown if the current instance or its associated device are disposed. + /// Thrown if the current instance is not in a readonly state. + public static IReadOnlyTexture1D AsReadOnly(this ReadWriteTexture1D texture) + { + Guard.IsNotNull(texture); + + return texture.AsReadOnly(); + } + + /// + /// Retrieves a wrapping instance for the input resource. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The input instance to create a wrapper for. + /// An instance wrapping the current resource. + /// + /// The returned instance can be used in a shader to enable texture sampling. + /// + /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so, + /// use , + /// and specify . After that, this method can be used to get a readonly wrapper for + /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader + /// being dispatched through that same , as it will not work if the texture changes state later on. + /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same + /// API as before but specifying . Failing to do so results in undefined behavior. + /// + /// + /// Thrown if the current instance or its associated device are disposed. + /// Thrown if the current instance is not in a readonly state. + public static IReadOnlyNormalizedTexture1D AsReadOnly(this ReadWriteTexture1D texture) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + Guard.IsNotNull(texture); + + return texture.AsReadOnly(); + } +} diff --git a/src/ComputeSharp/Graphics/Extensions/Texture1DExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Texture1DExtensions.cs new file mode 100644 index 00000000..55c7f2fe --- /dev/null +++ b/src/ComputeSharp/Graphics/Extensions/Texture1DExtensions.cs @@ -0,0 +1,544 @@ +using System; +using System.Runtime.InteropServices; +using CommunityToolkit.Diagnostics; +using ComputeSharp.Resources; + +namespace ComputeSharp; + +/// +/// A that contains extension methods for the type. +/// +public static class Texture1DExtensions +{ + /// + /// Reads the contents of the current instance and returns an array. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// A array with the contents of the current texture. + public static T[] ToArray(this Texture1D source) + where T : unmanaged + { + Guard.IsNotNull(source); + + T[] data = new T[source.Width]; + + source.CopyTo(data); + + return data; + } + + /// + /// Reads the contents of the current instance and returns an array. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The horizontal offset in the source texture. + /// The width of the memory area to copy. + /// A array with the contents of the current texture. + public static unsafe T[] ToArray(this Texture1D source, int x, int width) + where T : unmanaged + { + Guard.IsNotNull(source); + Guard.IsGreaterThanOrEqualTo(width, 0); + + T[] data = new T[width]; + + fixed (T* p = data) + { + source.CopyTo(new Span(p, width), x, width); + } + + return data; + } + + /// + /// Reads the contents of the specified range from the current instance and writes them into a target array. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The input array to write data to. + public static void CopyTo(this Texture1D source, T[] destination) + where T : unmanaged + { + Guard.IsNotNull(source); + Guard.IsNotNull(destination); + + source.CopyTo(destination.AsSpan(), 0, source.Width); + } + +#if NET6_0_OR_GREATER + /// + /// Reads the contents of the specified range from the current instance and writes them into a target array. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The input array to write data to. + /// The horizontal range of items to copy. + public static void CopyTo(this Texture1D source, T[] destination, Range x) + where T : unmanaged + { + Guard.IsNotNull(source); + Guard.IsNotNull(destination); + + source.CopyTo(destination.AsSpan(), x); + } +#endif + + /// + /// Reads the contents of the specified range from the current instance and writes them into a target array. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The input array to write data to. + /// The horizontal offset in the source texture. + /// The width of the memory area to copy. + public static void CopyTo(this Texture1D source, T[] destination, int sourceOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(source); + Guard.IsNotNull(destination); + + source.CopyTo(destination.AsSpan(), sourceOffsetX, width); + } + + /// + /// Reads the contents of the specified range from the current instance and writes them into a target array. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The input array to write data to. + /// The starting offset within to write data to. + public static void CopyTo(this Texture1D source, T[] destination, int destinationOffset) + where T : unmanaged + { + Guard.IsNotNull(source); + Guard.IsNotNull(destination); + + source.CopyTo(destination.AsSpan(destinationOffset), 0, source.Width); + } + +#if NET6_0_OR_GREATER + /// + /// Reads the contents of the specified range from the current instance and writes them into a target array. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The input array to write data to. + /// The starting offset within to write data to. + /// The horizontal range of items to copy. + public static void CopyTo(this Texture1D source, T[] destination, int destinationOffset, Range x) + where T : unmanaged + { + Guard.IsNotNull(source); + Guard.IsNotNull(destination); + + source.CopyTo(destination.AsSpan(destinationOffset), x); + } +#endif + + /// + /// Reads the contents of the specified range from the current instance and writes them into a target array. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The input array to write data to. + /// The starting offset within to write data to. + /// The horizontal offset in the source texture. + /// The width of the memory area to copy. + public static void CopyTo(this Texture1D source, T[] destination, int destinationOffset, int sourceOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(source); + Guard.IsNotNull(destination); + + source.CopyTo(destination.AsSpan(destinationOffset), sourceOffsetX, width); + } + + /// + /// Reads the contents of the current instance and writes them into a target . + /// The input data will be read from the start of the texture. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The input to write data to. + public static void CopyTo(this Texture1D source, Span destination) + where T : unmanaged + { + Guard.IsNotNull(source); + + source.CopyTo(destination, 0, source.Width); + } + +#if NET6_0_OR_GREATER + /// + /// Reads the contents of the specified range from the current instance and writes them into a target . + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The input to write data to. + /// The horizontal range of items to copy. + public static void CopyTo(this Texture1D source, Span destination, Range x) + where T : unmanaged + { + Guard.IsNotNull(source); + + var (offsetX, width) = x.GetOffsetAndLength(source.Width); + + source.CopyTo(destination, offsetX, width); + } +#endif + + /// + /// Reads the contents of the specified range from the current instance and writes them into a target . + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The input to write data to. + /// The horizontal offset in the source texture. + /// The width of the memory area to copy. + public static void CopyTo(this Texture1D source, Span destination, int sourceOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(source); + + source.CopyTo(ref MemoryMarshal.GetReference(destination), destination.Length, sourceOffsetX, width); + } + + /// + /// Reads the contents of a instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The target instance to write data to. + public static void CopyTo(this Texture1D source, Texture1D destination) + where T : unmanaged + { + Guard.IsNotNull(source); + Guard.IsNotNull(destination); + + source.CopyTo(destination, 0, 0, source.Width); + } + + /// + /// Reads the contents of a instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The target instance to write data to. + /// The horizontal offset in the source texture. + /// The width of the memory area to copy. + public static void CopyTo(this Texture1D source, Texture1D destination, int sourceOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(source); + Guard.IsNotNull(destination); + + source.CopyTo(destination, sourceOffsetX, 0, width); + } + + /// + /// Reads the contents of a instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The target instance to write data to. + /// The horizontal offset in the source texture. + /// The horizontal offset in the destination texture. + /// The width of the memory area to copy. + public static void CopyTo(this Texture1D source, Texture1D destination, int sourceOffsetX, int destinationOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(source); + Guard.IsNotNull(destination); + + source.CopyTo(destination, sourceOffsetX, destinationOffsetX, width); + } + + /// + /// Reads the contents of a instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The target instance to write data to. + public static void CopyTo(this Texture1D source, ReadBackTexture1D destination) + where T : unmanaged + { + Guard.IsNotNull(source); + Guard.IsNotNull(destination); + + source.CopyTo(destination, 0, 0, source.Width); + } + + /// + /// Reads the contents of a instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The target instance to write data to. + /// The horizontal offset in the source texture. + /// The width of the memory area to copy. + public static void CopyTo(this Texture1D source, ReadBackTexture1D destination, int sourceOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(source); + Guard.IsNotNull(destination); + + source.CopyTo(destination, sourceOffsetX, 0, width); + } + + /// + /// Reads the contents of a instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The target instance to write data to. + /// The horizontal offset in the source texture. + /// The horizontal offset in the destination texture. + /// The width of the memory area to copy. + public static void CopyTo(this Texture1D source, ReadBackTexture1D destination, int sourceOffsetX, int destinationOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(source); + Guard.IsNotNull(destination); + + source.CopyTo(destination, sourceOffsetX, destinationOffsetX, width); + } + + /// + /// Writes the contents of a given array to the current instance. + /// + /// The type of items stored on the texture. + /// The target instance to write data to. + /// The input array to read data from. + public static void CopyFrom(this Texture1D destination, T[] source) + where T : unmanaged + { + Guard.IsNotNull(destination); + Guard.IsNotNull(source); + + destination.CopyFrom(source.AsSpan(), 0, destination.Width); + } + +#if NET6_0_OR_GREATER + /// + /// Writes the contents of a given array to a specified area of the current instance. + /// + /// The type of items stored on the texture. + /// The target instance to write data to. + /// The input array to read data from. + /// The horizontal range of items to write. + public static void CopyFrom(this Texture1D destination, T[] source, Range x) + where T : unmanaged + { + Guard.IsNotNull(destination); + Guard.IsNotNull(source); + + destination.CopyFrom(source.AsSpan(), x); + } +#endif + + /// + /// Writes the contents of a given array to a specified area of the current instance. + /// + /// The type of items stored on the texture. + /// The target instance to write data to. + /// The input array to read data from. + /// The horizontal offset in the destination texture. + /// The width of the memory area to write to. + public static void CopyFrom(this Texture1D destination, T[] source, int destinationOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(destination); + Guard.IsNotNull(source); + + destination.CopyFrom(source.AsSpan(), destinationOffsetX, width); + } + +#if NET6_0_OR_GREATER + /// + /// Writes the contents of a given array to a specified area of the current instance. + /// + /// The type of items stored on the texture. + /// The target instance to write data to. + /// The input array to read data from. + /// The starting offset within to read data from. + /// The horizontal range of items to write. + public static void CopyFrom(this Texture1D destination, T[] source, int sourceOffset, Range x) + where T : unmanaged + { + Guard.IsNotNull(destination); + Guard.IsNotNull(source); + + destination.CopyFrom(source.AsSpan(sourceOffset), x); + } +#endif + + /// + /// Writes the contents of a given array to a specified area of the current instance. + /// + /// The type of items stored on the texture. + /// The target instance to write data to. + /// The input array to read data from. + /// The starting offset within to read data from. + /// The horizontal offset in the destination texture. + /// The width of the memory area to write to. + public static void CopyFrom(this Texture1D destination, T[] source, int sourceOffset, int destinationOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(destination); + Guard.IsNotNull(source); + + destination.CopyFrom(source.AsSpan(sourceOffset), destinationOffsetX, width); + } + + /// + /// Writes the contents of a given to the current instance. + /// The input data will be written to the start of the texture, and all input items will be copied. + /// + /// The type of items stored on the texture. + /// The target instance to write data to. + /// The input to read data from. + public static void CopyFrom(this Texture1D destination, ReadOnlySpan source) + where T : unmanaged + { + Guard.IsNotNull(destination); + + destination.CopyFrom(source, 0, destination.Width); + } + +#if NET6_0_OR_GREATER + /// + /// Writes the contents of a given to a specified area of the current instance. + /// + /// The type of items stored on the texture. + /// The target instance to write data to. + /// The input to read data from. + /// The horizontal range of items to write. + public static void CopyFrom(this Texture1D destination, ReadOnlySpan source, Range x) + where T : unmanaged + { + Guard.IsNotNull(destination); + + var (offsetX, width) = x.GetOffsetAndLength(destination.Width); + + destination.CopyFrom(source, offsetX, width); + } +#endif + + /// + /// Writes the contents of a given to a specified area of the current instance. + /// + /// The type of items stored on the texture. + /// The target instance to write data to. + /// The input to read data from. + /// The horizontal offset in the destination texture. + /// The width of the memory area to write to. + public static void CopyFrom(this Texture1D destination, ReadOnlySpan source, int destinationOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(destination); + + destination.CopyFrom(ref MemoryMarshal.GetReference(source), source.Length, destinationOffsetX, width); + } + + /// + /// Reads the contents of an instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The target instance to write data to. + /// The input instance to read data from. + public static void CopyFrom(this Texture1D destination, Texture1D source) + where T : unmanaged + { + Guard.IsNotNull(destination); + Guard.IsNotNull(source); + + destination.CopyFrom(source, 0, 0, source.Width); + } + + /// + /// Reads the contents of an instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The target instance to write data to. + /// The input instance to read data from. + /// The horizontal offset in the source texture. + /// The width of the memory area to copy. + public static void CopyFrom(this Texture1D destination, Texture1D source, int sourceOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(destination); + Guard.IsNotNull(source); + + source.CopyTo(destination, sourceOffsetX, 0, width); + } + + /// + /// Reads the contents of an instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The target instance to write data to. + /// The input instance to read data from. + /// The horizontal offset in the source texture. + /// The horizontal offset in the destination texture. + /// The width of the memory area to copy. + public static void CopyFrom(this Texture1D destination, Texture1D source, int sourceOffsetX, int destinationOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(destination); + Guard.IsNotNull(source); + + source.CopyTo(destination, sourceOffsetX, destinationOffsetX, width); + } + + /// + /// Reads the contents of an instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The target instance to write data to. + /// The input instance to read data from. + public static void CopyFrom(this Texture1D destination, UploadTexture1D source) + where T : unmanaged + { + Guard.IsNotNull(destination); + Guard.IsNotNull(source); + + source.CopyTo(destination, 0, 0, source.Width); + } + + /// + /// Reads the contents of an instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The target instance to write data to. + /// The input instance to read data from. + /// The horizontal offset in the source texture. + /// The width of the memory area to copy. + public static void CopyFrom(this Texture1D destination, UploadTexture1D source, int sourceOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(destination); + Guard.IsNotNull(source); + + destination.CopyFrom(source, sourceOffsetX, 0, width); + } + + /// + /// Reads the contents of an instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The target instance to write data to. + /// The input instance to read data from. + /// The horizontal offset in the source texture. + /// The horizontal offset in the destination texture. + /// The width of the memory area to copy. + public static void CopyFrom(this Texture1D destination, UploadTexture1D source, int sourceOffsetX, int destinationOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(destination); + Guard.IsNotNull(source); + + destination.CopyFrom(source, sourceOffsetX, destinationOffsetX, width); + } +} diff --git a/src/ComputeSharp/Graphics/Extensions/UploadTexture1DExtensions.cs b/src/ComputeSharp/Graphics/Extensions/UploadTexture1DExtensions.cs new file mode 100644 index 00000000..87f160f9 --- /dev/null +++ b/src/ComputeSharp/Graphics/Extensions/UploadTexture1DExtensions.cs @@ -0,0 +1,60 @@ +using CommunityToolkit.Diagnostics; +using ComputeSharp.Resources; + +namespace ComputeSharp; + +/// +/// A that contains extension methods for the type. +/// +public static class UploadTexture1DExtensions +{ + /// + /// Reads the contents of a instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The target instance to write data to. + public static void CopyTo(this UploadTexture1D source, Texture1D destination) + where T : unmanaged + { + Guard.IsNotNull(source); + Guard.IsNotNull(destination); + + destination.CopyFrom(source, 0, 0, source.Width); + } + + /// + /// Reads the contents of a instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The target instance to write data to. + /// The horizontal offset in the source texture. + /// The width of the memory area to copy. + public static void CopyTo(this UploadTexture1D source, Texture1D destination, int sourceOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(source); + Guard.IsNotNull(destination); + + destination.CopyFrom(source, sourceOffsetX, 0, width); + } + + /// + /// Reads the contents of a instance and writes them into a target instance. + /// + /// The type of items stored on the texture. + /// The input instance to read data from. + /// The target instance to write data to. + /// The horizontal offset in the source texture. + /// The horizontal offset in the destination texture. + /// The width of the memory area to copy. + public static void CopyTo(this UploadTexture1D source, Texture1D destination, int sourceOffsetX, int destinationOffsetX, int width) + where T : unmanaged + { + Guard.IsNotNull(source); + Guard.IsNotNull(destination); + + destination.CopyFrom(source, sourceOffsetX, destinationOffsetX, width); + } +} diff --git a/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs b/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs index 6b6bc55f..1cc635f9 100644 --- a/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs +++ b/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs @@ -30,6 +30,22 @@ public static class ComputeContextExtensions context.Barrier(buffer.ValidateAndGetID3D12Resource(context.GraphicsDevice, out Unsafe.AsRef(in lease))); } + /// + /// Inserts a resource barrier for a specific resource. + /// + /// The type of items stored on the texture. + /// The to use to insert the resource barrier. + /// The input instance to insert the barrier for. + public static unsafe void Barrier(this in ComputeContext context, ReadWriteTexture1D texture) + where T : unmanaged + { + Guard.IsNotNull(texture); + + using NativeObject.Lease lease = default; + + context.Barrier(texture.ValidateAndGetID3D12Resource(context.GraphicsDevice, out Unsafe.AsRef(in lease))); + } + /// /// Inserts a resource barrier for a specific resource. /// @@ -62,6 +78,24 @@ public static class ComputeContextExtensions context.Barrier(texture.ValidateAndGetID3D12Resource(context.GraphicsDevice, out Unsafe.AsRef(in lease))); } + /// + /// Inserts a resource barrier for a specific resource. + /// + /// The type of items stored on the texture. + /// The type of pixels used on the GPU side. + /// The to use to insert the resource barrier. + /// The input instance to insert the barrier for. + public static unsafe void Barrier(this in ComputeContext context, ReadWriteTexture1D texture) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + Guard.IsNotNull(texture); + + using NativeObject.Lease lease = default; + + context.Barrier(texture.ValidateAndGetID3D12Resource(context.GraphicsDevice, out Unsafe.AsRef(in lease))); + } + /// /// Inserts a resource barrier for a specific resource. /// @@ -98,6 +132,22 @@ public static class ComputeContextExtensions context.Barrier(texture.ValidateAndGetID3D12Resource(context.GraphicsDevice, out Unsafe.AsRef(in lease))); } + /// + /// Inserts a resource barrier for a specific resource. + /// + /// The type of pixels stored on the texture. + /// The to use to insert the resource barrier. + /// The input instance to insert the barrier for. + public static unsafe void Barrier(this in ComputeContext context, IReadWriteNormalizedTexture1D texture) + where TPixel : unmanaged + { + Guard.IsNotNull(texture); + + using NativeObject.Lease lease = default; + + context.Barrier(((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetID3D12Resource(context.GraphicsDevice, out Unsafe.AsRef(in lease))); + } + /// /// Inserts a resource barrier for a specific resource. /// @@ -146,6 +196,22 @@ public static class ComputeContextExtensions context.Clear(buffer.D3D12Resource, handles.Gpu, handles.Cpu, isNormalized: false); } + /// + /// Clears a specific resource. + /// + /// The type of items stored on the texture. + /// The to use to clear the resource. + /// The input instance to clear. + public static unsafe void Clear(this in ComputeContext context, ReadWriteTexture1D texture) + where T : unmanaged + { + Guard.IsNotNull(texture); + + var handles = texture.ValidateAndGetGpuAndCpuDescriptorHandlesForClear(context.GraphicsDevice, out bool isNormalized); + + context.Clear(texture.D3D12Resource, handles.Gpu, handles.Cpu, isNormalized); + } + /// /// Clears a specific resource. /// @@ -178,6 +244,24 @@ public static class ComputeContextExtensions context.Clear(texture.D3D12Resource, handles.Gpu, handles.Cpu, isNormalized); } + /// + /// Clears a specific resource. + /// + /// The type of items stored on the texture. + /// The type of pixels used on the GPU side. + /// The to use to clear the resource. + /// The input instance to clear. + public static unsafe void Clear(this in ComputeContext context, ReadWriteTexture1D texture) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + Guard.IsNotNull(texture); + + var handles = texture.ValidateAndGetGpuAndCpuDescriptorHandlesForClear(context.GraphicsDevice, out _); + + context.Clear(texture.D3D12Resource, handles.Gpu, handles.Cpu, true); + } + /// /// Clears a specific resource. /// @@ -214,6 +298,24 @@ public static class ComputeContextExtensions context.Clear(texture.D3D12Resource, handles.Gpu, handles.Cpu, true); } + /// + /// Clears a specific resource. + /// + /// The type of pixels stored on the texture. + /// The to use to clear the resource. + /// The input instance to clear. + public static unsafe void Clear(this in ComputeContext context, IReadWriteNormalizedTexture1D texture) + where TPixel : unmanaged + { + Guard.IsNotNull(texture); + + var handles = ((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetGpuAndCpuDescriptorHandlesForClear(context.GraphicsDevice, out _); + + using NativeObject.Lease lease = default; + + context.Clear(((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetID3D12Resource(context.GraphicsDevice, out Unsafe.AsRef(in lease)), handles.Gpu, handles.Cpu, true); + } + /// /// Clears a specific resource. /// @@ -250,6 +352,25 @@ public static class ComputeContextExtensions context.Clear(((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetID3D12Resource(context.GraphicsDevice, out Unsafe.AsRef(in lease)), handles.Gpu, handles.Cpu, true); } + /// + /// Fills a specific texture with a given value. + /// + /// The type of items stored on the texture. + /// The type of pixels used on the GPU side. + /// The to use to fill the resource. + /// The input instance to fill. + /// The value to use to fill . + public static unsafe void Fill(this in ComputeContext context, ReadWriteTexture1D texture, T value) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + Guard.IsNotNull(texture); + + var handles = texture.ValidateAndGetGpuAndCpuDescriptorHandlesForClear(context.GraphicsDevice, out _); + + context.Fill(texture.D3D12Resource, handles.Gpu, handles.Cpu, DXGIFormatHelper.ExtendToNormalizedValue(value.ToPixel())); + } + /// /// Fills a specific texture with a given value. /// @@ -288,6 +409,29 @@ public static class ComputeContextExtensions context.Fill(texture.D3D12Resource, handles.Gpu, handles.Cpu, DXGIFormatHelper.ExtendToNormalizedValue(value.ToPixel())); } + /// + /// Fills a specific texture with a given value. + /// + /// The type of pixels stored on the texture. + /// The to use to fill the resource. + /// The input instance to fill. + /// The value to use to fill . + public static unsafe void Fill(this in ComputeContext context, IReadWriteNormalizedTexture1D texture, TPixel value) + where TPixel : unmanaged + { + Guard.IsNotNull(texture); + + var handles = ((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetGpuAndCpuDescriptorHandlesForClear(context.GraphicsDevice, out _); + + using NativeObject.Lease lease = default; + + context.Fill( + ((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetID3D12Resource(context.GraphicsDevice, out Unsafe.AsRef(in lease)), + handles.Gpu, + handles.Cpu, + DXGIFormatHelper.ExtendToNormalizedValue(value)); + } + /// /// Fills a specific texture with a given value. /// @@ -427,6 +571,95 @@ public static class ComputeContextExtensions context.Run(texture, ref Unsafe.AsRef(in shader)); } + /// + /// Transitions the state of a specific resource. + /// + /// The to use to transition the resource. + /// The input instance to transition. + /// The state to transition the input resource to. + public static unsafe void Transition(this in ComputeContext context, ReadWriteTexture1D texture, ResourceState resourceState) + { + Guard.IsNotNull(texture); + + using NativeObject.Lease lease = default; + + var states = texture.ValidateAndGetID3D12ResourceAndTransitionStates(context.GraphicsDevice, resourceState, out ID3D12Resource* d3D12Resource, out Unsafe.AsRef(in lease)); + + context.Transition(d3D12Resource, states.Before, states.After); + } + + /// + /// Transitions the state of a specific resource. + /// + /// The to use to transition the resource. + /// The input instance to transition. + /// The state to transition the input resource to. + public static unsafe void Transition(this in ComputeContext context, ReadWriteTexture1D texture, ResourceState resourceState) + { + Guard.IsNotNull(texture); + + using NativeObject.Lease lease = default; + + var states = texture.ValidateAndGetID3D12ResourceAndTransitionStates(context.GraphicsDevice, resourceState, out ID3D12Resource* d3D12Resource, out Unsafe.AsRef(in lease)); + + context.Transition(d3D12Resource, states.Before, states.After); + } + + /// + /// Transitions the state of a specific resource. + /// + /// The to use to transition the resource. + /// The input instance to transition. + /// The state to transition the input resource to. + public static unsafe void Transition(this in ComputeContext context, ReadWriteTexture1D texture, ResourceState resourceState) + { + Guard.IsNotNull(texture); + + using NativeObject.Lease lease = default; + + var states = texture.ValidateAndGetID3D12ResourceAndTransitionStates(context.GraphicsDevice, resourceState, out ID3D12Resource* d3D12Resource, out Unsafe.AsRef(in lease)); + + context.Transition(d3D12Resource, states.Before, states.After); + } + + /// + /// Transitions the state of a specific resource. + /// + /// The to use to transition the resource. + /// The input instance to transition. + /// The state to transition the input resource to. + public static unsafe void Transition(this in ComputeContext context, ReadWriteTexture1D texture, ResourceState resourceState) + { + Guard.IsNotNull(texture); + + using NativeObject.Lease lease = default; + + var states = texture.ValidateAndGetID3D12ResourceAndTransitionStates(context.GraphicsDevice, resourceState, out ID3D12Resource* d3D12Resource, out Unsafe.AsRef(in lease)); + + context.Transition(d3D12Resource, states.Before, states.After); + } + + /// + /// Transitions the state of a specific resource. + /// + /// The type of items stored on the texture. + /// The type of pixels used on the GPU side. + /// The to use to transition the resource. + /// The input instance to transition. + /// The state to transition the input resource to. + public static unsafe void Transition(this in ComputeContext context, ReadWriteTexture1D texture, ResourceState resourceState) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + Guard.IsNotNull(texture); + + using NativeObject.Lease lease = default; + + var states = texture.ValidateAndGetID3D12ResourceAndTransitionStates(context.GraphicsDevice, resourceState, out ID3D12Resource* d3D12Resource, out Unsafe.AsRef(in lease)); + + context.Transition(d3D12Resource, states.Before, states.After); + } + /// /// Transitions the state of a specific resource. /// @@ -590,7 +823,7 @@ public static class ComputeContextExtensions /// The type of items stored on the texture. /// The type of pixels used on the GPU side. /// The to use to transition the resource. - /// The input instance to transition. + /// The input instance to transition. /// The state to transition the input resource to. public static unsafe void Transition(this in ComputeContext context, ReadWriteTexture3D texture, ResourceState resourceState) where T : unmanaged, IPixel From 8c7c659aa39fe32eaabbb3b82947be25c0d1da3d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 29 Aug 2022 02:11:12 +0200 Subject: [PATCH 10/17] Add texture 1D mappings to source generator --- .../Mappings/HlslKnownMethods.cs | 3 +++ .../Mappings/HlslKnownProperties.cs | 4 ++++ .../Mappings/HlslKnownTypes.cs | 21 +++++++++++++++++++ 3 files changed, 28 insertions(+) diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMethods.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMethods.cs index eebfd2dd..b1f16b0b 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMethods.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMethods.cs @@ -10,6 +10,9 @@ partial class HlslKnownMethods { return new Dictionary { + [$"ComputeSharp.ReadOnlyTexture1D`2.Sample({typeof(float).FullName})"] = null, + [$"ComputeSharp.IReadOnlyTexture1D`1.Sample({typeof(float).FullName})"] = null, + [$"ComputeSharp.IReadOnlyNormalizedTexture1D`1.Sample({typeof(float).FullName})"] = null, [$"ComputeSharp.ReadOnlyTexture2D`2.Sample({typeof(float).FullName}, {typeof(float).FullName})"] = "float2", [$"ComputeSharp.ReadOnlyTexture2D`2.Sample({typeof(Float2).FullName})"] = null, [$"ComputeSharp.IReadOnlyTexture2D`1.Sample({typeof(float).FullName}, {typeof(float).FullName})"] = "float2", diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownProperties.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownProperties.cs index 0b595b6e..982a2344 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownProperties.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownProperties.cs @@ -38,21 +38,25 @@ partial class HlslKnownProperties return new Dictionary { ["ComputeSharp.Resources.Buffer`1.Length"] = (2, 0), + ["ComputeSharp.Resources.Texture1D`1.Width"] = (1, 0), ["ComputeSharp.Resources.Texture2D`1.Width"] = (2, 0), ["ComputeSharp.Resources.Texture2D`1.Height"] = (2, 1), ["ComputeSharp.Resources.Texture3D`1.Width"] = (3, 0), ["ComputeSharp.Resources.Texture3D`1.Height"] = (3, 1), ["ComputeSharp.Resources.Texture3D`1.Depth"] = (3, 2), + ["ComputeSharp.IReadOnlyTexture1D`1.Width"] = (1, 0), ["ComputeSharp.IReadOnlyTexture2D`1.Width"] = (2, 0), ["ComputeSharp.IReadOnlyTexture2D`1.Height"] = (2, 1), ["ComputeSharp.IReadOnlyTexture3D`1.Width"] = (3, 0), ["ComputeSharp.IReadOnlyTexture3D`1.Height"] = (3, 1), ["ComputeSharp.IReadOnlyTexture3D`1.Depth"] = (3, 2), + ["ComputeSharp.IReadOnlyNormalizedTexture1D`1.Width"] = (1, 0), ["ComputeSharp.IReadOnlyNormalizedTexture2D`1.Width"] = (2, 0), ["ComputeSharp.IReadOnlyNormalizedTexture2D`1.Height"] = (2, 1), ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Width"] = (3, 0), ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Height"] = (3, 1), ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Depth"] = (3, 2), + ["ComputeSharp.IReadWriteNormalizedTexture1D`1.Width"] = (1, 0), ["ComputeSharp.IReadWriteNormalizedTexture2D`1.Width"] = (2, 0), ["ComputeSharp.IReadWriteNormalizedTexture2D`1.Height"] = (2, 1), ["ComputeSharp.IReadWriteNormalizedTexture3D`1.Width"] = (3, 0), diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 0018c6dc..e8d318a6 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -55,12 +55,16 @@ partial class HlslKnownTypes return typeName switch { "ComputeSharp.ReadOnlyBuffer`1" or + "ComputeSharp.ReadOnlyTexture1D`1" or + "ComputeSharp.ReadOnlyTexture1D`2" or "ComputeSharp.ReadOnlyTexture2D`1" or "ComputeSharp.ReadOnlyTexture2D`2" or "ComputeSharp.ReadOnlyTexture3D`1" or "ComputeSharp.ReadOnlyTexture3D`2" or + "ComputeSharp.IReadOnlyTexture1D`1" or "ComputeSharp.IReadOnlyTexture2D`1" or "ComputeSharp.IReadOnlyTexture3D`1" => true, + "ComputeSharp.IReadOnlyNormalizedTexture1D`1" or "ComputeSharp.IReadOnlyNormalizedTexture2D`1" or "ComputeSharp.IReadOnlyNormalizedTexture3D`1" => true, _ => false @@ -77,10 +81,13 @@ partial class HlslKnownTypes return typeName switch { "ComputeSharp.ReadWriteBuffer`1" or + "ComputeSharp.ReadWriteTexture1D`1" or + "ComputeSharp.ReadWriteTexture1D`2" or "ComputeSharp.ReadWriteTexture2D`1" or "ComputeSharp.ReadWriteTexture2D`2" or "ComputeSharp.ReadWriteTexture3D`1" or "ComputeSharp.ReadWriteTexture3D`2" or + "ComputeSharp.IReadWriteNormalizedTexture1D`1" or "ComputeSharp.IReadWriteNormalizedTexture2D`1" or "ComputeSharp.IReadWriteNormalizedTexture3D`1" => true, _ => false @@ -99,16 +106,23 @@ partial class HlslKnownTypes "ComputeSharp.ConstantBuffer`1" or "ComputeSharp.ReadOnlyBuffer`1" or "ComputeSharp.ReadWriteBuffer`1" or + "ComputeSharp.ReadOnlyTexture1D`1" or + "ComputeSharp.ReadOnlyTexture1D`2" or "ComputeSharp.ReadOnlyTexture2D`1" or "ComputeSharp.ReadOnlyTexture2D`2" or + "ComputeSharp.ReadWriteTexture1D`1" or + "ComputeSharp.ReadWriteTexture1D`2" or "ComputeSharp.ReadWriteTexture2D`1" or "ComputeSharp.ReadWriteTexture2D`2" or "ComputeSharp.ReadOnlyTexture3D`1" or "ComputeSharp.ReadOnlyTexture3D`2" or "ComputeSharp.ReadWriteTexture3D`1" or "ComputeSharp.ReadWriteTexture3D`2" or + "ComputeSharp.IReadOnlyTexture1D`1" or "ComputeSharp.IReadOnlyTexture2D`1" or "ComputeSharp.IReadOnlyTexture3D`1" or + "ComputeSharp.IReadOnlyNormalizedTexture1D`1" or + "ComputeSharp.IReadWriteNormalizedTexture1D`1" or "ComputeSharp.IReadOnlyNormalizedTexture2D`1" or "ComputeSharp.IReadWriteNormalizedTexture2D`1" or "ComputeSharp.IReadOnlyNormalizedTexture3D`1" or @@ -143,6 +157,10 @@ partial class HlslKnownTypes "ComputeSharp.ConstantBuffer`1" => mappedElementType, "ComputeSharp.ReadOnlyBuffer`1" => $"StructuredBuffer<{mappedElementType}>", "ComputeSharp.ReadWriteBuffer`1" => $"RWStructuredBuffer<{mappedElementType}>", + "ComputeSharp.ReadOnlyTexture1D`1" => $"Texture1D<{mappedElementType}>", + "ComputeSharp.ReadOnlyTexture1D`2" => $"Texture1D", + "ComputeSharp.ReadWriteTexture1D`1" => $"RWTexture1D<{mappedElementType}>", + "ComputeSharp.ReadWriteTexture1D`2" => $"RWTexture1D", "ComputeSharp.ReadOnlyTexture2D`1" => $"Texture2D<{mappedElementType}>", "ComputeSharp.ReadOnlyTexture2D`2" => $"Texture2D", "ComputeSharp.ReadWriteTexture2D`1" => $"RWTexture2D<{mappedElementType}>", @@ -151,8 +169,11 @@ partial class HlslKnownTypes "ComputeSharp.ReadOnlyTexture3D`2" => $"Texture3D", "ComputeSharp.ReadWriteTexture3D`1" => $"RWTexture3D<{mappedElementType}>", "ComputeSharp.ReadWriteTexture3D`2" => $"RWTexture3D", + "ComputeSharp.IReadOnlyTexture1D`1" => $"Texture1D<{mappedElementType}>", "ComputeSharp.IReadOnlyTexture2D`1" => $"Texture2D<{mappedElementType}>", "ComputeSharp.IReadOnlyTexture3D`1" => $"Texture3D<{mappedElementType}>", + "ComputeSharp.IReadOnlyNormalizedTexture1D`1" => $"Texture1D", + "ComputeSharp.IReadWriteNormalizedTexture1D`1" => $"RWTexture1D", "ComputeSharp.IReadOnlyNormalizedTexture2D`1" => $"Texture2D", "ComputeSharp.IReadWriteNormalizedTexture2D`1" => $"RWTexture2D", "ComputeSharp.IReadOnlyNormalizedTexture3D`1" => $"Texture3D", From d3476684fcdf553d5116db584eff0713d5532831 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 31 Aug 2022 02:34:33 +0200 Subject: [PATCH 11/17] Add unit tests for 1D texture dimension accessors --- .../ResourceDimensionsTests.g.cs | 228 ++++++++++++++++++ .../ResourceDimensionsTests.tt | 8 + 2 files changed, 236 insertions(+) diff --git a/tests/ComputeSharp.Tests/ResourceDimensionsTests.g.cs b/tests/ComputeSharp.Tests/ResourceDimensionsTests.g.cs index 732137ef..f6d3e5ec 100644 --- a/tests/ComputeSharp.Tests/ResourceDimensionsTests.g.cs +++ b/tests/ComputeSharp.Tests/ResourceDimensionsTests.g.cs @@ -72,6 +72,234 @@ public partial class ResourceDimensionsTests } } + [CombinatorialTestMethod] + [AllDevices] + [Data(8)] + [Data(64)] + [Data(128)] + [Data(376)] + public void ReadOnlyTexture1D_T1_AsReadOnlyTexture1D(Device device, int axis0) + { + using ReadOnlyTexture1D resource = device.Get().AllocateReadOnlyTexture1D(axis0); + using ReadWriteBuffer result = device.Get().AllocateReadWriteBuffer(1); + + device.Get().For(1, new ReadOnlyTexture1D_T1_AsReadOnlyTexture1DShader(resource, result)); + + int[] dimensions = result.ToArray(); + + CollectionAssert.AreEqual( + expected: new[] { axis0 }, + actual: dimensions); + } + + [AutoConstructor] + internal readonly partial struct ReadOnlyTexture1D_T1_AsReadOnlyTexture1DShader : IComputeShader + { + public readonly ReadOnlyTexture1D source; + public readonly ReadWriteBuffer result; + + public void Execute() + { + result[0] = source.Width; + } + } + + [CombinatorialTestMethod] + [AllDevices] + [Data(8)] + [Data(64)] + [Data(128)] + [Data(376)] + public void ReadWriteTexture1D_T1_AsReadWriteTexture1D(Device device, int axis0) + { + using ReadWriteTexture1D resource = device.Get().AllocateReadWriteTexture1D(axis0); + using ReadWriteBuffer result = device.Get().AllocateReadWriteBuffer(1); + + device.Get().For(1, new ReadWriteTexture1D_T1_AsReadWriteTexture1DShader(resource, result)); + + int[] dimensions = result.ToArray(); + + CollectionAssert.AreEqual( + expected: new[] { axis0 }, + actual: dimensions); + } + + [AutoConstructor] + internal readonly partial struct ReadWriteTexture1D_T1_AsReadWriteTexture1DShader : IComputeShader + { + public readonly ReadWriteTexture1D source; + public readonly ReadWriteBuffer result; + + public void Execute() + { + result[0] = source.Width; + } + } + + [CombinatorialTestMethod] + [AllDevices] + [Data(8)] + [Data(64)] + [Data(128)] + [Data(376)] + public void ReadWriteTexture1D_T1_AsIReadOnlyTexture1D(Device device, int axis0) + { + using ReadWriteTexture1D resource = device.Get().AllocateReadWriteTexture1D(axis0); + using ReadWriteBuffer result = device.Get().AllocateReadWriteBuffer(1); + + using (var context = device.Get().CreateComputeContext()) + { + context.Transition(resource, ResourceState.ReadOnly); + context.For(1, new ReadWriteTexture1D_T1_AsIReadOnlyTexture1DShader(resource.AsReadOnly(), result)); + } + + int[] dimensions = result.ToArray(); + + CollectionAssert.AreEqual( + expected: new[] { axis0 }, + actual: dimensions); + } + + [AutoConstructor] + internal readonly partial struct ReadWriteTexture1D_T1_AsIReadOnlyTexture1DShader : IComputeShader + { + public readonly IReadOnlyTexture1D source; + public readonly ReadWriteBuffer result; + + public void Execute() + { + result[0] = source.Width; + } + } + + [CombinatorialTestMethod] + [AllDevices] + [Data(8)] + [Data(64)] + [Data(128)] + [Data(376)] + public void ReadOnlyTexture1D_T2_AsReadOnlyTexture1D(Device device, int axis0) + { + using ReadOnlyTexture1D resource = device.Get().AllocateReadOnlyTexture1D(axis0); + using ReadWriteBuffer result = device.Get().AllocateReadWriteBuffer(1); + + device.Get().For(1, new ReadOnlyTexture1D_T2_AsReadOnlyTexture1DShader(resource, result)); + + int[] dimensions = result.ToArray(); + + CollectionAssert.AreEqual( + expected: new[] { axis0 }, + actual: dimensions); + } + + [AutoConstructor] + internal readonly partial struct ReadOnlyTexture1D_T2_AsReadOnlyTexture1DShader : IComputeShader + { + public readonly ReadOnlyTexture1D source; + public readonly ReadWriteBuffer result; + + public void Execute() + { + result[0] = source.Width; + } + } + + [CombinatorialTestMethod] + [AllDevices] + [Data(8)] + [Data(64)] + [Data(128)] + [Data(376)] + public void ReadOnlyTexture1D_T2_AsIReadOnlyNormalizedTexture1D(Device device, int axis0) + { + using ReadOnlyTexture1D resource = device.Get().AllocateReadOnlyTexture1D(axis0); + using ReadWriteBuffer result = device.Get().AllocateReadWriteBuffer(1); + + device.Get().For(1, new ReadOnlyTexture1D_T2_AsIReadOnlyNormalizedTexture1DShader(resource, result)); + + int[] dimensions = result.ToArray(); + + CollectionAssert.AreEqual( + expected: new[] { axis0 }, + actual: dimensions); + } + + [AutoConstructor] + internal readonly partial struct ReadOnlyTexture1D_T2_AsIReadOnlyNormalizedTexture1DShader : IComputeShader + { + public readonly IReadOnlyNormalizedTexture1D source; + public readonly ReadWriteBuffer result; + + public void Execute() + { + result[0] = source.Width; + } + } + + [CombinatorialTestMethod] + [AllDevices] + [Data(8)] + [Data(64)] + [Data(128)] + [Data(376)] + public void ReadWriteTexture1D_T2_AsReadWriteTexture1D(Device device, int axis0) + { + using ReadWriteTexture1D resource = device.Get().AllocateReadWriteTexture1D(axis0); + using ReadWriteBuffer result = device.Get().AllocateReadWriteBuffer(1); + + device.Get().For(1, new ReadWriteTexture1D_T2_AsReadWriteTexture1DShader(resource, result)); + + int[] dimensions = result.ToArray(); + + CollectionAssert.AreEqual( + expected: new[] { axis0 }, + actual: dimensions); + } + + [AutoConstructor] + internal readonly partial struct ReadWriteTexture1D_T2_AsReadWriteTexture1DShader : IComputeShader + { + public readonly ReadWriteTexture1D source; + public readonly ReadWriteBuffer result; + + public void Execute() + { + result[0] = source.Width; + } + } + + [CombinatorialTestMethod] + [AllDevices] + [Data(8)] + [Data(64)] + [Data(128)] + [Data(376)] + public void ReadWriteTexture1D_T2_AsIReadWriteNormalizedTexture1D(Device device, int axis0) + { + using ReadWriteTexture1D resource = device.Get().AllocateReadWriteTexture1D(axis0); + using ReadWriteBuffer result = device.Get().AllocateReadWriteBuffer(1); + + device.Get().For(1, new ReadWriteTexture1D_T2_AsIReadWriteNormalizedTexture1DShader(resource, result)); + + int[] dimensions = result.ToArray(); + + CollectionAssert.AreEqual( + expected: new[] { axis0 }, + actual: dimensions); + } + + [AutoConstructor] + internal readonly partial struct ReadWriteTexture1D_T2_AsIReadWriteNormalizedTexture1DShader : IComputeShader + { + public readonly IReadWriteNormalizedTexture1D source; + public readonly ReadWriteBuffer result; + + public void Execute() + { + result[0] = source.Width; + } + } + [CombinatorialTestMethod] [AllDevices] [Data(8, 12)] diff --git a/tests/ComputeSharp.Tests/ResourceDimensionsTests.tt b/tests/ComputeSharp.Tests/ResourceDimensionsTests.tt index 8e3daf32..a315d0d5 100644 --- a/tests/ComputeSharp.Tests/ResourceDimensionsTests.tt +++ b/tests/ComputeSharp.Tests/ResourceDimensionsTests.tt @@ -20,6 +20,10 @@ var typesMap = new Dictionary { ["ReadOnlyBuffer"] = new[] { "Length" }, ["ReadWriteBuffer"] = new[] { "Length" }, + ["ReadOnlyTexture1D"] = new[] { "Width" }, + ["ReadWriteTexture1D"] = new[] { "Width" }, + ["ReadOnlyTexture1D"] = new[] { "Width" }, + ["ReadWriteTexture1D"] = new[] { "Width" }, ["ReadOnlyTexture2D"] = new[] { "Width", "Height" }, ["ReadWriteTexture2D"] = new[] { "Width", "Height" }, ["ReadOnlyTexture2D"] = new[] { "Width", "Height" }, @@ -33,6 +37,9 @@ var typesMap = new Dictionary // Map of all resource types that also have a supported interface var interfacesMap = new Dictionary { + ["ReadWriteTexture1D"] = "IReadOnlyTexture1D", + ["ReadOnlyTexture1D"] = "IReadOnlyNormalizedTexture1D", + ["ReadWriteTexture1D"] = "IReadWriteNormalizedTexture1D", ["ReadWriteTexture2D"] = "IReadOnlyTexture2D", ["ReadOnlyTexture2D"] = "IReadOnlyNormalizedTexture2D", ["ReadWriteTexture2D"] = "IReadWriteNormalizedTexture2D", @@ -44,6 +51,7 @@ var interfacesMap = new Dictionary // Map of all resource that need a readonly wrapper var readonlyWrappersMap = new HashSet { + "IReadOnlyTexture1D", "IReadOnlyTexture2D", "IReadOnlyTexture3D" }; From f46f924f08c052e5e561efc90455b445b764623f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 31 Aug 2022 03:00:48 +0200 Subject: [PATCH 12/17] Add TransferTexture1DTests unit tests --- .../Extensions/GraphicsDeviceExtensions.cs | 20 ++ .../TransferTexture1DTests.cs | 175 ++++++++++++++++++ 2 files changed, 195 insertions(+) create mode 100644 tests/ComputeSharp.Tests/TransferTexture1DTests.cs diff --git a/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs b/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs index 09d85ec9..2e8cd78c 100644 --- a/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs +++ b/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs @@ -140,6 +140,26 @@ public static class GraphicsDeviceExtensions }; } + /// + /// Allocates a new instance of the specified type. + /// + /// The type of items in the buffer. + /// The target instance to allocate the buffer for. + /// The type of buffer to allocate. + /// The width of the texture to create. + /// The allocation mode to use for the new resource. + /// A instance of the requested size. + public static TransferTexture1D AllocateTransferTexture1D(this GraphicsDevice device, Type type, int width, AllocationMode allocationMode = AllocationMode.Default) + where T : unmanaged + { + return type switch + { + _ when type == typeof(UploadTexture1D<>) => device.AllocateUploadTexture1D(width, allocationMode), + _ when type == typeof(ReadBackTexture1D<>) => device.AllocateReadBackTexture1D(width, allocationMode), + _ => throw new ArgumentException($"Invalid type: {type}", nameof(type)) + }; + } + /// /// Allocates a new instance of the specified type. /// diff --git a/tests/ComputeSharp.Tests/TransferTexture1DTests.cs b/tests/ComputeSharp.Tests/TransferTexture1DTests.cs new file mode 100644 index 00000000..61529276 --- /dev/null +++ b/tests/ComputeSharp.Tests/TransferTexture1DTests.cs @@ -0,0 +1,175 @@ +using System; +using System.Linq; +using System.Runtime.CompilerServices; +using CommunityToolkit.HighPerformance; +using ComputeSharp.Resources; +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests; + +[TestClass] +[TestCategory("TransferTexture1D")] +public partial class TransferTexture1DTests +{ + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(UploadTexture1D<>))] + [Resource(typeof(ReadBackTexture1D<>))] + [Data(AllocationMode.Default)] + [Data(AllocationMode.Clear)] + public unsafe void Allocate_Uninitialized_Ok(Device device, Type textureType, AllocationMode allocationMode) + { + using TransferTexture1D texture = device.Get().AllocateTransferTexture1D(textureType, 256, allocationMode); + + Assert.IsNotNull(texture); + Assert.AreEqual(texture.Width, 256); + Assert.AreEqual(texture.Memory.Length, 256); + Assert.AreEqual(texture.Span.Length, 256); + Assert.AreSame(texture.GraphicsDevice, device.Get()); + + if (allocationMode == AllocationMode.Clear) + { + foreach (float x in texture.Memory.Span) + { + Assert.AreEqual(x, 0f); + } + + foreach (float x in texture.Span) + { + Assert.AreEqual(x, 0f); + } + } + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(UploadTexture1D<>))] + [Resource(typeof(ReadBackTexture1D<>))] + [Data(-14253)] + [Data(-1)] + [Data(0)] + [Data(-14)] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Allocate_Uninitialized_Fail(Device device, Type textureType, int width) + { + using TransferTexture1D texture = device.Get().AllocateTransferTexture1D(textureType, width); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(UploadTexture1D<>))] + [Resource(typeof(ReadBackTexture1D<>))] + [ExpectedException(typeof(ObjectDisposedException))] + public void UsageAfterDispose(Device device, Type textureType) + { + using TransferTexture1D texture = device.Get().AllocateTransferTexture1D(textureType, 32); + + texture.Dispose(); + + _ = texture.Span; + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void Allocate_UploadTexture1D_Copy_Full(Device device) + { + using UploadTexture1D uploadTexture1D = device.Get().AllocateUploadTexture1D(256); + + new Random(42).NextBytes(uploadTexture1D.Span.AsBytes()); + + using ReadOnlyTexture1D readOnlyTexture1D = device.Get().AllocateReadOnlyTexture1D(uploadTexture1D.Width); + + uploadTexture1D.CopyTo(readOnlyTexture1D); + + int[] result = readOnlyTexture1D.ToArray(); + + Assert.AreEqual(uploadTexture1D.Width, result.Length); + + fixed (int* _ = result) + { + Assert.IsTrue(uploadTexture1D.Span.SequenceEqual(new Span(Unsafe.AsPointer(ref result[0]), result.Length))); + } + } + + [CombinatorialTestMethod] + [AllDevices] + [Data(0, 2048)] + [Data(128, 1813)] + [Data(0, 2000)] + [Data(97, 512)] + public unsafe void Allocate_UploadTexture1D_Copy_Range(Device device, int x, int width) + { + using UploadTexture1D uploadTexture1D = device.Get().AllocateUploadTexture1D(2048); + + new Random(42).NextBytes(uploadTexture1D.Span.AsBytes()); + + using ReadOnlyTexture1D readOnlyTexture1D = device.Get().AllocateReadOnlyTexture1D(uploadTexture1D.Width); + + uploadTexture1D.CopyTo(readOnlyTexture1D, x, width); + + int[] result = readOnlyTexture1D.ToArray(); + + fixed (void* _ = result) + { + Span sourceRow = uploadTexture1D.Span.Slice(x, width); + Span destinationRow = new Span(Unsafe.AsPointer(ref result[0]), result.Length).Slice(0, width); + + Assert.IsTrue(sourceRow.SequenceEqual(destinationRow)); + } + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void Allocate_ReadBackTexture1D_Copy_Full(Device device) + { + int[] source = new int[256]; + + fixed (int* p = source) + { + new Random(42).NextBytes(new Span(p, source.Length).AsBytes()); + } + + using ReadOnlyTexture1D readOnlyTexture1D = device.Get().AllocateReadOnlyTexture1D(source); + using ReadBackTexture1D readBackTexture1D = device.Get().AllocateReadBackTexture1D(256); + + readOnlyTexture1D.CopyTo(readBackTexture1D); + + Assert.AreEqual(readBackTexture1D.Width, 256); + + fixed (int* p = source) + { + Assert.IsTrue(readBackTexture1D.Span.SequenceEqual(new Span(Unsafe.AsPointer(ref source[0]), source.Length))); + } + } + + [CombinatorialTestMethod] + [AllDevices] + [Data(0, 2048)] + [Data(128, 1813)] + [Data(0, 2000)] + [Data(97, 512)] + public unsafe void Allocate_ReadBackTexture2D_Copy_Range(Device device, int x, int width) + { + int[] source = new int[2048]; + + fixed (int* p = source) + { + new Random(42).NextBytes(new Span(p, source.Length).AsBytes()); + } + + using ReadOnlyTexture1D readOnlyTexture1D = device.Get().AllocateReadOnlyTexture1D(source); + using ReadBackTexture1D readBackTexture1D = device.Get().AllocateReadBackTexture1D(2048); + + readOnlyTexture1D.CopyTo(readBackTexture1D, x, width); + + fixed (int* p = source) + { + Span sourceRow = new Span(Unsafe.AsPointer(ref source[0]), source.Length).Slice(x, width); + Span destinationRow = readBackTexture1D.Span.Slice(0, width); + + Assert.IsTrue(sourceRow.SequenceEqual(destinationRow)); + } + } +} From 62f12ed51094a24c0c7a46b0a0cdbdf68e248e42 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 1 Sep 2022 00:51:14 +0200 Subject: [PATCH 13/17] Add missing GraphicsDeviceExtensions test extensions --- .../Extensions/GraphicsDeviceExtensions.cs | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs b/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs index 2e8cd78c..d40c81b0 100644 --- a/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs +++ b/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs @@ -30,6 +30,48 @@ public static class GraphicsDeviceExtensions }; } + /// + /// Allocates a new instance of the specified type. + /// + /// The type of items in the texture. + /// The target instance to allocate the texture for. + /// The type of texture to allocate. + /// The width of the texture to create. + /// The allocation mode to use for the new resource. + /// A instance of the requested size. + public static Texture1D AllocateTexture1D(this GraphicsDevice device, Type type, int width, AllocationMode allocationMode = AllocationMode.Default) + where T : unmanaged + { + return type switch + { + _ when type == typeof(ReadOnlyTexture1D<>) => device.AllocateReadOnlyTexture1D(width, allocationMode), + _ when type == typeof(ReadWriteTexture1D<>) => device.AllocateReadWriteTexture1D(width, allocationMode), + _ => throw new ArgumentException($"Invalid type: {type}", nameof(type)) + }; + } + + /// + /// Allocates a new instance of the specified type. + /// + /// The type of items in the texture. + /// The type of pixels used on the GPU side. + /// The target instance to allocate the texture for. + /// The type of texture to allocate. + /// The width of the texture to create. + /// The allocation mode to use for the new resource. + /// A instance of the requested size. + public static Texture1D AllocateTexture1D(this GraphicsDevice device, Type type, int width, AllocationMode allocationMode = AllocationMode.Default) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + return type switch + { + _ when type == typeof(ReadOnlyTexture1D<,>) => device.AllocateReadOnlyTexture1D(width, allocationMode), + _ when type == typeof(ReadWriteTexture1D<,>) => device.AllocateReadWriteTexture1D(width, allocationMode), + _ => throw new ArgumentException($"Invalid type: {type}", nameof(type)) + }; + } + /// /// Allocates a new instance of the specified type. /// @@ -223,6 +265,25 @@ public static class GraphicsDeviceExtensions }; } + /// + /// Allocates a new instance of the specified type. + /// + /// The type of items in the texture. + /// The target instance to allocate the texture for. + /// The type of texture to allocate. + /// The data to load on the texture. + /// A instance of the requested type. + public static Texture1D AllocateTexture1D(this GraphicsDevice device, Type type, T[] data) + where T : unmanaged + { + return type switch + { + _ when type == typeof(ReadOnlyTexture1D<>) => device.AllocateReadOnlyTexture1D(data), + _ when type == typeof(ReadWriteTexture1D<>) => device.AllocateReadWriteTexture1D(data), + _ => throw new ArgumentException($"Invalid type: {type}", nameof(type)) + }; + } + /// /// Allocates a new instance of the specified type. /// From 429dca7b1636f326432d96ae997ad03dc0c5d1de Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 1 Sep 2022 00:52:17 +0200 Subject: [PATCH 14/17] Add Texture1D tests --- .../Texture1DTests.Pixels.g.cs | 157 ++++++++++++++++++ .../Texture1DTests.Pixels.tt | 84 ++++++++++ 2 files changed, 241 insertions(+) create mode 100644 tests/ComputeSharp.Tests/Texture1DTests.Pixels.g.cs create mode 100644 tests/ComputeSharp.Tests/Texture1DTests.Pixels.tt diff --git a/tests/ComputeSharp.Tests/Texture1DTests.Pixels.g.cs b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.g.cs new file mode 100644 index 00000000..35a34f40 --- /dev/null +++ b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.g.cs @@ -0,0 +1,157 @@ +using System; +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests; + +[TestClass] +[TestCategory("Texture1D")] +public partial class Texture1DTests +{ + [CombinatorialTestMethod] + [AllDevices] + [Data(typeof(Bgra32), typeof(Float4))] + [Data(typeof(R16), typeof(float))] + [Data(typeof(R8), typeof(float))] + [Data(typeof(Rg16), typeof(Float2))] + [Data(typeof(Rg32), typeof(Float2))] + [Data(typeof(Rgba32), typeof(Float4))] + [Data(typeof(Rgba64), typeof(Float4))] + public void Dispatch_NormalizedTexture1D(Device device, Type t, Type tPixel) + { + if (t == typeof(Bgra32) && tPixel == typeof(Float4)) + { + using ReadOnlyTexture1D source = device.Get().AllocateReadOnlyTexture1D(128); + using ReadWriteTexture1D destination = device.Get().AllocateReadWriteTexture1D(128); + + device.Get().For(128, new Shader_Unorm_Bgra32_Float4(source, destination)); + } + if (t == typeof(R16) && tPixel == typeof(float)) + { + using ReadOnlyTexture1D source = device.Get().AllocateReadOnlyTexture1D(128); + using ReadWriteTexture1D destination = device.Get().AllocateReadWriteTexture1D(128); + + device.Get().For(128, new Shader_Unorm_R16_float(source, destination)); + } + if (t == typeof(R8) && tPixel == typeof(float)) + { + using ReadOnlyTexture1D source = device.Get().AllocateReadOnlyTexture1D(128); + using ReadWriteTexture1D destination = device.Get().AllocateReadWriteTexture1D(128); + + device.Get().For(128, new Shader_Unorm_R8_float(source, destination)); + } + if (t == typeof(Rg16) && tPixel == typeof(Float2)) + { + using ReadOnlyTexture1D source = device.Get().AllocateReadOnlyTexture1D(128); + using ReadWriteTexture1D destination = device.Get().AllocateReadWriteTexture1D(128); + + device.Get().For(128, new Shader_Unorm_Rg16_Float2(source, destination)); + } + if (t == typeof(Rg32) && tPixel == typeof(Float2)) + { + using ReadOnlyTexture1D source = device.Get().AllocateReadOnlyTexture1D(128); + using ReadWriteTexture1D destination = device.Get().AllocateReadWriteTexture1D(128); + + device.Get().For(128, new Shader_Unorm_Rg32_Float2(source, destination)); + } + if (t == typeof(Rgba32) && tPixel == typeof(Float4)) + { + using ReadOnlyTexture1D source = device.Get().AllocateReadOnlyTexture1D(128); + using ReadWriteTexture1D destination = device.Get().AllocateReadWriteTexture1D(128); + + device.Get().For(128, new Shader_Unorm_Rgba32_Float4(source, destination)); + } + if (t == typeof(Rgba64) && tPixel == typeof(Float4)) + { + using ReadOnlyTexture1D source = device.Get().AllocateReadOnlyTexture1D(128); + using ReadWriteTexture1D destination = device.Get().AllocateReadWriteTexture1D(128); + + device.Get().For(128, new Shader_Unorm_Rgba64_Float4(source, destination)); + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Bgra32_Float4 : IComputeShader + { + public readonly ReadOnlyTexture1D source; + public readonly ReadWriteTexture1D destination; + + public void Execute() + { + destination[ThreadIds.X] = (source[ThreadIds.X] + destination[ThreadIds.X]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_R16_float : IComputeShader + { + public readonly ReadOnlyTexture1D source; + public readonly ReadWriteTexture1D destination; + + public void Execute() + { + destination[ThreadIds.X] = (source[ThreadIds.X] + destination[ThreadIds.X]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_R8_float : IComputeShader + { + public readonly ReadOnlyTexture1D source; + public readonly ReadWriteTexture1D destination; + + public void Execute() + { + destination[ThreadIds.X] = (source[ThreadIds.X] + destination[ThreadIds.X]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rg16_Float2 : IComputeShader + { + public readonly ReadOnlyTexture1D source; + public readonly ReadWriteTexture1D destination; + + public void Execute() + { + destination[ThreadIds.X] = (source[ThreadIds.X] + destination[ThreadIds.X]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rg32_Float2 : IComputeShader + { + public readonly ReadOnlyTexture1D source; + public readonly ReadWriteTexture1D destination; + + public void Execute() + { + destination[ThreadIds.X] = (source[ThreadIds.X] + destination[ThreadIds.X]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rgba32_Float4 : IComputeShader + { + public readonly ReadOnlyTexture1D source; + public readonly ReadWriteTexture1D destination; + + public void Execute() + { + destination[ThreadIds.X] = (source[ThreadIds.X] + destination[ThreadIds.X]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rgba64_Float4 : IComputeShader + { + public readonly ReadOnlyTexture1D source; + public readonly ReadWriteTexture1D destination; + + public void Execute() + { + destination[ThreadIds.X] = (source[ThreadIds.X] + destination[ThreadIds.X]) / 2; + } + } +} diff --git a/tests/ComputeSharp.Tests/Texture1DTests.Pixels.tt b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.tt new file mode 100644 index 00000000..fd768705 --- /dev/null +++ b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.tt @@ -0,0 +1,84 @@ +<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ assembly name="System.Core" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Text" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ output extension=".g.cs"#> +<# +var typesMap = new Dictionary +{ + ["Bgra32"] = new[] { "Float4" }, + ["R16"] = new[] { "float" }, + ["R8"] = new[] { "float" }, + ["Rg16"] = new[] { "Float2" }, + ["Rg32"] = new[] { "Float2" }, + ["Rgba32"] = new[] { "Float4" }, + ["Rgba64"] = new[] { "Float4" } +}; + +IEnumerable<(string T, string TPixel)> EnumerateTypes() +{ + foreach (var pair in typesMap) + foreach (var tPixel in pair.Value) + yield return (pair.Key, tPixel); +} +#> +using System; +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests; + +[TestClass] +[TestCategory("Texture1D")] +public partial class Texture1DTests +{ + [CombinatorialTestMethod] + [AllDevices] +<# +foreach (var (t, tPixel) in EnumerateTypes()) +{ +#> + [Data(typeof(<#=t#>), typeof(<#=tPixel#>))] +<# +} +#> + public void Dispatch_NormalizedTexture1D(Device device, Type t, Type tPixel) + { +<# +foreach (var (t, tPixel) in EnumerateTypes()) +{ +#> + if (t == typeof(<#=t#>) && tPixel == typeof(<#=tPixel#>)) + { + using ReadOnlyTexture1D<<#=t#>, <#=tPixel#>> source = device.Get().AllocateReadOnlyTexture1D<<#=t#>, <#=tPixel#>>(128); + using ReadWriteTexture1D<<#=t#>, <#=tPixel#>> destination = device.Get().AllocateReadWriteTexture1D<<#=t#>, <#=tPixel#>>(128); + + device.Get().For(128, new Shader_Unorm_<#=t#>_<#=tPixel#>(source, destination)); + } +<# +} +#> + } +<# + +foreach (var (t, tPixel) in EnumerateTypes()) +{ +#> + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_<#=t#>_<#=tPixel#> : IComputeShader + { + public readonly ReadOnlyTexture1D<<#=t#>, <#=tPixel#>> source; + public readonly ReadWriteTexture1D<<#=t#>, <#=tPixel#>> destination; + + public void Execute() + { + destination[ThreadIds.X] = (source[ThreadIds.X] + destination[ThreadIds.X]) / 2; + } + } +<# +} +#> +} From a79e777064d00300ce4f03a4b67348e92c1b1a99 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 1 Sep 2022 01:55:33 +0200 Subject: [PATCH 15/17] Add Texture1D sampling tests --- .../Texture1DTests.Pixels.cs | 167 ++++++++++++++++++ .../Texture1DTests.Pixels.g.cs | 5 +- .../Texture1DTests.Pixels.tt | 5 +- 3 files changed, 169 insertions(+), 8 deletions(-) create mode 100644 tests/ComputeSharp.Tests/Texture1DTests.Pixels.cs diff --git a/tests/ComputeSharp.Tests/Texture1DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.cs new file mode 100644 index 00000000..a81500bd --- /dev/null +++ b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.cs @@ -0,0 +1,167 @@ +using System; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +using CommunityToolkit.HighPerformance; +using ComputeSharp.Resources; +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using ComputeSharp.Tests.Helpers; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SixLabors.ImageSharp; +using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; + +namespace ComputeSharp.Tests; + +[TestClass] +[TestCategory("Texture1D")] +public partial class Texture1DTests +{ + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture1D<,>))] + [Resource(typeof(ReadWriteTexture1D<,>))] + [Data(typeof(Bgra32), typeof(float4))] + [Data(typeof(R16), typeof(float))] + [Data(typeof(R8), typeof(float))] + [Data(typeof(Rg16), typeof(float2))] + [Data(typeof(Rg32), typeof(float2))] + [Data(typeof(Rgba32), typeof(float4))] + [Data(typeof(Rgba64), typeof(float4))] + public void Allocate_Uninitialized_Pixel_Ok(Device device, Type textureType, Type t, Type tPixel) + { + static void Test(Device device, Type textureType) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + using Texture1D texture = device.Get().AllocateTexture1D(textureType, 128); + + Assert.IsNotNull(texture); + Assert.AreEqual(texture.Width, 128); + Assert.AreSame(texture.GraphicsDevice, device.Get()); + + if (textureType == typeof(ReadOnlyTexture1D<,>)) + { + Assert.IsTrue(texture is ReadOnlyTexture1D); + } + else + { + Assert.IsTrue(texture is ReadWriteTexture1D); + } + } + + TestHelper.Run(Test, t, tPixel, device, textureType); + } + + [CombinatorialTestMethod] + [AllDevices] + public void SampleFromSourceTexture_ComputeShader(Device device) + { + _ = device.Get(); + + string imagingPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); + string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets"); + + using var original = Image.Load(Path.Combine(imagingPath, "city.jpg")); + using var sampled = Image.Load(Path.Combine(assetsPath, "CityAfter1024x1024Sampling.png")); + + if (!original.DangerousTryGetSinglePixelMemory(out Memory originalMemory)) + { + Assert.Inconclusive(); + } + + Span row = MemoryMarshal.Cast(originalMemory.Span.Slice(0, original.Width)); + + using ReadOnlyTexture1D source = device.Get().AllocateReadOnlyTexture1D(row); + using ReadWriteTexture1D destination = device.Get().AllocateReadWriteTexture1D(sampled.Width); + + device.Get().For(sampled.Width, new SamplingComputeShader(source, destination)); + + Rgba32[] processed = destination.ToArray(); + + if (!sampled.DangerousTryGetSinglePixelMemory(out Memory sampledMemory)) + { + Assert.Inconclusive(); + } + + using var sampledRow = Image.WrapMemory(sampledMemory.Slice(0, sampled.Width), sampled.Width, 1); + using var processedRow = Image.WrapMemory(processed.AsMemory().Cast(), sampled.Width, 1); + + TolerantImageComparer.AssertEqual(sampledRow, processedRow, 0.0000017f); + } + + [AutoConstructor] + public readonly partial struct SamplingComputeShader : IComputeShader + { + public readonly IReadOnlyNormalizedTexture1D source; + public readonly IReadWriteNormalizedTexture1D destination; + + public void Execute() + { + destination[ThreadIds.X] = source.Sample(ThreadIds.Normalized.X); + } + } + + [CombinatorialTestMethod] + [AllDevices] + [Data(typeof(Bgra32), typeof(float4))] + [Data(typeof(R16), typeof(float))] + [Data(typeof(R8), typeof(float))] + [Data(typeof(Rg16), typeof(float2))] + [Data(typeof(Rg32), typeof(float2))] + [Data(typeof(Rgba32), typeof(float4))] + [Data(typeof(Rgba64), typeof(float4))] + public void AsReadOnly_MultipleCalls_SameInstance(Device device, Type t, Type tPixel) + { + static void Test(Device device) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + using ReadWriteTexture1D texture = device.Get().AllocateReadWriteTexture1D(64); + + using (var context = device.Get().CreateComputeContext()) + { + context.Transition(texture, ResourceState.ReadOnly); + + IReadOnlyNormalizedTexture1D wrapper1 = texture.AsReadOnly(); + + Assert.IsNotNull(wrapper1); + + IReadOnlyNormalizedTexture1D wrapper2 = texture.AsReadOnly(); + + Assert.IsNotNull(wrapper2); + Assert.AreSame(wrapper1, wrapper2); + + context.Transition(texture, ResourceState.ReadWrite); + } + } + + TestHelper.Run(Test, t, tPixel, device); + } + + [CombinatorialTestMethod] + [AllDevices] + [Data(typeof(Bgra32), typeof(float4))] + [Data(typeof(R16), typeof(float))] + [Data(typeof(R8), typeof(float))] + [Data(typeof(Rg16), typeof(float2))] + [Data(typeof(Rg32), typeof(float2))] + [Data(typeof(Rgba32), typeof(float4))] + [Data(typeof(Rgba64), typeof(float4))] + [ExpectedException(typeof(InvalidOperationException))] + public void AsReadOnly_InvalidState_ThrowInvalidOperationException(Device device, Type t, Type tPixel) + { + static void Test(Device device) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + using ReadWriteTexture1D texture = device.Get().AllocateReadWriteTexture1D(64); + + _ = texture.AsReadOnly(); + + Assert.Fail(); + } + + TestHelper.Run(Test, t, tPixel, device); + } +} diff --git a/tests/ComputeSharp.Tests/Texture1DTests.Pixels.g.cs b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.g.cs index 35a34f40..a2971a09 100644 --- a/tests/ComputeSharp.Tests/Texture1DTests.Pixels.g.cs +++ b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.g.cs @@ -1,13 +1,10 @@ using System; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; -using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComputeSharp.Tests; -[TestClass] -[TestCategory("Texture1D")] -public partial class Texture1DTests +partial class Texture1DTests { [CombinatorialTestMethod] [AllDevices] diff --git a/tests/ComputeSharp.Tests/Texture1DTests.Pixels.tt b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.tt index fd768705..29e2195d 100644 --- a/tests/ComputeSharp.Tests/Texture1DTests.Pixels.tt +++ b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.tt @@ -26,13 +26,10 @@ IEnumerable<(string T, string TPixel)> EnumerateTypes() using System; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; -using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComputeSharp.Tests; -[TestClass] -[TestCategory("Texture1D")] -public partial class Texture1DTests +partial class Texture1DTests { [CombinatorialTestMethod] [AllDevices] From 2528c0a069e6bf6438a0c8d3aa6b9e8ec1281250 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 1 Sep 2022 02:27:11 +0200 Subject: [PATCH 16/17] Add range tests for Texture1D --- .../Texture1DTests.Pixels.cs | 4 +- tests/ComputeSharp.Tests/Texture1DTests.cs | 406 ++++++++++++++++++ 2 files changed, 407 insertions(+), 3 deletions(-) create mode 100644 tests/ComputeSharp.Tests/Texture1DTests.cs diff --git a/tests/ComputeSharp.Tests/Texture1DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.cs index a81500bd..4c60ce88 100644 --- a/tests/ComputeSharp.Tests/Texture1DTests.Pixels.cs +++ b/tests/ComputeSharp.Tests/Texture1DTests.Pixels.cs @@ -13,9 +13,7 @@ using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; namespace ComputeSharp.Tests; -[TestClass] -[TestCategory("Texture1D")] -public partial class Texture1DTests +partial class Texture1DTests { [CombinatorialTestMethod] [AllDevices] diff --git a/tests/ComputeSharp.Tests/Texture1DTests.cs b/tests/ComputeSharp.Tests/Texture1DTests.cs new file mode 100644 index 00000000..d7fd68a3 --- /dev/null +++ b/tests/ComputeSharp.Tests/Texture1DTests.cs @@ -0,0 +1,406 @@ +using System; +using System.Linq; +using ComputeSharp.Resources; +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests; + +[TestClass] +[TestCategory("Texture1D")] +public partial class Texture1DTests +{ + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture1D<>))] + [Resource(typeof(ReadWriteTexture1D<>))] + [Data(AllocationMode.Default)] + [Data(AllocationMode.Clear)] + public void Allocate_Uninitialized_Ok(Device device, Type textureType, AllocationMode allocationMode) + { + using Texture1D texture = device.Get().AllocateTexture1D(textureType, 128, allocationMode); + + Assert.IsNotNull(texture); + Assert.AreEqual(texture.Width, 128); + Assert.AreSame(texture.GraphicsDevice, device.Get()); + + if (allocationMode == AllocationMode.Clear) + { + foreach (float x in texture.ToArray()) + { + Assert.AreEqual(x, 0f); + } + } + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture1D<>))] + [Resource(typeof(ReadWriteTexture1D<>))] + [Data(-14253)] + [Data(-1)] + [Data(0)] + [Data(-14)] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Allocate_Uninitialized_Fail(Device device, Type textureType, int width) + { + using Texture1D texture = device.Get().AllocateTexture1D(textureType, width); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture1D<>))] + [Resource(typeof(ReadWriteTexture1D<>))] + public void Allocate_FromArray(Device device, Type textureType) + { + float[] data = Enumerable.Range(0, 128).Select(static i => (float)i).ToArray(); + + using Texture1D texture = device.Get().AllocateTexture1D(textureType, data); + + Assert.IsNotNull(texture); + Assert.AreEqual(texture.Width, 128); + Assert.AreSame(texture.GraphicsDevice, device.Get()); + + float[] result = texture.ToArray(); + + Assert.IsNotNull(result); + Assert.AreEqual(data.Length, result.Length); + Assert.IsTrue(data.SequenceEqual(result)); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture1D<>))] + [Resource(typeof(ReadWriteTexture1D<>))] + [ExpectedException(typeof(ObjectDisposedException))] + public void UsageAfterDispose(Device device, Type textureType) + { + using Texture1D texture = device.Get().AllocateTexture1D(textureType, 10); + + texture.Dispose(); + + _ = texture.ToArray(); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture1D<>))] + [Resource(typeof(ReadWriteTexture1D<>))] + [Data(0, 64)] + [Data(0, 64)] + [Data(14, 50)] + [Data(10, 54)] + [Data(20, 32)] + [Data(60, 4)] + [Data(0, 64)] + [Data(63, 1)] + [Data(2, 60)] + public void GetData_RangeToArray_Ok(Device device, Type textureType, int x, int width) + { + float[] array = Enumerable.Range(0, 256).Select(static i => (float)i).ToArray(); + + using Texture1D texture = device.Get().AllocateTexture1D(textureType, array); + + float[] result = texture.ToArray(x, width); + + Assert.AreEqual(width, result.Length); + + Span expected = array.AsSpan(x, width); + + CollectionAssert.AreEqual(expected.ToArray(), result); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture1D<>))] + [Resource(typeof(ReadWriteTexture1D<>))] + [Data(-1, 20)] + [Data(20, -1)] + [Data(64, 1)] + [Data(12, 200)] + [Data(80, 40)] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void GetData_RangeToArray_Fail(Device device, Type textureType, int x, int width) + { + using Texture1D texture = device.Get().AllocateTexture1D(textureType, 64); + + _ = texture.ToArray(x, width); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture1D<>))] + [Resource(typeof(ReadWriteTexture1D<>))] + [Data(0, 64)] + [Data(0, 64)] + [Data(14, 50)] + [Data(10, 54)] + [Data(20, 32)] + [Data(60, 4)] + [Data(0, 64)] + [Data(63, 1)] + [Data(2, 60)] + public void GetData_RangeToVoid_Ok(Device device, Type textureType, int x, int width) + { + float[] array = Enumerable.Range(0, 512).Select(static i => (float)i).ToArray(); + + using Texture1D texture = device.Get().AllocateTexture1D(textureType, array); + + float[] result = new float[width]; + + texture.CopyTo(result, x, width); + + Span expected = array.AsSpan(x, width); + + CollectionAssert.AreEqual(expected.ToArray(), result); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture1D<>))] + [Resource(typeof(ReadWriteTexture1D<>))] + [Data(0, 500)] + [Data(-1, 50)] + [Data(12, -1)] + [Data(128, 1)] + [Data(12, -20)] + [Data(0, -40)] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void GetData_RangeToVoid_Fail(Device device, Type textureType, int x, int width) + { + float[] array = Enumerable.Range(0, 128).Select(static i => (float)i).ToArray(); + + using Texture1D texture = device.Get().AllocateTexture1D(textureType, array); + + float[] result = new float[128]; + + texture.CopyTo(result, x, width); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture1D<>))] + [Resource(typeof(ReadWriteTexture1D<>))] + [AdditionalResource(typeof(ReadOnlyTexture1D<>))] + [AdditionalResource(typeof(ReadWriteTexture1D<>))] + [Data(1024, 1024, 0, 0, 1024)] + [Data(1024, 1024, 0, 256, 480)] + [Data(1024, 1024, 127, 256, 480)] + [Data(1024, 1024, 256, 0, 480)] + [Data(512, 1024, 29, 127, 320)] + [Data(512, 256, 120, 0, 256)] + public void CopyTo_TextureToVoid_Ok( + Device device, + Type sourceType, + Type destinationType, + int sourceWidth, + int destinationWidth, + int sourceOffsetX, + int destinationOffsetX, + int copyWidth) + { + float[] array = Enumerable.Range(0, sourceWidth).Select(static i => (float)i).ToArray(); + + using Texture1D source = device.Get().AllocateTexture1D(sourceType, array); + using Texture1D destination = device.Get().AllocateTexture1D(destinationType, destinationWidth, AllocationMode.Clear); + + source.CopyTo(destination, sourceOffsetX, destinationOffsetX, copyWidth); + + ReadOnlySpan expected = array; + ReadOnlySpan result = destination.ToArray(); + + for (int i = 0; i < destinationWidth; i++) + { + if (i >= destinationOffsetX && + i < destinationOffsetX + copyWidth) + { + int sourceX = i - destinationOffsetX + sourceOffsetX; + + Assert.AreEqual(expected[sourceX], result[i]); + } + else + { + Assert.AreEqual(0, result[i]); + } + } + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture1D<>))] + [Resource(typeof(ReadWriteTexture1D<>))] + [AdditionalResource(typeof(ReadOnlyTexture1D<>))] + [AdditionalResource(typeof(ReadWriteTexture1D<>))] + [Data(1024, 1024, 0, 0, 2055)] + [Data(1024, 1024, 0, 0, 3920)] + [Data(1024, 1024, 0, 0, -1)] + [Data(1024, 1024, 0, 0, -2)] + [Data(1024, 1024, 0, 0, int.MaxValue)] + [Data(512, 1024, 0, 768, 768)] + [Data(512, 1024, 0, 256, 768)] + [Data(512, 1024, 0, 620, 480)] + [Data(512, 512, 450, 0, 128)] + [Data(512, 512, 0, 450, 128)] + [Data(512, 512, -1, 0, 128)] + [Data(512, 512, 0, -1, 128)] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void CopyTo_TextureToVoid_Fail( + Device device, + Type sourceType, + Type destinationType, + int sourceWidth, + int destinationWidth, + int sourceOffsetX, + int destinationOffsetX, + int copyWidth) + { + using Texture1D source = device.Get().AllocateTexture1D(sourceType, sourceWidth); + using Texture1D destination = device.Get().AllocateTexture1D(destinationType, destinationWidth, AllocationMode.Clear); + + source.CopyTo(destination, sourceOffsetX, destinationOffsetX, copyWidth); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture1D<>))] + [Resource(typeof(ReadWriteTexture1D<>))] + [AdditionalResource(typeof(ReadOnlyTexture1D<>))] + [AdditionalResource(typeof(ReadWriteTexture1D<>))] + [Data(1024, 1024, 0, 0, 1024)] + [Data(1024, 1024, 127, 256, 480)] + [Data(1024, 1024, 0, 127, 480)] + [Data(1024, 1024, 122, 329, 480)] + [Data(512, 1024, 122, 256, 320)] + [Data(512, 256, 0, 0, 256)] + [Data(512, 1024, 0, 512, 512)] + [Data(512, 1024, 0, 0, 512)] + public void CopyFrom_TextureToVoid_Ok( + Device device, + Type sourceType, + Type destinationType, + int sourceWidth, + int destinationWidth, + int sourceOffsetX, + int destinationOffsetX, + int copyWidth) + { + float[] array = Enumerable.Range(0, sourceWidth).Select(static i => (float)i).ToArray(); + + using Texture1D source = device.Get().AllocateTexture1D(sourceType, array); + using Texture1D destination = device.Get().AllocateTexture1D(destinationType, destinationWidth, AllocationMode.Clear); + + destination.CopyFrom(source, sourceOffsetX, destinationOffsetX, copyWidth); + + ReadOnlySpan expected = array; + ReadOnlySpan result = destination.ToArray(); + + for (int i = 0; i < destinationWidth; i++) + { + if (i >= destinationOffsetX && + i < destinationOffsetX + copyWidth) + { + int sourceX = i - destinationOffsetX + sourceOffsetX; + + Assert.AreEqual(expected[sourceX], result[i]); + } + else + { + Assert.AreEqual(0, result[i]); + } + } + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture1D<>))] + [Resource(typeof(ReadWriteTexture1D<>))] + [AdditionalResource(typeof(ReadOnlyTexture1D<>))] + [AdditionalResource(typeof(ReadWriteTexture1D<>))] + [Data(1024, 1024, 1024, 0, 2055)] + [Data(1024, 1024, 1024, 0, 3920)] + [Data(1024, 1024, 1024, 0, -1)] + [Data(1024, 1024, 1024, 0, int.MaxValue)] + [Data(512, 1024, 0, 0, 768)] + [Data(512, 1024, 0, 0, 620)] + [Data(1024, 512, 512, 0, 768)] + [Data(1024, 512, 512, 0, 620)] + [Data(512, 512, 450, 0, 128)] + [Data(512, 512, 0, 450, 128)] + [Data(512, 512, -1, 0, 128)] + [Data(512, 512, 0, -1, 128)] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void CopyFrom_TextureToVoid_Fail( + Device device, + Type sourceType, + Type destinationType, + int sourceWidth, + int destinationWidth, + int sourceOffsetX, + int destinationOffsetX, + int copyWidth) + { + using Texture1D source = device.Get().AllocateTexture1D(sourceType, sourceWidth); + using Texture1D destination = device.Get().AllocateTexture1D(destinationType, destinationWidth, AllocationMode.Clear); + + destination.CopyFrom(source, sourceOffsetX, destinationOffsetX, copyWidth); + } + + [CombinatorialTestMethod] + [AllDevices] + public void Dispatch_ReadOnlyTexture1D(Device device) + { + int[] data = Enumerable.Range(0, 256).ToArray(); + + using ReadOnlyTexture1D source = device.Get().AllocateReadOnlyTexture1D(data); + using ReadWriteBuffer destination = device.Get().AllocateReadWriteBuffer(data.Length); + + device.Get().For(source.Width, new ReadOnlyTexture1DKernel(source, destination)); + + int[] result = destination.ToArray(); + + CollectionAssert.AreEqual(data, result); + } + + [AutoConstructor] + internal readonly partial struct ReadOnlyTexture1DKernel : IComputeShader + { + public readonly ReadOnlyTexture1D source; + public readonly ReadWriteBuffer destination; + + public void Execute() + { + destination[ThreadIds.X] = source[ThreadIds.X]; + } + } + + [CombinatorialTestMethod] + [AllDevices] + public void Dispatch_ReadWriteTexture1D(Device device) + { + int[] data = Enumerable.Range(0,256).ToArray(); + + using ReadWriteTexture1D source = device.Get().AllocateReadWriteTexture1D(data); + using ReadWriteTexture1D destination = device.Get().AllocateReadWriteTexture1D(256); + + device.Get().For(source.Width, new ReadWriteTexture1DKernel(source, destination)); + + int[] result = new int[data.Length]; + + destination.CopyTo(result); + + CollectionAssert.AreEqual(data, result); + } + + [AutoConstructor] + internal readonly partial struct ReadWriteTexture1DKernel : IComputeShader + { + public readonly ReadWriteTexture1D source; + public readonly ReadWriteTexture1D destination; + + public void Execute() + { + destination[ThreadIds.X] = source[ThreadIds.X]; + } + } +} From 46bd6c46e6c5678bbf10edc546ac52be65db1eba Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 1 Sep 2022 02:27:24 +0200 Subject: [PATCH 17/17] Remove unnecessary modifiers --- tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs | 2 +- tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs | 2 +- tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt | 2 +- tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs | 2 +- tests/ComputeSharp.Tests/Texture3DTests.Pixels.g.cs | 2 +- tests/ComputeSharp.Tests/Texture3DTests.Pixels.tt | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs index 91d19797..956500ba 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs @@ -11,7 +11,7 @@ using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; namespace ComputeSharp.Tests; -public partial class Texture2DTests +partial class Texture2DTests { [CombinatorialTestMethod] [AllDevices] diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs index a32e6235..b0815b9f 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs @@ -4,7 +4,7 @@ using ComputeSharp.Tests.Extensions; namespace ComputeSharp.Tests; -public partial class Texture2DTests +partial class Texture2DTests { [CombinatorialTestMethod] [AllDevices] diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt index 43d11ee2..da622b25 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt @@ -29,7 +29,7 @@ using ComputeSharp.Tests.Extensions; namespace ComputeSharp.Tests; -public partial class Texture2DTests +partial class Texture2DTests { [CombinatorialTestMethod] [AllDevices] diff --git a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs index a360030f..b482b4d3 100644 --- a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs +++ b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs @@ -7,7 +7,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComputeSharp.Tests; -public partial class Texture3DTests +partial class Texture3DTests { [CombinatorialTestMethod] [AllDevices] diff --git a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.g.cs b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.g.cs index 9debe150..5f3c08b7 100644 --- a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.g.cs +++ b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.g.cs @@ -4,7 +4,7 @@ using ComputeSharp.Tests.Extensions; namespace ComputeSharp.Tests; -public partial class Texture3DTests +partial class Texture3DTests { [CombinatorialTestMethod] [AllDevices] diff --git a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.tt b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.tt index e83e615a..003696f7 100644 --- a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.tt +++ b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.tt @@ -29,7 +29,7 @@ using ComputeSharp.Tests.Extensions; namespace ComputeSharp.Tests; -public partial class Texture3DTests +partial class Texture3DTests { [CombinatorialTestMethod] [AllDevices]