SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
VulkanBuffer.cpp
Go to the documentation of this file.
1// VMA backs all buffer allocations (suballocation from large device blocks).
2#include <vulkan/vulkan.h>
3#define VMA_STATIC_VULKAN_FUNCTIONS 1
4#define VMA_DYNAMIC_VULKAN_FUNCTIONS 0
5#define VMA_IMPLEMENTATION
6#include <vma/vk_mem_alloc.h>
7
9#include <Core/Logger.hpp>
10#include <cstring>
11#include <stdexcept>
12
13namespace Sleak {
14namespace RenderEngine {
15
16VmaAllocator VulkanBuffer::s_allocator = VK_NULL_HANDLE;
17
18// Staging pool whose blocks stay resident, so upload bursts never pay for
19// fresh vkAllocateMemory calls.
20static VmaPool g_stagingPool = VK_NULL_HANDLE;
21#define STAGING_PROBE_BUFFER_BYTES (64 * 1024)
22static constexpr VkDeviceSize kStagingBlockSize = 64ull * 1024 * 1024;
23static constexpr size_t kStagingMinBlocks = 2;
24
25void VulkanBuffer::InitAllocator(VkInstance instance,
26 VkPhysicalDevice physicalDevice,
27 VkDevice device) {
28 if (s_allocator != VK_NULL_HANDLE) return;
29 VmaAllocatorCreateInfo aci{};
30 aci.instance = instance;
31 aci.physicalDevice = physicalDevice;
32 aci.device = device;
33 aci.vulkanApiVersion = VK_API_VERSION_1_1;
34 if (vmaCreateAllocator(&aci, &s_allocator) != VK_SUCCESS) {
35 SLEAK_ERROR("Failed to create VMA allocator!");
36 s_allocator = VK_NULL_HANDLE;
37 return;
38 }
39
40 // Staging pool
41 VkBufferCreateInfo stagingInfo{};
42 stagingInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
43 stagingInfo.size = STAGING_PROBE_BUFFER_BYTES;
44 stagingInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
45 stagingInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
46 VmaAllocationCreateInfo stagingAlloc{};
47 stagingAlloc.usage = VMA_MEMORY_USAGE_AUTO;
48 stagingAlloc.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT;
49 stagingAlloc.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
50 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
51 VmaPoolCreateInfo poolInfo{};
52 poolInfo.blockSize = kStagingBlockSize;
53 poolInfo.minBlockCount = kStagingMinBlocks;
54 if (vmaFindMemoryTypeIndexForBufferInfo(
55 s_allocator, &stagingInfo, &stagingAlloc,
56 &poolInfo.memoryTypeIndex) != VK_SUCCESS ||
57 vmaCreatePool(s_allocator, &poolInfo, &g_stagingPool) != VK_SUCCESS) {
58 SLEAK_WARN("VMA staging pool unavailable, using the default pools");
59 g_stagingPool = VK_NULL_HANDLE;
60 }
61}
62
64 if (s_allocator == VK_NULL_HANDLE) return;
65 if (g_stagingPool != VK_NULL_HANDLE) {
66 vmaDestroyPool(s_allocator, g_stagingPool);
67 g_stagingPool = VK_NULL_HANDLE;
68 }
69 vmaDestroyAllocator(s_allocator);
70 s_allocator = VK_NULL_HANDLE;
71}
72
73// Static batch state
74bool VulkanBuffer::s_batchingEnabled = false;
75bool VulkanBuffer::s_batchActive = false;
76VkCommandBuffer VulkanBuffer::s_batchCommandBuffer = VK_NULL_HANDLE;
77VkDevice VulkanBuffer::s_batchDevice = VK_NULL_HANDLE;
78VkCommandPool VulkanBuffer::s_batchCommandPool = VK_NULL_HANDLE;
79VkQueue VulkanBuffer::s_batchQueue = VK_NULL_HANDLE;
80std::vector<VulkanBuffer::PendingStagingCleanup> VulkanBuffer::s_pendingCleanup;
81
82// Static deferred deletion state
83std::vector<VulkanBuffer::DeferredBufferDelete> VulkanBuffer::s_deferredDeletions;
84uint64_t VulkanBuffer::s_frameNumber = 0;
85
86// OOM fallback state
87static uint32_t g_maxFramesInFlight = 3; // updated each frame by ProcessDeferredDeletions
88static uint64_t g_lastPoolWarnFrame = UINT64_MAX;
89static uint64_t g_lastReclaimWarnFrame = UINT64_MAX;
90
91// Recycling bucket granularity, per-frame pool-insertion cap, idle-trim rate.
92static constexpr VkDeviceSize kPoolBucket = 64 * 1024;
93static constexpr size_t kMaxDeletesPerFrame = 64;
94static constexpr size_t kIdleTrimPerFrame = 8;
95// Only drain the pool after this many consecutive streaming-idle frames, so
96// brief gaps while moving don't starve the pool of its reuse benefit.
97static constexpr uint32_t kIdleFramesBeforeTrim = 120;
98static uint32_t g_idleFrames = 0;
99
100// Recycling helpers
101/// Rounds a size up to the nearest pool bucket so similar-sized buffers can share slots.
102static VkDeviceSize BucketSize(VkDeviceSize s) {
103 return ((s + kPoolBucket - 1) / kPoolBucket) * kPoolBucket;
104}
105/// True for vertex/index usages, the only kinds worth pooling for reuse.
106static bool UsageIsRecyclable(VkBufferUsageFlags usage) {
107 return (usage & (VK_BUFFER_USAGE_VERTEX_BUFFER_BIT |
108 VK_BUFFER_USAGE_INDEX_BUFFER_BIT)) != 0;
109}
110/// True when a buffer is both device-local and a recyclable usage, the pool's eligibility gate.
111static bool IsRecyclable(VkBufferUsageFlags usage, VkMemoryPropertyFlags props) {
112 return (props & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) &&
113 UsageIsRecyclable(usage);
114}
115
116// Buffer recycling pool
117std::vector<VulkanBuffer::PooledBuffer> VulkanBuffer::s_bufferPool;
118VkDeviceSize VulkanBuffer::s_poolBytes = 0;
119
120// VRAM tracking
121VkDeviceSize VulkanBuffer::s_totalAllocatedBytes = 0;
122VkPhysicalDevice VulkanBuffer::s_physicalDeviceGlobal = VK_NULL_HANDLE;
123VkDeviceSize VulkanBuffer::s_perTypeBytes[VK_MAX_MEMORY_TYPES] = {};
124bool VulkanBuffer::s_memTypeIsDeviceLocal[VK_MAX_MEMORY_TYPES] = {};
125uint32_t VulkanBuffer::s_memTypeCount = 0;
126
127
128VulkanBuffer::VulkanBuffer(VkDevice device, VkPhysicalDevice physicalDevice,
129 uint32_t size, BufferType type,
130 VkCommandPool commandPool, VkQueue graphicsQueue)
131 : m_device(device),
132 m_physicalDevice(physicalDevice),
133 m_commandPool(commandPool),
134 m_graphicsQueue(graphicsQueue) {
135 Size = size;
136 Type = type;
137}
138
142
143bool VulkanBuffer::Initialize(void* data) {
144 if (Size == 0) return false;
145
146 switch (Type) {
147 case BufferType::Vertex: {
148 VkDeviceSize stagingAllocSize = 0;
149 uint32_t stagingMemTypeIdx = 0;
150 CreateBuffer(
151 Size,
152 VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
153 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
154 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
155 m_stagingBuffer, m_stagingMemory, &stagingAllocSize,
156 &stagingMemTypeIdx);
157 if (m_stagingBuffer == VK_NULL_HANDLE) return false;
158
159 // Copy data to staging buffer
160 if (data) {
161 void* mapped;
162 vmaMapMemory(s_allocator, m_stagingMemory, &mapped);
163 memcpy(mapped, data, Size);
164 vmaUnmapMemory(s_allocator, m_stagingMemory);
165 }
166
167 // Create device-local buffer
168 CreateBuffer(
169 Size,
170 VK_BUFFER_USAGE_TRANSFER_DST_BIT |
171 VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
172 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
173 m_buffer, m_memory);
174
175 if (m_buffer == VK_NULL_HANDLE) {
176 if (m_stagingBuffer != VK_NULL_HANDLE) {
177 vmaDestroyBuffer(s_allocator, m_stagingBuffer,
178 m_stagingMemory);
179 m_stagingBuffer = VK_NULL_HANDLE;
180 m_stagingMemory = VK_NULL_HANDLE;
181 s_totalAllocatedBytes -= stagingAllocSize;
182 if (stagingMemTypeIdx < s_memTypeCount)
183 s_perTypeBytes[stagingMemTypeIdx] -= stagingAllocSize;
184 }
185 return false;
186 }
187
188 if (data) {
189 CopyBuffer(m_stagingBuffer, m_buffer, Size);
190 }
191
192 if (s_batchActive) {
193 s_pendingCleanup.push_back({m_stagingBuffer, m_stagingMemory, stagingAllocSize, stagingMemTypeIdx});
194 } else {
195 vmaDestroyBuffer(s_allocator, m_stagingBuffer, m_stagingMemory);
196 s_totalAllocatedBytes -= stagingAllocSize;
197 if (stagingMemTypeIdx < s_memTypeCount)
198 s_perTypeBytes[stagingMemTypeIdx] -= stagingAllocSize;
199 }
200 m_stagingBuffer = VK_NULL_HANDLE;
201 m_stagingMemory = VK_NULL_HANDLE;
202 break;
203 }
204 case BufferType::Index: {
205 VkDeviceSize stagingAllocSize = 0;
206 uint32_t stagingMemTypeIdx = 0;
207 CreateBuffer(
208 Size,
209 VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
210 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
211 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
212 m_stagingBuffer, m_stagingMemory, &stagingAllocSize,
213 &stagingMemTypeIdx);
214 if (m_stagingBuffer == VK_NULL_HANDLE) return false;
215
216 if (data) {
217 void* mapped;
218 vmaMapMemory(s_allocator, m_stagingMemory, &mapped);
219 memcpy(mapped, data, Size);
220 vmaUnmapMemory(s_allocator, m_stagingMemory);
221 }
222
223 CreateBuffer(
224 Size,
225 VK_BUFFER_USAGE_TRANSFER_DST_BIT |
226 VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
227 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
228 m_buffer, m_memory);
229
230 if (m_buffer == VK_NULL_HANDLE) {
231 if (m_stagingBuffer != VK_NULL_HANDLE) {
232 vmaDestroyBuffer(s_allocator, m_stagingBuffer,
233 m_stagingMemory);
234 m_stagingBuffer = VK_NULL_HANDLE;
235 m_stagingMemory = VK_NULL_HANDLE;
236 s_totalAllocatedBytes -= stagingAllocSize;
237 if (stagingMemTypeIdx < s_memTypeCount)
238 s_perTypeBytes[stagingMemTypeIdx] -= stagingAllocSize;
239 }
240 return false;
241 }
242
243 if (data) {
244 CopyBuffer(m_stagingBuffer, m_buffer, Size);
245 }
246
247 if (s_batchActive) {
248 s_pendingCleanup.push_back({m_stagingBuffer, m_stagingMemory, stagingAllocSize, stagingMemTypeIdx});
249 } else {
250 vmaDestroyBuffer(s_allocator, m_stagingBuffer, m_stagingMemory);
251 s_totalAllocatedBytes -= stagingAllocSize;
252 if (stagingMemTypeIdx < s_memTypeCount)
253 s_perTypeBytes[stagingMemTypeIdx] -= stagingAllocSize;
254 }
255 m_stagingBuffer = VK_NULL_HANDLE;
256 m_stagingMemory = VK_NULL_HANDLE;
257 break;
258 }
260 // Constant buffers are host-visible for frequent updates
261 CreateBuffer(
262 Size,
263 VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
264 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
265 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
266 m_buffer, m_memory);
267
268 if (m_buffer == VK_NULL_HANDLE) return false;
269
270 // Persistently map
271 vmaMapMemory(s_allocator, m_memory, &m_mappedData);
272
273 if (data) {
274 memcpy(m_mappedData, data, Size);
275 }
276 break;
277 }
278 default: {
279 // Generic buffer
280 CreateBuffer(
281 Size,
282 VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
283 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
284 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
285 m_buffer, m_memory);
286
287 if (data) {
288 void* mapped;
289 vmaMapMemory(s_allocator, m_memory, &mapped);
290 memcpy(mapped, data, Size);
291 vmaUnmapMemory(s_allocator, m_memory);
292 }
293 break;
294 }
295 }
296
297 bIsInitialized = true;
298 return true;
299}
300
302 // For constant buffers with persistent mapping, nothing extra needed
303 // Data is already written to mapped memory
304}
305
306void VulkanBuffer::Update(void* data, size_t size) {
307 if (!data || size == 0) return;
308
309 if (Type == BufferType::Constant && m_mappedData) {
310 // Constant buffer is persistently mapped
311 memcpy(m_mappedData, data, size);
312 } else if (Type == BufferType::Vertex || Type == BufferType::Index) {
313 VkBuffer staging;
314 VmaAllocation stagingMem;
315 VkDeviceSize stagingAllocSize = 0;
316 uint32_t stagingMemTypeIdx = 0;
317 CreateBuffer(
318 size,
319 VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
320 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
321 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
322 staging, stagingMem, &stagingAllocSize, &stagingMemTypeIdx);
323
324 void* mapped;
325 vmaMapMemory(s_allocator, stagingMem, &mapped);
326 memcpy(mapped, data, size);
327 vmaUnmapMemory(s_allocator, stagingMem);
328
329 CopyBuffer(staging, m_buffer, size);
330
331 if (s_batchActive) {
332 s_pendingCleanup.push_back({staging, stagingMem, stagingAllocSize, stagingMemTypeIdx});
333 } else {
334 vmaDestroyBuffer(s_allocator, staging, stagingMem);
335 s_totalAllocatedBytes -= stagingAllocSize;
336 if (stagingMemTypeIdx < s_memTypeCount)
337 s_perTypeBytes[stagingMemTypeIdx] -= stagingAllocSize;
338 }
339 }
340}
341
343 if (m_device == VK_NULL_HANDLE) return;
344
345 if (Type == BufferType::Constant && m_mappedData) {
346 vmaUnmapMemory(s_allocator, m_memory);
347 m_mappedData = nullptr;
348 }
349
350 // Staging buffers can be destroyed immediately (not GPU-visible after copy)
351 if (m_stagingBuffer != VK_NULL_HANDLE) {
352 vmaDestroyBuffer(s_allocator, m_stagingBuffer, m_stagingMemory);
353 m_stagingBuffer = VK_NULL_HANDLE;
354 m_stagingMemory = VK_NULL_HANDLE;
355 }
356 // Defer GPU buffer destruction — may still be referenced by in-flight
357 // command buffers. Will be recycled or cleaned up after fence wait.
358 if (m_buffer != VK_NULL_HANDLE) {
359 s_deferredDeletions.push_back({m_buffer, m_memory, m_device,
360 m_allocSize, m_usage, m_memoryTypeIndex,
361 s_frameNumber, m_bufferSize});
362 m_buffer = VK_NULL_HANDLE;
363 m_memory = VK_NULL_HANDLE;
364 m_allocSize = 0;
365 m_bufferSize = 0;
366 }
367
368 bIsInitialized = false;
369}
370
372 if (bIsMapped) return true;
373 if (Type == BufferType::Constant && m_mappedData) {
374 Data = m_mappedData;
375 bIsMapped = true;
376 return true;
377 }
378 VkResult result = vmaMapMemory(s_allocator, m_memory, &Data);
379 if (result != VK_SUCCESS) return false;
380 bIsMapped = true;
381 return true;
382}
383
385 if (!bIsMapped) return;
386 // Don't unmap persistent constant buffer mappings
387 if (Type == BufferType::Constant && m_mappedData) {
388 bIsMapped = false;
389 return;
390 }
391 vmaUnmapMemory(s_allocator, m_memory);
392 Data = nullptr;
393 bIsMapped = false;
394}
395
397 return m_mappedData ? m_mappedData : Data;
398}
399
400void VulkanBuffer::CreateBuffer(VkDeviceSize size,
401 VkBufferUsageFlags usage,
402 VkMemoryPropertyFlags properties,
403 VkBuffer& buffer,
404 VmaAllocation& memory,
405 VkDeviceSize* outAllocSize,
406 uint32_t* outMemTypeIdx) {
407 // Recyclable device-local vertex/index buffers are bucketed so similar
408 // meshes can reuse a freed allocation instead of hitting vkAllocateMemory.
409 const bool recyclable = IsRecyclable(usage, properties);
410 const VkDeviceSize createSize = recyclable ? BucketSize(size) : size;
411
412 if (recyclable &&
413 TryRecycleBuffer(createSize, usage, properties, buffer, memory,
414 outAllocSize)) {
415 if (outMemTypeIdx && &buffer == &m_buffer) *outMemTypeIdx = m_memoryTypeIndex;
416 return;
417 }
418
419 VkBufferCreateInfo bufferInfo{};
420 bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
421 bufferInfo.size = createSize;
422 bufferInfo.usage = usage;
423 bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
424
425 VmaAllocationCreateInfo allocCI{};
426 allocCI.usage = VMA_MEMORY_USAGE_AUTO;
427 allocCI.requiredFlags = properties; // preserve exact memory-property semantics
428 if (properties & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
429 // Constants are read back
430 allocCI.flags |=
432 ? VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT
433 : VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT;
434 }
435 if (usage == VK_BUFFER_USAGE_TRANSFER_SRC_BIT) allocCI.pool = g_stagingPool;
436
437 VmaAllocationInfo info{};
438 VkResult r = vmaCreateBuffer(s_allocator, &bufferInfo, &allocCI,
439 &buffer, &memory, &info);
440
441 if (r != VK_SUCCESS && !s_bufferPool.empty()) {
442 // OOM step 1: evict whole recycling pool (pool buffers are not GPU-referenced)
443 if (g_lastPoolWarnFrame != s_frameNumber) {
444 SLEAK_WARN("Vulkan alloc failed, evicting {} pooled buffers ({:.1f} MB)",
445 s_bufferPool.size(),
446 static_cast<double>(s_poolBytes) / (1024.0 * 1024.0));
447 g_lastPoolWarnFrame = s_frameNumber;
448 }
449 for (auto& e : s_bufferPool) {
450 vmaDestroyBuffer(s_allocator, e.buffer, e.memory);
451 s_totalAllocatedBytes -= e.allocSize;
452 if (e.memoryTypeIndex < s_memTypeCount)
453 s_perTypeBytes[e.memoryTypeIndex] -= e.allocSize;
454 }
455 s_bufferPool.clear();
456 s_poolBytes = 0;
457 r = vmaCreateBuffer(s_allocator, &bufferInfo, &allocCI,
458 &buffer, &memory, &info);
459 }
460
461 if (r != VK_SUCCESS) {
462 // OOM step 2: reclaim fence-safe deferred deletions (no device-wide idle)
463 if (g_lastReclaimWarnFrame != s_frameNumber) {
464 SLEAK_WARN("Vulkan alloc still failing, reclaiming fence-safe deferred deletions");
465 g_lastReclaimWarnFrame = s_frameNumber;
466 }
468 r = vmaCreateBuffer(s_allocator, &bufferInfo, &allocCI,
469 &buffer, &memory, &info);
470 }
471
472 if (r != VK_SUCCESS) {
473 SLEAK_ERROR("Failed to allocate Vulkan buffer memory!");
474 buffer = VK_NULL_HANDLE;
475 memory = VK_NULL_HANDLE;
476 return;
477 }
478
479 s_totalAllocatedBytes += info.size;
480 if (info.memoryType < s_memTypeCount)
481 s_perTypeBytes[info.memoryType] += info.size;
482
483 if (outAllocSize) *outAllocSize = info.size;
484 if (outMemTypeIdx) *outMemTypeIdx = info.memoryType;
485
486 if (&buffer == &m_buffer) {
487 m_allocSize = info.size;
488 m_usage = usage;
489 m_memoryTypeIndex = info.memoryType;
490 m_bufferSize = createSize;
491 }
492}
493
494void VulkanBuffer::CopyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer,
495 VkDeviceSize size) {
496 // If a batch is active, record into the shared command buffer
497 EnsureBatchStarted(m_device, m_commandPool, m_graphicsQueue);
498 if (s_batchActive) {
499 VkBufferCopy copyRegion{};
500 copyRegion.size = size;
501 vkCmdCopyBuffer(s_batchCommandBuffer, srcBuffer, dstBuffer, 1,
502 &copyRegion);
503 return;
504 }
505
506 // Fallback: immediate copy (used when no batch is active, e.g. texture uploads)
507 VkCommandBufferAllocateInfo allocInfo{};
508 allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
509 allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
510 allocInfo.commandPool = m_commandPool;
511 allocInfo.commandBufferCount = 1;
512
513 VkCommandBuffer commandBuffer;
514 vkAllocateCommandBuffers(m_device, &allocInfo, &commandBuffer);
515
516 VkCommandBufferBeginInfo beginInfo{};
517 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
518 beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
519
520 vkBeginCommandBuffer(commandBuffer, &beginInfo);
521
522 VkBufferCopy copyRegion{};
523 copyRegion.size = size;
524 vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyRegion);
525
526 vkEndCommandBuffer(commandBuffer);
527
528 VkFenceCreateInfo fenceInfo{};
529 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
530 VkFence copyFence;
531 vkCreateFence(m_device, &fenceInfo, nullptr, &copyFence);
532
533 VkSubmitInfo submitInfo{};
534 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
535 submitInfo.commandBufferCount = 1;
536 submitInfo.pCommandBuffers = &commandBuffer;
537
538 vkQueueSubmit(m_graphicsQueue, 1, &submitInfo, copyFence);
539 vkWaitForFences(m_device, 1, &copyFence, VK_TRUE, UINT64_MAX);
540
541 vkDestroyFence(m_device, copyFence, nullptr);
542 vkFreeCommandBuffers(m_device, m_commandPool, 1, &commandBuffer);
543}
544
545void VulkanBuffer::EnsureBatchStarted(VkDevice device, VkCommandPool pool,
546 VkQueue queue) {
547 if (s_batchActive || !s_batchingEnabled) return;
548
549 s_batchDevice = device;
550 s_batchCommandPool = pool;
551 s_batchQueue = queue;
552
553 VkCommandBufferAllocateInfo allocInfo{};
554 allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
555 allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
556 allocInfo.commandPool = pool;
557 allocInfo.commandBufferCount = 1;
558
559 if (vkAllocateCommandBuffers(device, &allocInfo, &s_batchCommandBuffer) != VK_SUCCESS) {
560 SLEAK_ERROR("Failed to allocate batch transfer command buffer!");
561 return;
562 }
563
564 VkCommandBufferBeginInfo beginInfo{};
565 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
566 beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
567
568 if (vkBeginCommandBuffer(s_batchCommandBuffer, &beginInfo) != VK_SUCCESS) {
569 SLEAK_ERROR("Failed to begin batch transfer command buffer!");
570 vkFreeCommandBuffers(device, pool, 1, &s_batchCommandBuffer);
571 s_batchCommandBuffer = VK_NULL_HANDLE;
572 return;
573 }
574
575 s_batchActive = true;
576}
577
579 if (s_batchActive) {
580 vkFreeCommandBuffers(s_batchDevice, s_batchCommandPool, 1,
581 &s_batchCommandBuffer);
582 s_batchCommandBuffer = VK_NULL_HANDLE;
583 s_batchActive = false;
584 }
585
586 for (auto& pending : s_pendingCleanup) {
587 vmaDestroyBuffer(s_allocator, pending.buffer, pending.memory);
588 s_totalAllocatedBytes -= pending.allocSize;
589 if (pending.memoryTypeIndex < s_memTypeCount)
590 s_perTypeBytes[pending.memoryTypeIndex] -= pending.allocSize;
591 }
592 s_pendingCleanup.clear();
593}
594
596VulkanBuffer::FlushPendingCopiesAsync(VkSemaphore signalSemaphore) {
597 AsyncFlushResult result;
598
599 if (!s_batchActive) return result;
600
601 vkEndCommandBuffer(s_batchCommandBuffer);
602
603 // Submit with semaphore signal — NO fence wait (zero CPU blocking)
604 VkSubmitInfo submitInfo{};
605 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
606 submitInfo.commandBufferCount = 1;
607 submitInfo.pCommandBuffers = &s_batchCommandBuffer;
608 submitInfo.signalSemaphoreCount = 1;
609 submitInfo.pSignalSemaphores = &signalSemaphore;
610
611 vkQueueSubmit(s_batchQueue, 1, &submitInfo, VK_NULL_HANDLE);
612
613 // Return everything the caller needs for per-frame deferred cleanup
614 result.submitted = true;
615 result.stagingBuffers = std::move(s_pendingCleanup);
616 result.commandBuffer = s_batchCommandBuffer;
617 result.commandPool = s_batchCommandPool;
618 result.device = s_batchDevice;
619
620 s_pendingCleanup.clear();
621 s_batchCommandBuffer = VK_NULL_HANDLE;
622 s_batchActive = false;
623
624 return result;
625}
626
627uint32_t VulkanBuffer::FindMemoryType(uint32_t typeFilter,
628 VkMemoryPropertyFlags properties) {
629 VkPhysicalDeviceMemoryProperties memProperties;
630 vkGetPhysicalDeviceMemoryProperties(m_physicalDevice, &memProperties);
631
632 for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) {
633 if ((typeFilter & (1 << i)) &&
634 (memProperties.memoryTypes[i].propertyFlags & properties) ==
635 properties) {
636 return i;
637 }
638 }
639
640 SLEAK_ERROR("Failed to find suitable memory type!");
641 return 0;
642}
643
644void VulkanBuffer::ProcessDeferredDeletions(uint32_t maxFramesInFlight) {
645 g_maxFramesInFlight = maxFramesInFlight;
646
647 // Reclaim EVERY buffer whose fence chain confirms the GPU is done (aged
648 // past frames-in-flight). Destroys are uncapped: vmaDestroyBuffer only
649 // returns a suballocation to its VMA block, so even large unload bursts
650 // are cheap — and the deferred queue never backlogs (a backlog would keep
651 // freed buffers allocated and grow VRAM monotonically while moving). Only
652 // pool INSERTIONS are throttled per frame; excess eligible buffers are
653 // simply destroyed this frame instead of pooled.
654 size_t pooled = 0;
655 for (size_t i = 0; i < s_deferredDeletions.size(); ) {
656 auto& entry = s_deferredDeletions[i];
657 if (s_frameNumber - entry.frameNumber >= maxFramesInFlight) {
658 const bool deviceLocal =
659 entry.memoryTypeIndex < s_memTypeCount &&
660 s_memTypeIsDeviceLocal[entry.memoryTypeIndex];
661 const bool poolable =
662 deviceLocal && UsageIsRecyclable(entry.usage) &&
663 entry.bufferSize > 0 &&
664 pooled < kMaxDeletesPerFrame &&
665 s_bufferPool.size() < MAX_POOL_SIZE &&
666 s_poolBytes + entry.allocSize <= MAX_POOL_BYTES;
667
668 if (poolable) {
669 // Keep allocated (still counted in s_totalAllocatedBytes).
670 s_bufferPool.push_back({entry.buffer, entry.memory, entry.device,
671 entry.allocSize, entry.usage,
672 entry.memoryTypeIndex, entry.bufferSize,
673 s_frameNumber});
674 s_poolBytes += entry.allocSize;
675 ++pooled;
676 } else {
677 vmaDestroyBuffer(s_allocator, entry.buffer, entry.memory);
678 s_totalAllocatedBytes -= entry.allocSize;
679 if (entry.memoryTypeIndex < s_memTypeCount)
680 s_perTypeBytes[entry.memoryTypeIndex] -= entry.allocSize;
681 }
682 entry = std::move(s_deferredDeletions.back());
683 s_deferredDeletions.pop_back();
684 } else {
685 ++i;
686 }
687 }
688
689 EvictPoolOverBudget();
690
691 // Idle drain: only after SUSTAINED inactivity (empty queue for many
692 // consecutive frames). Brief gaps while streaming keep the pool intact so
693 // it provides reuse during movement; once the player truly stops, the pool
694 // gently drains and idle VRAM returns toward baseline. Pool entries are
695 // already GPU-safe (aged past frames-in-flight before being pooled).
696 if (s_deferredDeletions.empty()) {
698 ++g_idleFrames;
699 } else {
700 for (size_t n = 0; n < kIdleTrimPerFrame && !s_bufferPool.empty(); ++n) {
701 auto& e = s_bufferPool.back();
702 vmaDestroyBuffer(s_allocator, e.buffer, e.memory);
703 s_totalAllocatedBytes -= e.allocSize;
704 s_poolBytes -= e.allocSize;
705 if (e.memoryTypeIndex < s_memTypeCount)
706 s_perTypeBytes[e.memoryTypeIndex] -= e.allocSize;
707 s_bufferPool.pop_back();
708 }
709 }
710 } else {
711 g_idleFrames = 0;
712 }
713
714#ifdef DEBUG
715 // Rate-limited VMA VRAM observability: logical live vs driver block bytes.
716 if (s_allocator && (s_frameNumber % 600) == 0) {
717 VmaTotalStatistics vs{};
718 vmaCalculateStatistics(s_allocator, &vs);
719 SLEAK_LOG(
720 "VMA: live {} MB / blocks {} MB | pool {} entries {} MB | deferred {}",
721 vs.total.statistics.allocationBytes / (1024 * 1024),
722 vs.total.statistics.blockBytes / (1024 * 1024),
723 s_bufferPool.size(), s_poolBytes / (1024 * 1024),
724 s_deferredDeletions.size());
725 }
726#endif
727}
728
729bool VulkanBuffer::TryRecycleBuffer(VkDeviceSize size,
730 VkBufferUsageFlags usage,
731 VkMemoryPropertyFlags properties,
732 VkBuffer& buffer,
733 VmaAllocation& memory,
734 VkDeviceSize* outAllocSize) {
735 if (!IsRecyclable(usage, properties) || s_bufferPool.empty()) return false;
736
737 // Best-fit: smallest pooled buffer with exact usage that is big enough.
738 size_t best = s_bufferPool.size();
739 VkDeviceSize bestSize = 0;
740 for (size_t i = 0; i < s_bufferPool.size(); ++i) {
741 const auto& e = s_bufferPool[i];
742 if (e.usage == usage && e.device == m_device && e.bufferSize >= size) {
743 if (best == s_bufferPool.size() || e.bufferSize < bestSize) {
744 best = i;
745 bestSize = e.bufferSize;
746 }
747 }
748 }
749 if (best == s_bufferPool.size()) return false;
750
751 PooledBuffer e = s_bufferPool[best];
752 s_bufferPool[best] = s_bufferPool.back();
753 s_bufferPool.pop_back();
754 s_poolBytes -= e.allocSize;
755
756 // Buffer memory binding is permanent — reuse as-is, do NOT rebind.
757 buffer = e.buffer;
758 memory = e.memory;
759 if (outAllocSize) *outAllocSize = e.allocSize;
760
761 if (&buffer == &m_buffer) {
762 m_allocSize = e.allocSize;
763 m_usage = e.usage;
764 m_memoryTypeIndex = e.memoryTypeIndex;
765 m_bufferSize = e.bufferSize;
766 }
767 return true;
768}
769
770void VulkanBuffer::EvictPoolOverBudget() {
771 // Evict oldest entries first until under both byte and count budget.
772 while ((s_poolBytes > MAX_POOL_BYTES || s_bufferPool.size() > MAX_POOL_SIZE) &&
773 !s_bufferPool.empty()) {
774 size_t oldestIdx = 0;
775 uint64_t oldestFrame = s_bufferPool[0].insertFrame;
776 for (size_t i = 1; i < s_bufferPool.size(); ++i) {
777 if (s_bufferPool[i].insertFrame < oldestFrame) {
778 oldestFrame = s_bufferPool[i].insertFrame;
779 oldestIdx = i;
780 }
781 }
782 auto& e = s_bufferPool[oldestIdx];
783 vmaDestroyBuffer(s_allocator, e.buffer, e.memory);
784 s_totalAllocatedBytes -= e.allocSize;
785 s_poolBytes -= e.allocSize;
786 if (e.memoryTypeIndex < s_memTypeCount)
787 s_perTypeBytes[e.memoryTypeIndex] -= e.allocSize;
788 s_bufferPool[oldestIdx] = s_bufferPool.back();
789 s_bufferPool.pop_back();
790 }
791}
792
794 for (auto& entry : s_deferredDeletions) {
795 vmaDestroyBuffer(s_allocator, entry.buffer, entry.memory);
796 s_totalAllocatedBytes -= entry.allocSize;
797 if (entry.memoryTypeIndex < s_memTypeCount)
798 s_perTypeBytes[entry.memoryTypeIndex] -= entry.allocSize;
799 }
800 s_deferredDeletions.clear();
801
802 // Also drain the recycling pool
803 for (auto& entry : s_bufferPool) {
804 vmaDestroyBuffer(s_allocator, entry.buffer, entry.memory);
805 s_totalAllocatedBytes -= entry.allocSize;
806 if (entry.memoryTypeIndex < s_memTypeCount)
807 s_perTypeBytes[entry.memoryTypeIndex] -= entry.allocSize;
808 }
809 s_bufferPool.clear();
810 s_poolBytes = 0;
811}
812
814 return s_totalAllocatedBytes;
815}
816
818
820 if (s_physicalDeviceGlobal == VK_NULL_HANDLE) return 0;
821
822 VkPhysicalDeviceMemoryProperties memProps;
823 vkGetPhysicalDeviceMemoryProperties(s_physicalDeviceGlobal, &memProps);
824
825 VkDeviceSize totalDeviceLocal = 0;
826 for (uint32_t i = 0; i < memProps.memoryHeapCount; i++) {
827 if (memProps.memoryHeaps[i].flags &
828 VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) {
829 totalDeviceLocal += memProps.memoryHeaps[i].size;
830 }
831 }
832 return totalDeviceLocal;
833}
834
835void VulkanBuffer::SetPhysicalDevice(VkPhysicalDevice device) {
836 s_physicalDeviceGlobal = device;
837 if (device == VK_NULL_HANDLE) return;
838 VkPhysicalDeviceMemoryProperties memProps;
839 vkGetPhysicalDeviceMemoryProperties(device, &memProps);
840 s_memTypeCount = memProps.memoryTypeCount;
841 for (uint32_t i = 0; i < memProps.memoryTypeCount; ++i) {
842 uint32_t heapIdx = memProps.memoryTypes[i].heapIndex;
843 s_memTypeIsDeviceLocal[i] = (memProps.memoryHeaps[heapIdx].flags &
844 VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) != 0;
845 s_perTypeBytes[i] = 0;
846 }
847}
848
850 VkDeviceSize total = 0;
851 for (uint32_t i = 0; i < s_memTypeCount; ++i) {
852 if (s_memTypeIsDeviceLocal[i]) total += s_perTypeBytes[i];
853 }
854 return total;
855}
856
857void VulkanBuffer::EvictPoolForMemType(uint32_t memTypeIdx) {
858 for (size_t i = 0; i < s_bufferPool.size(); ) {
859 auto& e = s_bufferPool[i];
860 if (e.memoryTypeIndex == memTypeIdx) {
861 vmaDestroyBuffer(s_allocator, e.buffer, e.memory);
862 s_totalAllocatedBytes -= e.allocSize;
863 s_poolBytes -= e.allocSize;
864 if (memTypeIdx < s_memTypeCount)
865 s_perTypeBytes[memTypeIdx] -= e.allocSize;
866 s_bufferPool[i] = s_bufferPool.back();
867 s_bufferPool.pop_back();
868 } else {
869 ++i;
870 }
871 }
872}
873
874} // namespace RenderEngine
875} // namespace Sleak
#define SLEAK_ERROR(...)
Definition Logger.hpp:22
#define SLEAK_WARN(...)
Definition Logger.hpp:21
#define SLEAK_LOG(...)
Definition Logger.hpp:19
#define STAGING_PROBE_BUFFER_BYTES
static void SetPhysicalDevice(VkPhysicalDevice device)
static void ProcessDeferredDeletions(uint32_t maxFramesInFlight)
bool Map() override
Maps host-visible memory for direct CPU writes.
static VkDeviceSize GetTotalAllocatedBytes()
static void DestroyAllocator()
Destroys the staging pool and the allocator once every buffer is freed.
bool Initialize(void *data) override
Allocates the buffer (recycling a pooled one if a match exists) and uploads initial data,...
static void InitAllocator(VkInstance instance, VkPhysicalDevice physicalDevice, VkDevice device)
VulkanBuffer(VkDevice device, VkPhysicalDevice physicalDevice, uint32_t size, BufferType type, VkCommandPool commandPool, VkQueue graphicsQueue)
static VkDeviceSize GetDeviceLocalAllocatedBytes()
static AsyncFlushResult FlushPendingCopiesAsync(VkSemaphore signalSemaphore)
static VkDeviceSize GetDeviceLocalHeapSize()
static uint32_t g_maxFramesInFlight
static constexpr size_t kIdleTrimPerFrame
static uint64_t g_lastReclaimWarnFrame
static constexpr uint32_t kIdleFramesBeforeTrim
BufferType
GPU buffer usage kind, drives backend binding flags and layout.
static constexpr size_t kMaxDeletesPerFrame
static bool UsageIsRecyclable(VkBufferUsageFlags usage)
True for vertex/index usages, the only kinds worth pooling for reuse.
static constexpr VkDeviceSize kPoolBucket
static constexpr size_t kStagingMinBlocks
static uint32_t g_idleFrames
static uint64_t g_lastPoolWarnFrame
static constexpr VkDeviceSize kStagingBlockSize
static VkDeviceSize BucketSize(VkDeviceSize s)
Rounds a size up to the nearest pool bucket so similar-sized buffers can share slots.
static bool IsRecyclable(VkBufferUsageFlags usage, VkMemoryPropertyFlags props)
True when a buffer is both device-local and a recyclable usage, the pool's eligibility gate.
static VmaPool g_stagingPool
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