using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using ComputeSharp.Graphics.Commands.Abstract; using Vortice.Direct3D12; namespace ComputeSharp.Graphics.Commands { /// /// A that acts as a pool to get new instances wheen needed /// internal sealed class CommandAllocatorPool : CommandController { /// /// The queue of currently pooled instances /// private readonly Queue<(ID3D12CommandAllocator CommandAllocator, long FenceValue)> CommandAllocatorQueue = new Queue<(ID3D12CommandAllocator, long)>(); /// public CommandAllocatorPool(GraphicsDevice device, CommandListType commandListType) : base(device, commandListType) { } /// /// Adds a new item to the internal pool queue /// /// The input to enqueue /// The fence value for the input public void Enqueue(ID3D12CommandAllocator commandAllocator, long fenceValue) { lock (CommandAllocatorQueue) { CommandAllocatorQueue.Enqueue((commandAllocator, fenceValue)); } } /// /// Gets a new or reused item to use to issue GPU commands /// [Pure] public ID3D12CommandAllocator GetCommandAllocator() { lock (CommandAllocatorQueue) { if (CommandAllocatorQueue.Count > 0) { (ID3D12CommandAllocator commandAllocator, long fenceValue) = CommandAllocatorQueue.Peek(); long completedValue = CommandListType switch { CommandListType.Compute => GraphicsDevice.NativeComputeFence.CompletedValue, CommandListType.Copy => GraphicsDevice.NativeCopyFence.CompletedValue, CommandListType.Direct => GraphicsDevice.NativeDirectFence.CompletedValue, _ => throw new NotSupportedException($"Unsupported command list type with value {CommandListType}") }; if (fenceValue <= completedValue) { CommandAllocatorQueue.Dequeue(); commandAllocator.Reset(); return commandAllocator; } } return GraphicsDevice.NativeDevice.CreateCommandAllocator(CommandListType); } } /// public override void Dispose() { lock (CommandAllocatorQueue) { foreach ((ID3D12CommandAllocator commandAllocator, long _) in CommandAllocatorQueue) { commandAllocator.Dispose(); } CommandAllocatorQueue.Clear(); } } } }