using System;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Buffers.Enums;
using ComputeSharp.Graphics.Helpers;
using SharpDX.Direct3D12;
using CommandList = ComputeSharp.Graphics.Commands.CommandList;
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 void GetData(Span span, int offset, int count)
{
using Buffer transferBuffer = new Buffer(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.Transfer);
using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
copyCommandList.CopyBufferRegion(this, offset * ElementSizeInBytes, transferBuffer, 0, count * ElementSizeInBytes);
copyCommandList.Flush();
transferBuffer.Map(0);
MemoryHelper.Copy(transferBuffer.MappedResource, 0, span, 0, count);
transferBuffer.Unmap(0);
}
///
public override void SetData(Span span, int offset, int count)
{
using Buffer transferBuffer = new Buffer(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.Transfer);
transferBuffer.Map(0);
MemoryHelper.Copy(span, 0, transferBuffer.MappedResource, 0, count);
transferBuffer.Unmap(0);
using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
copyCommandList.CopyBufferRegion(transferBuffer, 0, this, offset * ElementSizeInBytes, count * ElementSizeInBytes);
copyCommandList.Flush();
}
///
public override void SetData(HlslBuffer buffer)
{
if (!buffer.IsPaddingPresent)
{
// Directly copy the input buffer
using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes);
copyCommandList.Flush();
}
else SetDataWithCpuBuffer(buffer);
}
}
}