using System; using System.Buffers; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Abstract; using ComputeSharp.Graphics.Helpers; using SharpDX.Direct3D12; namespace ComputeSharp.Graphics.Buffers { /// /// A representing a typed read write buffer stored on GPU memory /// /// The type of items stored on the buffer public sealed class ReadOnlyBuffer : HlslBuffer where T : unmanaged { /// /// Creates a new instance with the specified parameters /// /// The associated with the current instance /// The number of items to store in the current buffer internal ReadOnlyBuffer(GraphicsDevice device, int size) : base(device, size, size * (Unsafe.SizeOf() / 16 + 1) * 16, HeapType.Upload) { PaddedElementSizeInBytes = SizeInBytes / Size; } /// /// Gets the size in bytes of the current buffer /// private int PaddedElementSizeInBytes { get; } /// /// Gets a single value from the current read write buffer /// /// The index of the value to get /// This API can only be used from a compute shader, and will always throw if used anywhere else public T this[uint i] => throw new InvalidOperationException("The indexer APIs can only be used from a compute shader"); /// public override void GetData(Span span) { byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); Span temporarySpan = temporaryArray.AsSpan(); Map(0); MemoryHelper.Copy(MappedResource, temporarySpan); Unmap(0); ref byte tin = ref temporarySpan.GetPinnableReference(); ref T tout = ref span.GetPinnableReference(); for (int i = 0; i < Size; i++) { ref byte rsource = ref Unsafe.Add(ref tin, i * PaddedElementSizeInBytes); Unsafe.Add(ref tout, i) = Unsafe.As(ref rsource); } ArrayPool.Shared.Return(temporaryArray); } /// public override void SetData(Span span) { byte[] temporaryArray = ArrayPool.Shared.Rent(SizeInBytes); Span temporarySpan = temporaryArray.AsSpan(0, SizeInBytes); // Array pool arrays can be longer ref T tin = ref span.GetPinnableReference(); ref byte tout = ref temporarySpan.GetPinnableReference(); temporarySpan.Clear(); for (int i = 0; i < Size; i++) { ref byte rtarget = ref Unsafe.Add(ref tout, i * PaddedElementSizeInBytes); Unsafe.As(ref rtarget) = Unsafe.Add(ref tin, i); } Map(0); MemoryHelper.Copy(temporarySpan, MappedResource); Unmap(0); ArrayPool.Shared.Return(temporaryArray); } } }