using System; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Enums; using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Helpers; using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; namespace ComputeSharp.Graphics.Buffers.Abstract { /// /// A representing a typed structured buffer stored on GPU memory /// /// The type of items stored on the buffer public abstract class HlslStructuredBuffer : HlslBuffer where T : unmanaged { /// /// Creates a new instance with the specified parameters /// /// The associated with the current instance /// The number of items to store in the current buffer /// The buffer type for the current buffer internal HlslStructuredBuffer(GraphicsDevice device, int size, BufferType bufferType) : base(device, size, size * Unsafe.SizeOf(), bufferType) { } /// public override unsafe void GetData(Span span, int offset, int count) { using Buffer transferBuffer = new Buffer(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.ReadBack); using (CommandList copyCommandList = new CommandList(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY)) { copyCommandList.CopyBufferRegion(D3D12Resource, offset * ElementSizeInBytes, transferBuffer.D3D12Resource, 0, count * ElementSizeInBytes); copyCommandList.ExecuteAndWaitForCompletion(); } using MappedResource resource = transferBuffer.MapResource(); MemoryHelper.Copy(resource.Pointer, 0, span, count); } /// public override unsafe void SetData(ReadOnlySpan span, int offset, int count) { using Buffer transferBuffer = new Buffer(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.Upload); using (MappedResource resource = transferBuffer.MapResource()) { MemoryHelper.Copy(span, resource.Pointer, 0, count); } using CommandList copyCommandList = new CommandList(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); copyCommandList.CopyBufferRegion(transferBuffer.D3D12Resource, 0, D3D12Resource, offset * ElementSizeInBytes, count * ElementSizeInBytes); copyCommandList.ExecuteAndWaitForCompletion(); } /// public override unsafe void SetData(HlslBuffer buffer) { if (!buffer.IsPaddingPresent) { // Directly copy the input buffer using CommandList copyCommandList = new CommandList(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); copyCommandList.CopyBufferRegion(buffer.D3D12Resource, 0, D3D12Resource, 0, SizeInBytes); copyCommandList.ExecuteAndWaitForCompletion(); } else SetDataWithCpuBuffer(buffer); } } }