Vulkan Memory Allocator
|
New explicit graphics APIs (Vulkan and Direct3D 12), thanks to manual memory management, give an opportunity to alias (overlap) multiple resources in the same region of memory - a feature not available in the old APIs (Direct3D 11, OpenGL). It can be useful to save video memory, but it must be used with caution.
For example, if you know the flow of your whole render frame in advance, you are going to use some intermediate textures or buffers only during a small range of render passes, and you know these ranges don't overlap in time, you can bind these resources to the same place in memory, even if they have completely different parameters (width, height, format etc.).
Such scenario is possible using VMA, but you need to create your images manually. Then you need to calculate parameters of an allocation to be made using formula:
Following example shows two different images bound to the same place in memory, allocated to fit largest of them.
VMA also provides convenience functions that create a buffer or image and bind it to memory represented by an existing VmaAllocation: vmaCreateAliasingBuffer(), vmaCreateAliasingBuffer2(), vmaCreateAliasingImage(), vmaCreateAliasingImage2(). Versions with "2" offer additional parameter allocationLocalOffset
.
Remember that using resources that alias in memory requires proper synchronization. You need to issue a memory barrier to make sure commands that use img1
and img2
don't overlap on GPU timeline. You also need to treat a resource after aliasing as uninitialized - containing garbage data. For example, if you use img1
and then want to use img2
, you need to issue an image memory barrier for img2
with oldLayout
= VK_IMAGE_LAYOUT_UNDEFINED
.
Additional considerations:
VK_IMAGE_CREATE_ALIAS_BIT
flag.memoryTypeBits
returned in memory requirements of each resource to make sure the bits overlap. Some GPUs may expose multiple memory types suitable e.g. only for buffers or images with COLOR_ATTACHMENT
usage, so the sets of memory types supported by your resources may be disjoint. Aliasing them is not possible in that case.