using System;
using SharpDX.Direct3D12;
namespace ComputeSharp.Graphics
{
///
/// A that provides logic to create resource descriptors for a instance
///
internal sealed class DescriptorAllocator : IDisposable
{
///
/// The default number of available descriptors per heap
///
private const int DescriptorsPerHeap = 4096;
///
/// The dummy object used to handle concurrent allocation requests
///
private readonly object Lock = new object();
///
/// The size of each new descriptor being allocated
///
private readonly int DescriptorSize;
///
/// The current for the instance in use
///
private CpuDescriptorHandle _CurrentCpuHandle;
///
/// The current for the instance in use
///
private GpuDescriptorHandle _CurrentGpuHandle;
///
/// The number of remaining handles to allocate on the current heap
///
private int _RemainingHandles;
///
/// Creates a new instance with the specified parameters
///
/// The instance to use
public DescriptorAllocator(GraphicsDevice device)
{
DescriptorSize = device.NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
DescriptorHeapDescription descriptorHeapDescription = new DescriptorHeapDescription
{
DescriptorCount = DescriptorsPerHeap,
Flags = DescriptorHeapFlags.ShaderVisible,
Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView
};
DescriptorHeap = device.NativeDevice.CreateDescriptorHeap(descriptorHeapDescription);
_RemainingHandles = DescriptorsPerHeap;
_CurrentCpuHandle = DescriptorHeap.CPUDescriptorHandleForHeapStart;
_CurrentGpuHandle = DescriptorHeap.GPUDescriptorHandleForHeapStart;
}
///
/// Gets the object in use for the current instance
///
public DescriptorHeap DescriptorHeap { get; }
///
/// Allocates a new CPU and GPU handle pair to use in a memory buffer
///
/// A pair of and to use
public (CpuDescriptorHandle, GpuDescriptorHandle) Allocate()
{
lock (Lock)
{
if (_RemainingHandles == 0)
{
_RemainingHandles = DescriptorHeap.Description.DescriptorCount;
_CurrentCpuHandle = DescriptorHeap.CPUDescriptorHandleForHeapStart;
_CurrentGpuHandle = DescriptorHeap.GPUDescriptorHandleForHeapStart;
}
CpuDescriptorHandle cpuDescriptorHandle = _CurrentCpuHandle;
GpuDescriptorHandle gpuDescriptorHandle = _CurrentGpuHandle;
_CurrentCpuHandle += DescriptorSize;
_CurrentGpuHandle += DescriptorSize;
_RemainingHandles -= 1;
return (cpuDescriptorHandle, gpuDescriptorHandle);
}
}
///
public void Dispose() => DescriptorHeap.Dispose();
}
}