Files
mirai/src/gpu_resource/allocator.h

63 lines
1.7 KiB
C++

#pragma once
#include <mutex>
#include "types/types.h"
#include "resource_types.h"
#include "core/object.h"
#include <vulkan/vulkan.hpp>
#include "allocation_types.h"
#include "render/vulkan_types.h"
#include "types/error.h"
namespace mirai {
/**
* @brief GPU 分配器配置
*/
struct allocator_config {
/// Vulkan 实例
vk::Instance instance{};
/// 物理设备
vk::PhysicalDevice physical_device{};
/// 逻辑设备
vk::Device device{};
/// Vulkan API 版本
u32 vulkan_api_version = VK_API_VERSION_1_3;
/// 是否启用 Buffer Device Address
bool enable_buffer_device_address = true;
/// 是否启用内存预算跟踪
bool enable_memory_budget = true;
/// 首选的大块分配大小(字节)
u64 preferred_large_heap_block_size = 256 * 1024 * 1024; // 256 MB
vk_dispatch_loader& disp;
};
class vma_allocator : public object {
MIRAI_OBJECT_TYPE_INFO(vma_allocator, object)
explicit vma_allocator(const allocator_config& config) {
setup(config);
}
void setup(const allocator_config& config);
result_t<buffer_allocation> alloc_buffer(const buffer_create_info& info);
result_t<buffer_allocation> alloc_staging_buffer(const buffer_create_info& info);
void_result_t free_buffer(const buffer_allocation& buffer);
void_result_t free_staging_buffer(const buffer_allocation& buffer);
protected:
void on_destroying() override;
private:
vk::Instance instance_{};
vk::PhysicalDevice physical_device_;
vk::Device device_;
vma::Allocator vma_allocator_;
vma::DefragmentationContext defrag_context_;
bool enable_buffer_device_address_ = true;
std::atomic<u64> total_allocated_bytes_{0};
std::atomic<u64> allocation_count_{0};
mutable std::mutex mutex_;
};
}