blurrypiano / littleVulkanEngine

Code repo for video tutorial series teaching Vulkan and computer graphics
MIT License
829 stars 147 forks source link

Buffer alignment not used on writeToBuffer? #50

Open codethinki opened 5 months ago

codethinki commented 5 months ago

i recently began refactoring and rewriting my vulkan engine which i began following your tutorial and i either dont understand vulkan or you forgot the buffer alignment on writeToBuffer(...).

your code:

void Buffer::writeToBuffer(const void* data, const VkDeviceSize size, const VkDeviceSize data_offset, const VkDeviceSize mapped_offset) const {
    assert(mapped && "writeToBuffer: Cannot copy to unmapped buffer");

    if(size == VK_WHOLE_SIZE) memcpy(mapped, data, bufferSize);
    else memcpy(static_cast<char*>(mapped) + mapped_offset, static_cast<const char*>(data) + data_offset, size);
}

the thing is that the buffer is (as far as i understood) aligned with "data, padding, ..." because buffer size = alignmentSize * instance_count. So on writeToBuffer you should either document that you want the padding (which would be weird to anticipate since the buffer should take care of it) or you copy the elements one by one and insert padding every time. This also would create problems if you want to index into the buffer when only rendering half a model or multiple models in a buffer or whatever since these calculations would have to know the buffer alignment size

The thing is that i dont think thats even required since (im speculating i dont know for sure) the alignment size should only be relevant for the whole buffer size because its allocated all at once. If thats right you can create the buffer with only some very small padding at the end by calculating padding = minAlignmentSize - bufferSize % minAlignmentSize and adding this to the total buffer size. This would also remove the need for additional padding insertion between the elements and every calculation requirement that would come with it

would be nice if you could answer soon :) and also this was an amazing tutorial very well done and explained. i could have never understood vulkan without this