using System; using Vortice.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(ID3D12Device device) { DescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); DescriptorHeapDescription descriptorHeapDescription = new DescriptorHeapDescription { DescriptorCount = DescriptorsPerHeap, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; DescriptorHeap = device.CreateDescriptorHeap(descriptorHeapDescription); _RemainingHandles = DescriptorsPerHeap; _CurrentCpuHandle = DescriptorHeap.GetCPUDescriptorHandleForHeapStart(); _CurrentGpuHandle = DescriptorHeap.GetGPUDescriptorHandleForHeapStart(); } /// /// Gets the object in use for the current instance /// public ID3D12DescriptorHeap 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.GetCPUDescriptorHandleForHeapStart(); _CurrentGpuHandle = DescriptorHeap.GetGPUDescriptorHandleForHeapStart(); } CpuDescriptorHandle cpuDescriptorHandle = _CurrentCpuHandle; GpuDescriptorHandle gpuDescriptorHandle = _CurrentGpuHandle; _CurrentCpuHandle += DescriptorSize; _CurrentGpuHandle += DescriptorSize; _RemainingHandles -= 1; return (cpuDescriptorHandle, gpuDescriptorHandle); } } /// public void Dispose() => DescriptorHeap.Dispose(); } }