]> git.tdb.fi Git - libs/gl.git/blob - source/backends/vulkan/memoryallocator.h
3e1861bae0fa9b6f088d044babb2460891c2f09c
[libs/gl.git] / source / backends / vulkan / memoryallocator.h
1 #ifndef MSP_GL_VULKAN_MEMORYALLOCATOR_H_
2 #define MSP_GL_VULKAN_MEMORYALLOCATOR_H_
3
4 #include <vector>
5 #include <msp/core/noncopyable.h>
6 #include <msp/graphics/vulkancontext.h>
7 #include "handles.h"
8
9 namespace Msp {
10 namespace GL {
11
12 class Device;
13
14 enum MemoryType
15 {
16         UNKNOWN_MEMORY,
17         DEVICE_MEMORY,
18         STAGING_MEMORY,
19         STREAMING_MEMORY
20 };
21
22 class MemoryAllocator: public NonCopyable
23 {
24 private:
25         struct Pool
26         {
27                 MemoryType type = UNKNOWN_MEMORY;
28                 std::vector<unsigned> free_blocks;
29                 bool can_consolidate = false;
30         };
31
32         struct Region
33         {
34                 int pool = -1;
35                 bool direct = false;
36                 VkDeviceMemory memory = 0;
37                 std::size_t size = 0;
38                 void *mapped_address = 0;
39                 unsigned map_count = 0;
40         };
41
42         struct Block
43         {
44                 int region = -1;
45                 bool allocated = false;
46                 std::size_t offset = 0;
47                 std::size_t size = 0;
48                 int prev = -1;
49                 int next = -1;
50         };
51
52         Device &device;
53         VkPhysicalDevice phys_device;
54         std::size_t total_device_memory = 0;
55         std::size_t default_region_size = 0;
56         std::size_t direct_alloc_threshold = 0;
57         std::size_t min_alignment = 256;
58         std::vector<Pool> pools;
59         std::vector<Region> regions;
60         std::vector<Block> blocks;
61
62 public:
63         MemoryAllocator(Device &);
64         ~MemoryAllocator();
65
66 private:
67         unsigned find_memory_pool(unsigned, MemoryType);
68         unsigned create_region(unsigned, size_t, bool);
69         std::vector<unsigned>::iterator lower_bound_by_size(std::vector<unsigned> &, std::size_t);
70         unsigned allocate(std::size_t, std::size_t, unsigned, MemoryType);
71         unsigned split_block(unsigned, std::size_t);
72         void consolidate(unsigned);
73         void merge_block_with_next(unsigned);
74
75 public:
76         unsigned allocate(VkBuffer, MemoryType);
77         unsigned allocate(VkImage, MemoryType);
78         void release(unsigned);
79
80         void *map(unsigned);
81         void unmap(unsigned);
82
83         std::string get_debug() const;
84 };
85
86 } // namespace GL
87 } // namespace Msp
88
89 #endif