SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
VulkanBuffer.hpp
Go to the documentation of this file.
1#ifndef VULKANBUFFER_HPP_
2#define VULKANBUFFER_HPP_
3
5#include <vulkan/vulkan.h>
6#include <vma/vk_mem_alloc.h>
7#include <vector>
8
9namespace Sleak {
10namespace RenderEngine {
11
12/// VMA-backed Vulkan buffer with staging uploads, batched copies, and a size-bucketed recycling pool.
13class ENGINE_API VulkanBuffer : public BufferBase {
14public:
15 VulkanBuffer(VkDevice device, VkPhysicalDevice physicalDevice,
16 uint32_t size, BufferType type,
17 VkCommandPool commandPool, VkQueue graphicsQueue);
18 ~VulkanBuffer() override;
19
20 /// Allocates the buffer (recycling a pooled one if a match exists) and uploads initial data, if any.
21 bool Initialize(void* data) override;
22 void Update() override;
23 /// Overwrites buffer contents, staging through a temporary buffer for device-local memory.
24 void Update(void* data, size_t size) override;
25 /// Hands the GPU buffer to deferred deletion, which keeps it alive until
26 /// every frame and upload batch that may reference it has completed.
27 void Cleanup() override;
28
29 /// Maps host-visible memory for direct CPU writes.
30 bool Map() override;
31 void Unmap() override;
32
33 void* GetData() override;
34
35 VkBuffer GetVkBuffer() const { return m_buffer; }
36
37 // VMA allocator lifecycle (owned by the renderer; created after the
38 // logical device, destroyed after all buffers are drained).
39 /// Creates the VMA allocator plus a staging pool whose blocks stay
40 /// resident for the allocator's lifetime.
41 static void InitAllocator(VkInstance instance,
42 VkPhysicalDevice physicalDevice, VkDevice device);
43 /// Destroys the staging pool and the allocator once every buffer is freed.
44 static void DestroyAllocator();
45 static VmaAllocator GetAllocator() { return s_allocator; }
46
47 /// Frees an upload batch that was recorded but never submitted, along
48 /// with its staging buffers. Only valid while the device is idle.
49 static void DiscardPendingCopies();
50
51 // Async flush: submit pending copies signaling the given semaphore.
52 // No CPU wait — the caller must wait on the semaphore before using data.
53 /// A staging buffer awaiting release once its async copy has completed.
55 VkBuffer buffer;
56 VmaAllocation memory;
57 VkDeviceSize allocSize = 0;
58 uint32_t memoryTypeIndex = 0;
59 };
60 /// Result of an async batched flush: the recorded command buffer plus staging resources to free later.
62 bool submitted = false;
63 std::vector<PendingStagingCleanup> stagingBuffers;
64 VkCommandBuffer commandBuffer = VK_NULL_HANDLE;
65 VkCommandPool commandPool = VK_NULL_HANDLE;
66 VkDevice device = VK_NULL_HANDLE;
67 };
68 static AsyncFlushResult FlushPendingCopiesAsync(VkSemaphore signalSemaphore);
69
70 // Enable/disable batching mode. When disabled, CopyBuffer uses
71 // immediate per-buffer submissions (safe during init/scene transitions).
72 static void SetBatchingEnabled(bool enabled) { s_batchingEnabled = enabled; }
73
74private:
75 /// Allocates a VMA-backed VkBuffer with the given usage/memory properties.
76 /// Constant buffers get CPU-cached memory since every bind reads them, and
77 /// staging buffers come from the resident staging pool.
78 void CreateBuffer(VkDeviceSize size, VkBufferUsageFlags usage,
79 VkMemoryPropertyFlags properties, VkBuffer& buffer,
80 VmaAllocation& memory, VkDeviceSize* outAllocSize = nullptr,
81 uint32_t* outMemTypeIdx = nullptr);
82
83 /// Records a GPU-side copy between buffers, batched or submitted immediately
84 /// per SetBatchingEnabled.
85 void CopyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
86
87 /// Finds a physical device memory type matching the filter and required
88 /// properties.
89 uint32_t FindMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties);
90
91 VkDevice m_device = VK_NULL_HANDLE;
92 VkPhysicalDevice m_physicalDevice = VK_NULL_HANDLE;
93 VkCommandPool m_commandPool = VK_NULL_HANDLE;
94 VkQueue m_graphicsQueue = VK_NULL_HANDLE;
95
96 VkBuffer m_buffer = VK_NULL_HANDLE;
97 VmaAllocation m_memory = VK_NULL_HANDLE;
98 VkDeviceSize m_allocSize = 0; // backing memory size (memReq)
99 VkDeviceSize m_bufferSize = 0; // logical VkBuffer size (bucketed)
100 VkBufferUsageFlags m_usage = 0;
101 uint32_t m_memoryTypeIndex = 0;
102
103 VkBuffer m_stagingBuffer = VK_NULL_HANDLE;
104 VmaAllocation m_stagingMemory = VK_NULL_HANDLE;
105
106 void* m_mappedData = nullptr;
107
108 // --- Batched transfer state ---
109 static bool s_batchingEnabled;
110 static bool s_batchActive;
111 static VkCommandBuffer s_batchCommandBuffer;
112 static VkDevice s_batchDevice;
113 static VkCommandPool s_batchCommandPool;
114 static VkQueue s_batchQueue;
115 static std::vector<PendingStagingCleanup> s_pendingCleanup;
116
117 /// Opens the shared batch command buffer if one isn't already recording.
118 static void EnsureBatchStarted(VkDevice device, VkCommandPool pool,
119 VkQueue queue);
120
121 // --- Deferred buffer deletion ---
122 /// A buffer queued for destruction once the GPU is guaranteed done referencing
123 /// it.
124 struct DeferredBufferDelete {
125 VkBuffer buffer;
126 VmaAllocation memory;
127 VkDevice device;
128 VkDeviceSize allocSize;
129 VkBufferUsageFlags usage;
130 uint32_t memoryTypeIndex;
131 uint64_t frameNumber;
132 VkDeviceSize bufferSize;
133 };
134 static std::vector<DeferredBufferDelete> s_deferredDeletions;
135 static uint64_t s_frameNumber;
136
137 // --- Buffer recycling pool ---
138 /// An idle buffer available for reuse by a future same-size, same-usage allocation.
139 struct PooledBuffer {
140 VkBuffer buffer;
141 VmaAllocation memory;
142 VkDevice device;
143 VkDeviceSize allocSize;
144 VkBufferUsageFlags usage;
145 uint32_t memoryTypeIndex;
146 VkDeviceSize bufferSize; // logical VkBuffer size (bucketed)
147 uint64_t insertFrame; // for oldest-first eviction
148 };
149 static std::vector<PooledBuffer> s_bufferPool;
150 static VkDeviceSize s_poolBytes; // total bytes currently in pool
151 // 64 MB budget — enough to recycle a few dozen column meshes without
152 // hoarding hundreds of MB of dead VRAM on a 6 GB card.
153 static constexpr VkDeviceSize MAX_POOL_BYTES = 64 * 1024 * 1024;
154 static constexpr size_t MAX_POOL_SIZE = 128; // hard cap on entry count too
155
156 /// Pulls a same-size, same-usage buffer out of the recycling pool if one is available.
157 bool TryRecycleBuffer(VkDeviceSize size, VkBufferUsageFlags usage,
158 VkMemoryPropertyFlags properties,
159 VkBuffer& buffer, VmaAllocation& memory,
160 VkDeviceSize* outAllocSize = nullptr);
161
162 // Evict entries from the pool until it fits within the byte budget.
163 static void EvictPoolOverBudget();
164
165public:
166 // Called by the renderer once per submitted frame, after its fence wait,
167 // to safely destroy buffers that are no longer referenced by the GPU.
168 static void ProcessDeferredDeletions(uint32_t maxFramesInFlight);
169 static void FlushAllDeferredDeletions();
170 static void AdvanceDeletionFrame() { s_frameNumber++; }
171
172 // VRAM tracking
173 static VkDeviceSize GetTotalAllocatedBytes();
174 static VkDeviceSize GetDeviceLocalHeapSize();
175 static VkDeviceSize GetDeviceLocalAllocatedBytes();
176 static void SetPhysicalDevice(VkPhysicalDevice device);
177 static void UntrackAllocation(VkDeviceSize size) {
178 s_totalAllocatedBytes -= size;
179 }
180 static void UntrackAllocation(VkDeviceSize size, uint32_t memTypeIdx) {
181 s_totalAllocatedBytes -= size;
182 if (memTypeIdx < s_memTypeCount)
183 s_perTypeBytes[memTypeIdx] -= size;
184 }
185 static void DumpPerFrameAllocStats();
186
187private:
188 static VmaAllocator s_allocator;
189 static VkDeviceSize s_totalAllocatedBytes;
190 static VkPhysicalDevice s_physicalDeviceGlobal;
191 static VkDeviceSize s_perTypeBytes[VK_MAX_MEMORY_TYPES];
192 static bool s_memTypeIsDeviceLocal[VK_MAX_MEMORY_TYPES];
193 static uint32_t s_memTypeCount;
194 /// Evicts pooled buffers backed by a specific memory type (used when that heap is under pressure).
195 static void EvictPoolForMemType(uint32_t memTypeIdx);
196};
197
198} // namespace RenderEngine
199} // namespace Sleak
200
201#endif // VULKANBUFFER_HPP_
Backend-agnostic GPU buffer: vertex, index, constant, or resource view target.
bool Map() override
Maps host-visible memory for direct CPU writes.
static void UntrackAllocation(VkDeviceSize size, uint32_t memTypeIdx)
static void UntrackAllocation(VkDeviceSize size)
bool Initialize(void *data) override
Allocates the buffer (recycling a pooled one if a match exists) and uploads initial data,...
VulkanBuffer(VkDevice device, VkPhysicalDevice physicalDevice, uint32_t size, BufferType type, VkCommandPool commandPool, VkQueue graphicsQueue)
static AsyncFlushResult FlushPendingCopiesAsync(VkSemaphore signalSemaphore)
static VmaAllocator GetAllocator()
static void SetBatchingEnabled(bool enabled)
Backend-facing rendering layer shared by the four graphics backends.
BufferType
GPU buffer usage kind, drives backend binding flags and layout.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10
Result of an async batched flush: the recorded command buffer plus staging resources to free later.
std::vector< PendingStagingCleanup > stagingBuffers
A staging buffer awaiting release once its async copy has completed.