using ComputeSharp.Graphics.Extensions; using System; using TerraFX.Interop; using static TerraFX.Interop.D3D12_DESCRIPTOR_HEAP_TYPE; namespace ComputeSharp.Graphics { /// /// A type that provides logic to create resource descriptors for a instance. /// internal unsafe struct DescriptorAllocator2 : IDisposable { /// /// The default number of available descriptors per heap. /// private const uint DescriptorsPerHeap = 4096; /// /// The in use for the current instance. /// private ComPtr d3D12DescriptorHeap; /// /// The dummy object used to handle concurrent allocation requests. /// private readonly object allocationLock; /// /// The size of each new descriptor being allocated. /// private readonly uint descriptorSize; /// /// The current for the instance in use. /// private D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandle; /// /// The current for the instance in use. /// private D3D12_GPU_DESCRIPTOR_HANDLE d3d12GpuDescriptorHandle; /// /// The number of remaining handles to allocate on the current heap. /// private uint remainingHandles; /// /// Creates a new instance with the specified parameters. /// /// The instance to use public DescriptorAllocator2(ID3D12Device* device) { this.d3D12DescriptorHeap = device->CreateDescriptorHeap(DescriptorsPerHeap); this.allocationLock = new object(); this.descriptorSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); this.d3d12CpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetCPUDescriptorHandleForHeapStart(); this.d3d12GpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetGPUDescriptorHandleForHeapStart(); this.remainingHandles = this.d3D12DescriptorHeap.Get()->GetDesc().NumDescriptors; } /// /// Gets the in use for the current instance. /// public ID3D12DescriptorHeap* D3D12DescriptorHeap => this.d3D12DescriptorHeap; /// /// Allocates a new CPU and GPU handle pair to use in a memory buffer /// /// The resulting value. /// The resulting value. public void Allocate( out D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandle, out D3D12_GPU_DESCRIPTOR_HANDLE d3d12GpuDescriptorHandle) { lock (this.allocationLock) { if (this.remainingHandles == 0) { this.d3d12CpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetCPUDescriptorHandleForHeapStart(); this.d3d12GpuDescriptorHandle = this.d3D12DescriptorHeap.Get()->GetGPUDescriptorHandleForHeapStart(); this.remainingHandles = this.d3D12DescriptorHeap.Get()->GetDesc().NumDescriptors; } d3d12CpuDescriptorHandle = this.d3d12CpuDescriptorHandle; d3d12GpuDescriptorHandle = this.d3d12GpuDescriptorHandle; this.d3d12CpuDescriptorHandle.ptr += this.descriptorSize; this.d3d12GpuDescriptorHandle.ptr += this.descriptorSize; this.remainingHandles--; } } /// public void Dispose() { this.d3D12DescriptorHeap.Dispose(); } } }