From 799c4a06271b3ac358386bd06419c64b170b1a90 Mon Sep 17 00:00:00 2001 From: cosmonaut Date: Fri, 15 Jan 2021 18:25:25 -0800 Subject: [PATCH] change command buffers to be pooled --- src/CommandBuffer.cs | 8 ++++---- src/GraphicsDevice.cs | 31 ++++++++++++++++++++++++++----- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/src/CommandBuffer.cs b/src/CommandBuffer.cs index 74bf059..fdbc218 100644 --- a/src/CommandBuffer.cs +++ b/src/CommandBuffer.cs @@ -4,16 +4,16 @@ using RefreshCS; namespace Campari { - public struct CommandBuffer + public class CommandBuffer { public GraphicsDevice Device { get; } - public IntPtr Handle { get; } + public IntPtr Handle { get; internal set; } // called from RefreshDevice - internal CommandBuffer(GraphicsDevice device, IntPtr handle) + internal CommandBuffer(GraphicsDevice device) { Device = device; - Handle = handle; + Handle = IntPtr.Zero; } public void BeginRenderPass( diff --git a/src/GraphicsDevice.cs b/src/GraphicsDevice.cs index 7720aaa..8e207d2 100644 --- a/src/GraphicsDevice.cs +++ b/src/GraphicsDevice.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Text; using RefreshCS; namespace Campari @@ -12,10 +10,13 @@ namespace Campari public bool IsDisposed { get; private set; } + private Queue commandBufferPool; + public GraphicsDevice( IntPtr deviceWindowHandle, Refresh.PresentMode presentMode, - bool debugMode + bool debugMode, + int initialCommandBufferPoolSize = 4 ) { var presentationParameters = new Refresh.PresentationParameters { @@ -27,13 +28,26 @@ namespace Campari ref presentationParameters, Conversions.BoolToByte(debugMode) ); + + commandBufferPool = new Queue(initialCommandBufferPoolSize); + for (var i = 0; i < initialCommandBufferPoolSize; i += 1) + { + commandBufferPool.Enqueue(new CommandBuffer(this)); + } } - /* FIXME: pool this */ public CommandBuffer AcquireCommandBuffer() { var commandBufferHandle = Refresh.Refresh_AcquireCommandBuffer(Handle, 0); - return new CommandBuffer(this, commandBufferHandle); + if (commandBufferPool.Count == 0) + { + commandBufferPool.Enqueue(new CommandBuffer(this)); + } + + var commandBuffer = commandBufferPool.Dequeue(); + commandBuffer.Handle = commandBufferHandle; + + return commandBuffer; } public unsafe void Submit(params CommandBuffer[] commandBuffers) @@ -50,6 +64,13 @@ namespace Campari (uint) commandBuffers.Length, (IntPtr) commandBufferPtrs ); + + // return to pool + for (var i = 0; i < commandBuffers.Length; i += 1) + { + commandBuffers[i].Handle = IntPtr.Zero; + commandBufferPool.Enqueue(commandBuffers[i]); + } } protected virtual void Dispose(bool disposing)