Search code examples
memoryalignmentbuffervulkan

Multiple Buffers In One Device Memory


I would like to combine my several buffers into a single device memory.

  1. If their alignment requirements are different, how should I treat when allocating and mapping memory. Should I calculate allocation size depending on these alignments and also when mapping them should I use their VkBufferCreateInfo's size or VkMemoryRequirements's size and alignment for offsets.

  2. I've realized that when buffer usage changes, the alignment changes also (like VERTEX_BIT and UNIFORM_BIT). I created 52 byte buffer and when usage was VERTEX_BIT , alignment was 16 byte which is understandable but when usage was UNIFORM_BIT, alignment was 64 byte. How it is possible, how it works? I couldn't see the differences by using Nsight graphics because it doesn't show the way how api uses these buffers. Thanks...


Solution

  • Alignment for buffers, or in the middle of a buffer, must be respected. The first address of a memory allocation is effectively at 0, so it aligns with all possible uses. Any buffer that starts from a non-zero offset must use an offset that is aligned appropriately with your usage of that buffer.

    And yes, when deciding how much to allocate, you must take into account padding to make sure all buffer sub-allocations you intend to make are properly aligned.

    As for mapping, you don't map buffers; you map memory. If the memory is host-visible, you should map the entire allocation immediately when you allocate it, and leave it mapped until it's time to destroy the memory. There is nothing to be gained by temporarily mapping only small parts of an allocation. Vulkan doesn't stop you in any way from using an allocation while it is mapped.

    when usage was VERTEX_BIT , alignment was 16 byte which is understandable but when usage was UNIFORM_BIT, alignment was 64 byte. How it is possible, how it works?

    It is "possible" because the implementation said so. The implementation decides on what it requires for alignment in particular use cases, and that's all there is to it. Your job isn't to understand "how it works"; it is to comply with the requirements.