71 lines
1.7 KiB
C++
71 lines
1.7 KiB
C++
//
|
|
// Created by atdunbg on 2026/9/20.
|
|
//
|
|
|
|
#ifndef HELLOVULKAN_MEMORYALLOCATOR_H
|
|
#define HELLOVULKAN_MEMORYALLOCATOR_H
|
|
|
|
|
|
#pragma once
|
|
|
|
#include <vulkan/vulkan.hpp>
|
|
#include <array>
|
|
#include <vector>
|
|
|
|
#include "Engine/Core/Types.h"
|
|
|
|
namespace Engine {
|
|
|
|
class Device;
|
|
|
|
class MemoryAllocator {
|
|
public:
|
|
MemoryAllocator(Device& device);
|
|
~MemoryAllocator();
|
|
|
|
MemoryAllocator(const MemoryAllocator&) = delete;
|
|
MemoryAllocator& operator=(const MemoryAllocator&) = delete;
|
|
|
|
struct Allocation {
|
|
vk::DeviceMemory Memory;
|
|
vk::DeviceSize Offset;
|
|
vk::DeviceSize Size;
|
|
void* MappedPtr = nullptr;
|
|
|
|
// 内部用于 Free
|
|
u32 BlockIndex = 0;
|
|
u32 TypeIndex = 0;
|
|
bool Valid = false;
|
|
};
|
|
|
|
Allocation Allocate(vk::MemoryRequirements reqs, vk::MemoryPropertyFlags props);
|
|
void Free(const Allocation& alloc);
|
|
|
|
void PrintStats() const;
|
|
|
|
private:
|
|
struct FreeRange {
|
|
vk::DeviceSize Offset;
|
|
vk::DeviceSize Size;
|
|
};
|
|
|
|
struct Block {
|
|
vk::DeviceMemory Memory;
|
|
vk::DeviceSize Size;
|
|
vk::DeviceSize Used = 0; // bump 分配用
|
|
void* MappedPtr = nullptr;
|
|
bool IsMapped = false;
|
|
std::vector<FreeRange> FreeList; // 已释放的区域
|
|
};
|
|
|
|
Device& m_Device;
|
|
std::array<std::vector<Block>, VK_MAX_MEMORY_TYPES> m_Blocks;
|
|
std::array<vk::DeviceSize, VK_MAX_MEMORY_TYPES> m_TotalAllocated{};
|
|
|
|
vk::DeviceSize GetBlockSize(vk::MemoryPropertyFlags props) const;
|
|
};
|
|
|
|
} // namespace Engine
|
|
|
|
#endif //HELLOVULKAN_MEMORYALLOCATOR_H
|