using System;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Buffers.Enums;
using ComputeSharp.Graphics.Buffers.Interop;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.Graphics.Helpers;
using TerraFX.Interop;
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 StructuredBuffer : Buffer
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 StructuredBuffer(GraphicsDevice device, int size, BufferType bufferType)
: base(device, size, size * Unsafe.SizeOf(), bufferType)
{
}
///
public override unsafe void GetData(Span span, int offset, int count)
{
int
byteOffset = offset * ElementSizeInBytes,
byteSize = count * ElementSizeInBytes;
using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(BufferType.ReadBack, byteSize);
using (CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY))
{
copyCommandList.CopyBufferRegion(D3D12Resource, byteOffset, d3D12Resource.Get(), 0, byteSize);
copyCommandList.ExecuteAndWaitForCompletion();
}
using ID3D12ResourceMap resource = d3D12Resource.Get()->Map();
MemoryHelper.Copy(resource.Pointer, 0, span, count);
}
///
public override unsafe void SetData(ReadOnlySpan span, int offset, int count)
{
int
byteOffset = offset * ElementSizeInBytes,
byteSize = count * ElementSizeInBytes;
using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(BufferType.Upload, byteSize);
using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map())
{
MemoryHelper.Copy(span, resource.Pointer, 0, count);
}
using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY);
copyCommandList.CopyBufferRegion(d3D12Resource.Get(), 0, D3D12Resource, byteOffset, byteSize);
copyCommandList.ExecuteAndWaitForCompletion();
}
///
public override unsafe void SetData(Buffer buffer)
{
if (!buffer.IsPaddingPresent)
{
// Directly copy the input buffer
using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY);
copyCommandList.CopyBufferRegion(buffer.D3D12Resource, 0, D3D12Resource, 0, SizeInBytes);
copyCommandList.ExecuteAndWaitForCompletion();
}
else SetDataWithCpuBuffer(buffer);
}
}
}