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>
14namespace RenderEngine {
16VmaAllocator VulkanBuffer::s_allocator = VK_NULL_HANDLE;
21#define STAGING_PROBE_BUFFER_BYTES (64 * 1024)
26 VkPhysicalDevice physicalDevice,
28 if (s_allocator != VK_NULL_HANDLE)
return;
29 VmaAllocatorCreateInfo aci{};
30 aci.instance = instance;
31 aci.physicalDevice = physicalDevice;
33 aci.vulkanApiVersion = VK_API_VERSION_1_1;
34 if (vmaCreateAllocator(&aci, &s_allocator) != VK_SUCCESS) {
36 s_allocator = VK_NULL_HANDLE;
41 VkBufferCreateInfo stagingInfo{};
42 stagingInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
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{};
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");
64 if (s_allocator == VK_NULL_HANDLE)
return;
69 vmaDestroyAllocator(s_allocator);
70 s_allocator = VK_NULL_HANDLE;
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;
83std::vector<VulkanBuffer::DeferredBufferDelete> VulkanBuffer::s_deferredDeletions;
84uint64_t VulkanBuffer::s_frameNumber = 0;
107 return (usage & (VK_BUFFER_USAGE_VERTEX_BUFFER_BIT |
108 VK_BUFFER_USAGE_INDEX_BUFFER_BIT)) != 0;
111static bool IsRecyclable(VkBufferUsageFlags usage, VkMemoryPropertyFlags props) {
112 return (props & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) &&
117std::vector<VulkanBuffer::PooledBuffer> VulkanBuffer::s_bufferPool;
118VkDeviceSize VulkanBuffer::s_poolBytes = 0;
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;
130 VkCommandPool commandPool, VkQueue graphicsQueue)
132 m_physicalDevice(physicalDevice),
133 m_commandPool(commandPool),
134 m_graphicsQueue(graphicsQueue) {
144 if (
Size == 0)
return false;
148 VkDeviceSize stagingAllocSize = 0;
149 uint32_t stagingMemTypeIdx = 0;
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,
157 if (m_stagingBuffer == VK_NULL_HANDLE)
return false;
162 vmaMapMemory(s_allocator, m_stagingMemory, &mapped);
163 memcpy(mapped, data,
Size);
164 vmaUnmapMemory(s_allocator, m_stagingMemory);
170 VK_BUFFER_USAGE_TRANSFER_DST_BIT |
171 VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
172 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
175 if (m_buffer == VK_NULL_HANDLE) {
176 if (m_stagingBuffer != VK_NULL_HANDLE) {
177 vmaDestroyBuffer(s_allocator, m_stagingBuffer,
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;
189 CopyBuffer(m_stagingBuffer, m_buffer,
Size);
193 s_pendingCleanup.push_back({m_stagingBuffer, m_stagingMemory, stagingAllocSize, stagingMemTypeIdx});
195 vmaDestroyBuffer(s_allocator, m_stagingBuffer, m_stagingMemory);
196 s_totalAllocatedBytes -= stagingAllocSize;
197 if (stagingMemTypeIdx < s_memTypeCount)
198 s_perTypeBytes[stagingMemTypeIdx] -= stagingAllocSize;
200 m_stagingBuffer = VK_NULL_HANDLE;
201 m_stagingMemory = VK_NULL_HANDLE;
205 VkDeviceSize stagingAllocSize = 0;
206 uint32_t stagingMemTypeIdx = 0;
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,
214 if (m_stagingBuffer == VK_NULL_HANDLE)
return false;
218 vmaMapMemory(s_allocator, m_stagingMemory, &mapped);
219 memcpy(mapped, data,
Size);
220 vmaUnmapMemory(s_allocator, m_stagingMemory);
225 VK_BUFFER_USAGE_TRANSFER_DST_BIT |
226 VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
227 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
230 if (m_buffer == VK_NULL_HANDLE) {
231 if (m_stagingBuffer != VK_NULL_HANDLE) {
232 vmaDestroyBuffer(s_allocator, m_stagingBuffer,
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;
244 CopyBuffer(m_stagingBuffer, m_buffer,
Size);
248 s_pendingCleanup.push_back({m_stagingBuffer, m_stagingMemory, stagingAllocSize, stagingMemTypeIdx});
250 vmaDestroyBuffer(s_allocator, m_stagingBuffer, m_stagingMemory);
251 s_totalAllocatedBytes -= stagingAllocSize;
252 if (stagingMemTypeIdx < s_memTypeCount)
253 s_perTypeBytes[stagingMemTypeIdx] -= stagingAllocSize;
255 m_stagingBuffer = VK_NULL_HANDLE;
256 m_stagingMemory = VK_NULL_HANDLE;
263 VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
264 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
265 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
268 if (m_buffer == VK_NULL_HANDLE)
return false;
271 vmaMapMemory(s_allocator, m_memory, &m_mappedData);
274 memcpy(m_mappedData, data,
Size);
282 VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
283 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
284 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
289 vmaMapMemory(s_allocator, m_memory, &mapped);
290 memcpy(mapped, data,
Size);
291 vmaUnmapMemory(s_allocator, m_memory);
307 if (!data || size == 0)
return;
311 memcpy(m_mappedData, data, size);
314 VmaAllocation stagingMem;
315 VkDeviceSize stagingAllocSize = 0;
316 uint32_t stagingMemTypeIdx = 0;
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);
325 vmaMapMemory(s_allocator, stagingMem, &mapped);
326 memcpy(mapped, data, size);
327 vmaUnmapMemory(s_allocator, stagingMem);
329 CopyBuffer(staging, m_buffer, size);
332 s_pendingCleanup.push_back({staging, stagingMem, stagingAllocSize, stagingMemTypeIdx});
334 vmaDestroyBuffer(s_allocator, staging, stagingMem);
335 s_totalAllocatedBytes -= stagingAllocSize;
336 if (stagingMemTypeIdx < s_memTypeCount)
337 s_perTypeBytes[stagingMemTypeIdx] -= stagingAllocSize;
343 if (m_device == VK_NULL_HANDLE)
return;
346 vmaUnmapMemory(s_allocator, m_memory);
347 m_mappedData =
nullptr;
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;
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;
378 VkResult result = vmaMapMemory(s_allocator, m_memory, &
Data);
379 if (result != VK_SUCCESS)
return false;
391 vmaUnmapMemory(s_allocator, m_memory);
397 return m_mappedData ? m_mappedData :
Data;
400void VulkanBuffer::CreateBuffer(VkDeviceSize size,
401 VkBufferUsageFlags usage,
402 VkMemoryPropertyFlags properties,
404 VmaAllocation& memory,
405 VkDeviceSize* outAllocSize,
406 uint32_t* outMemTypeIdx) {
409 const bool recyclable =
IsRecyclable(usage, properties);
410 const VkDeviceSize createSize = recyclable ?
BucketSize(size) : size;
413 TryRecycleBuffer(createSize, usage, properties, buffer, memory,
415 if (outMemTypeIdx && &buffer == &m_buffer) *outMemTypeIdx = m_memoryTypeIndex;
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;
425 VmaAllocationCreateInfo allocCI{};
426 allocCI.usage = VMA_MEMORY_USAGE_AUTO;
427 allocCI.requiredFlags = properties;
428 if (properties & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
432 ? VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT
433 : VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT;
435 if (usage == VK_BUFFER_USAGE_TRANSFER_SRC_BIT) allocCI.pool =
g_stagingPool;
437 VmaAllocationInfo info{};
438 VkResult r = vmaCreateBuffer(s_allocator, &bufferInfo, &allocCI,
439 &buffer, &memory, &info);
441 if (r != VK_SUCCESS && !s_bufferPool.empty()) {
444 SLEAK_WARN(
"Vulkan alloc failed, evicting {} pooled buffers ({:.1f} MB)",
446 static_cast<double>(s_poolBytes) / (1024.0 * 1024.0));
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;
455 s_bufferPool.clear();
457 r = vmaCreateBuffer(s_allocator, &bufferInfo, &allocCI,
458 &buffer, &memory, &info);
461 if (r != VK_SUCCESS) {
464 SLEAK_WARN(
"Vulkan alloc still failing, reclaiming fence-safe deferred deletions");
468 r = vmaCreateBuffer(s_allocator, &bufferInfo, &allocCI,
469 &buffer, &memory, &info);
472 if (r != VK_SUCCESS) {
473 SLEAK_ERROR(
"Failed to allocate Vulkan buffer memory!");
474 buffer = VK_NULL_HANDLE;
475 memory = VK_NULL_HANDLE;
479 s_totalAllocatedBytes += info.size;
480 if (info.memoryType < s_memTypeCount)
481 s_perTypeBytes[info.memoryType] += info.size;
483 if (outAllocSize) *outAllocSize = info.size;
484 if (outMemTypeIdx) *outMemTypeIdx = info.memoryType;
486 if (&buffer == &m_buffer) {
487 m_allocSize = info.size;
489 m_memoryTypeIndex = info.memoryType;
490 m_bufferSize = createSize;
494void VulkanBuffer::CopyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer,
497 EnsureBatchStarted(m_device, m_commandPool, m_graphicsQueue);
499 VkBufferCopy copyRegion{};
500 copyRegion.size = size;
501 vkCmdCopyBuffer(s_batchCommandBuffer, srcBuffer, dstBuffer, 1,
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;
513 VkCommandBuffer commandBuffer;
514 vkAllocateCommandBuffers(m_device, &allocInfo, &commandBuffer);
516 VkCommandBufferBeginInfo beginInfo{};
517 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
518 beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
520 vkBeginCommandBuffer(commandBuffer, &beginInfo);
522 VkBufferCopy copyRegion{};
523 copyRegion.size = size;
524 vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, ©Region);
526 vkEndCommandBuffer(commandBuffer);
528 VkFenceCreateInfo fenceInfo{};
529 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
531 vkCreateFence(m_device, &fenceInfo,
nullptr, ©Fence);
533 VkSubmitInfo submitInfo{};
534 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
535 submitInfo.commandBufferCount = 1;
536 submitInfo.pCommandBuffers = &commandBuffer;
538 vkQueueSubmit(m_graphicsQueue, 1, &submitInfo, copyFence);
539 vkWaitForFences(m_device, 1, ©Fence, VK_TRUE, UINT64_MAX);
541 vkDestroyFence(m_device, copyFence,
nullptr);
542 vkFreeCommandBuffers(m_device, m_commandPool, 1, &commandBuffer);
545void VulkanBuffer::EnsureBatchStarted(VkDevice device, VkCommandPool pool,
547 if (s_batchActive || !s_batchingEnabled)
return;
549 s_batchDevice = device;
550 s_batchCommandPool = pool;
551 s_batchQueue = queue;
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;
559 if (vkAllocateCommandBuffers(device, &allocInfo, &s_batchCommandBuffer) != VK_SUCCESS) {
560 SLEAK_ERROR(
"Failed to allocate batch transfer command buffer!");
564 VkCommandBufferBeginInfo beginInfo{};
565 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
566 beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
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;
575 s_batchActive =
true;
580 vkFreeCommandBuffers(s_batchDevice, s_batchCommandPool, 1,
581 &s_batchCommandBuffer);
582 s_batchCommandBuffer = VK_NULL_HANDLE;
583 s_batchActive =
false;
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;
592 s_pendingCleanup.clear();
599 if (!s_batchActive)
return result;
601 vkEndCommandBuffer(s_batchCommandBuffer);
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;
611 vkQueueSubmit(s_batchQueue, 1, &submitInfo, VK_NULL_HANDLE);
618 result.
device = s_batchDevice;
620 s_pendingCleanup.clear();
621 s_batchCommandBuffer = VK_NULL_HANDLE;
622 s_batchActive =
false;
627uint32_t VulkanBuffer::FindMemoryType(uint32_t typeFilter,
628 VkMemoryPropertyFlags properties) {
629 VkPhysicalDeviceMemoryProperties memProperties;
630 vkGetPhysicalDeviceMemoryProperties(m_physicalDevice, &memProperties);
632 for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) {
633 if ((typeFilter & (1 << i)) &&
634 (memProperties.memoryTypes[i].propertyFlags & properties) ==
640 SLEAK_ERROR(
"Failed to find suitable memory type!");
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 =
663 entry.bufferSize > 0 &&
665 s_bufferPool.size() < MAX_POOL_SIZE &&
666 s_poolBytes + entry.allocSize <= MAX_POOL_BYTES;
670 s_bufferPool.push_back({entry.buffer, entry.memory, entry.device,
671 entry.allocSize, entry.usage,
672 entry.memoryTypeIndex, entry.bufferSize,
674 s_poolBytes += entry.allocSize;
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;
682 entry = std::move(s_deferredDeletions.back());
683 s_deferredDeletions.pop_back();
689 EvictPoolOverBudget();
696 if (s_deferredDeletions.empty()) {
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();
716 if (s_allocator && (s_frameNumber % 600) == 0) {
717 VmaTotalStatistics vs{};
718 vmaCalculateStatistics(s_allocator, &vs);
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());
729bool VulkanBuffer::TryRecycleBuffer(VkDeviceSize size,
730 VkBufferUsageFlags usage,
731 VkMemoryPropertyFlags properties,
733 VmaAllocation& memory,
734 VkDeviceSize* outAllocSize) {
735 if (!
IsRecyclable(usage, properties) || s_bufferPool.empty())
return false;
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) {
745 bestSize = e.bufferSize;
749 if (best == s_bufferPool.size())
return false;
751 PooledBuffer e = s_bufferPool[best];
752 s_bufferPool[best] = s_bufferPool.back();
753 s_bufferPool.pop_back();
754 s_poolBytes -= e.allocSize;
759 if (outAllocSize) *outAllocSize = e.allocSize;
761 if (&buffer == &m_buffer) {
762 m_allocSize = e.allocSize;
764 m_memoryTypeIndex = e.memoryTypeIndex;
765 m_bufferSize = e.bufferSize;
770void VulkanBuffer::EvictPoolOverBudget() {
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;
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();
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;
800 s_deferredDeletions.clear();
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;
809 s_bufferPool.clear();
814 return s_totalAllocatedBytes;
820 if (s_physicalDeviceGlobal == VK_NULL_HANDLE)
return 0;
822 VkPhysicalDeviceMemoryProperties memProps;
823 vkGetPhysicalDeviceMemoryProperties(s_physicalDeviceGlobal, &memProps);
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;
832 return totalDeviceLocal;
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;
850 VkDeviceSize total = 0;
851 for (uint32_t i = 0; i < s_memTypeCount; ++i) {
852 if (s_memTypeIsDeviceLocal[i]) total += s_perTypeBytes[i];
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();
#define STAGING_PROBE_BUFFER_BYTES
static void DiscardPendingCopies()
static void SetPhysicalDevice(VkPhysicalDevice device)
void * GetData() override
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 FlushAllDeferredDeletions()
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 void DumpPerFrameAllocStats()
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.
Result of an async batched flush: the recorded command buffer plus staging resources to free later.
VkCommandPool commandPool
std::vector< PendingStagingCleanup > stagingBuffers
VkCommandBuffer commandBuffer