Skip to content
ImagineWorld

Working with Vulkan Objects

node_idnode-book_vulkan-3d-graphics-rendering-cookbook_chapter-03-working-with-vulkan-objects
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleWorking with Vulkan Objects
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In the previous chapter, we learned how to get our first triangle on the screen using Vulkan. Let’s go forward and learn how to deal with textures and buffers to build a modern Vulkan wrapper. The recipes of this chapter will not be focusing solely on the graphics APIs, but on various tips and tricks necessary to improve graphical applications development and various 3D graphics algorithms. On the Vulkan side, we will cover the basic stuff to get it up and running. The underlying Vulkan implementation is based on the LightweightVK library https://github.com/corporateshark/lightweightvk.

In the chapter we will cover the following recipes:

  • Dealing with buffers in Vulkan
  • Implementing staging buffers
  • Using texture data in Vulkan
  • Storing Vulkan objects
  • Using Vulkan descriptor indexing

To run the recipes from this chapter, you have to use a Windows or Linux computer with a video card and drivers supporting Vulkan 1.3. Read the previous Chapter 2 to learn the basics necessary to get you started with Vulkan.

Buffers in Vulkan are essentially memory regions that store data for GPU access. More specifically, a Vulkan buffer refers to a VkBuffer object that is associated with memory regions allocated through VkDeviceMemory. To render a 3D scene with Vulkan, we must convert the scene data into a format the GPU can process. In this recipe, we’ll explain how to create GPU buffers and upload vertex data into them. We’ll use the open-source asset-loading library Assimp https://github.com/assimp/assimp to load a 3D model from an .obj file and render it using LightweightVK and Vulkan. Additionally, this recipe includes a basic introduction to using the Vulkan Memory Allocator (VMA) library.

In Vulkan, uploading data to GPU buffers is done using command buffers, similar to many other Vulkan operations. This requires a command queue that supports transfer operations. The process of creating and using command buffers was covered in the previous chapter in the recipe Using Vulkan command buffers.

Let’s begin with the high-level code in our sample application, Chapter03/01_Assimp, and work our way down to the Vulkan API from there.

  1. First, we need to load the model from an .obj file using the Assimp library. Here’s some basic code to achieve this. Keep in mind that calling reserve() on vectors can improve performance. For simplicity, we’ll load only the first mesh and extract vertex positions and indices.
    const aiScene* scene = aiImportFile(
    "data/rubber_duck/scene.gltf", aiProcess_Triangulate);
    const aiMesh* mesh = scene->mMeshes[0];
    std::vector<vec3> positions;
    std::vector<uint32_t> indices;
    for (unsigned int i = 0; i != mesh->mNumVertices; i++) {
    const aiVector3D v = mesh->mVertices[i];
    positions.push_back(vec3(v.x, v.y, v.z));
    }
    for (unsigned int i = 0; i != mesh->mNumFaces; i++) {
    for (int j = 0; j != 3; j++) {
    indices.push_back(mesh->mFaces[i].mIndices[j]);
    }
    }
    aiReleaseImport(scene);
  2. Next, we need to create buffers for the loaded vertex positions and indices. The vertex buffer will use the BufferUsageBits_Vertex flag, and we’ll instruct LightweightVK to upload the initial data from positions.data() right away. The C++20 designated initializer syntax is particularly convenient for working with high-level APIs like this. Similarly, the index buffer will use the BufferUsageBits_Index flag. Both buffers will be stored in GPU memory to optimize performance. This is achieved by specifying the storage type as StorageType_Device, which LightweightVK interprets to select the appropriate Vulkan memory type for these buffers.
    Holder<BufferHandle> vertexBuffer = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Vertex,
    .storage = lvk::StorageType_Device,
    .size = sizeof(vec3) * positions.size(),
    .data = positions.data(),
    .debugName = "Buffer: vertex" });
    Holder<BufferHandle> indexBuffer = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Index,
    .storage = lvk::StorageType_Device,
    .size = sizeof(uint32_t) * indices.size(),
    .data = indices.data(),
    .debugName = "Buffer: index" });
  3. To render a concave mesh in Vulkan, we need to use a depth buffer, which we’ll create as follows. Here, we specify Format_Z_F32, but the LightweightVK Vulkan backend will automatically substitute it with the closest available format supported by the current Vulkan implementation. The width and height values match the dimensions of the framebuffer. Since the depth texture will only be used as a depth buffer and not for sampling, specifying the usage flags as TextureUsageBits_Attachment is sufficient.
    Holder<TextureHandle> depthTexture = ctx->createTexture({
    .type = lvk::TextureType_2D,
    .format = lvk::Format_Z_F32,
    .dimensions = {(uint32_t)width, (uint32_t)height},
    .usage = lvk::TextureUsageBits_Attachment,
    .debugName = "Depth buffer",
    });
  4. Before proceeding to create rendering pipelines, as described in the previous chapter in the recipe Initializing Vulkan pipelines, we need to define the vertex input state using the previously mentioned vertex buffer. Here’s how to do it. The .location = 0 corresponds to the input location in the GLSL vertex shader that will be used to render this mesh.
    const lvk::VertexInput vdesc = {
    .attributes = { { .location = 0,
    .format = lvk::VertexFormat::Float3 } },
    .inputBindings = { { .stride = sizeof(vec3) } },
    };
  5. Now, we can create two rendering pipelines: one for rendering a solid mesh and another for rendering a wireframe mesh on top of it. Note that the pipeline depthFormat is set to the actual format of the depth texture we created earlier.
    Holder<ShaderModuleHandle> vert =
    loadShaderModule(ctx, "Chapter03/01_Assimp/src/main.vert");
    Holder<ShaderModuleHandle> frag =
    loadShaderModule(ctx, "Chapter03/01_Assimp/src/main.frag");
    Holder<RenderPipelineHandle> pipelineSolid =
    ctx->createRenderPipeline({
    .vertexInput = vdesc,
    .smVert = vert,
    .smFrag = frag,
    .color = { { .format = ctx->getSwapchainFormat() } },
    .depthFormat = ctx->getFormat(depthTexture),
    .cullMode = lvk::CullMode_Back,
    });
  6. The second rendering pipeline performs wireframe rendering by setting the polygonMode field to PolygonMode_Line. Both pipelines share the same set of shaders, with a specialization constant used to adjust the shader behavior without modifying the underlying GLSL code.
    const uint32_t isWireframe = 1;
    Holder<RenderPipelineHandle> pipelineWireframe =
    ctx->createRenderPipeline({
    .vertexInput = vdesc,
    .smVert = vert,
    .smFrag = frag,
    .specInfo = {
    .entries = { { .constantId = 0,
    .size = sizeof(uint32_t) } },
    .data = &isWireframe,
    .dataSize = sizeof(isWireframe) },
    .color = { { .format = ctx->getSwapchainFormat() } },
    .depthFormat = ctx->getFormat(depthTexture),
    .cullMode = lvk::CullMode_Back,
    .polygonMode = lvk::PolygonMode_Line,
    });

Now let’s take a look at the application’s main loop. We’ll omit the GLFW event polling and framebuffer size update code here, but you can find it in Chapter03/01_Assimp/src/main.cpp.

  1. In the main loop, the projection matrix p is updated based on the current framebuffer’s aspect ratio.
    while (!glfwWindowShouldClose(window)) {
    // … skipped GLFW code
    const float ratio = width / height;
    const mat4 p = glm::perspective(45.0f, ratio, 0.1f, 1000.0f);
  2. Set the model-view matrix to enable a gradual rotation of the model around the vertical axis. The model matrix m aligns the model’s “up” direction with Vulkan’s vertical axis. The view matrix v defines the 3D camera’s orientation and viewing direction, which slowly rotates around the vertical axis Y.
    const mat4 m = glm::rotate(
    mat4(1.0f), glm::radians(-90.0f), vec3(1, 0, 0));
    const mat4 v = glm::rotate(glm::translate(mat4(1.0f),
    vec3(0.0f, -0.5f, -1.5f)), (float)glfwGetTime(),
    vec3(0.0f, 1.0f, 0.0f));
  3. The render pass description now includes a load operation and a clear value for the depth buffer. The framebuffer contains only one color attachment—the current swapchain image.
    const lvk::RenderPass renderPass = {
    .color = {
    { .loadOp = LoadOp_Clear, .clearColor = { 1, 1, 1, 1 }}},
    .depth = { .loadOp = LoadOp_Clear, .clearDepth = 1. }
    };
    const lvk::Framebuffer framebuffer = {
    .color = {{ .texture = ctx->getCurrentSwapchainTexture()}},
    .depthStencil = { .texture = depthTexture },
    };
  4. With all preparations complete, we can acquire a command buffer as described in the recipe Using Vulkan command buffers from Chapter 2 and begin rendering.
    lvk::ICommandBuffer& buf = ctx->acquireCommandBuffer();
    buf.cmdBeginRendering(renderPass, framebuffer);
  5. Both the vertex and index buffers should be bound. The vertex buffer is bound to binding point 0. The index buffer uses unsigned 32-bit integer values as indices.
    buf.cmdBindVertexBuffer(0, vertexBuffer);
    buf.cmdBindIndexBuffer(indexBuffer, lvk::IndexFormat_UI32);
  6. Let’s render a solid mesh using the first rendering pipeline. The model-view-projection matrix is passed to the shader using Vulkan push constants. Push constants are a performant mechanism for passing small amounts of data to shaders. Vulkan 1.3 guarantees at least 128 bytes for push constants, which is enough to store two 4x4 matrices or 16 arbitrary 64-bit GPU buffer addresses. The depth-stencil state is configured to enable the use of our depth buffer.
    buf.cmdBindRenderPipeline(pipelineSolid);
    buf.cmdBindDepthState({ .compareOp = lvk::CompareOp_Less,
    .isDepthWriteEnabled = true });
    buf.cmdPushConstants(p * v * m);
    buf.cmdDrawIndexed(indices.size());
  7. Next, we render a wireframe copy of the mesh on top of the solid one. We set a depth bias to ensure the wireframe edges are rendered correctly and without flickering. This is necessary to prevent Z-fighting between the rendered solid mesh and the wireframe overlay.
    buf.cmdBindRenderPipeline(pipelineWireframe);
    buf.cmdSetDepthBiasEnable(true);
    buf.cmdSetDepthBias(0.0f, -1.0f, 0.0f);
    buf.cmdDrawIndexed(indices.size());
  8. Now the command buffer can be submitted for execution.
    buf.cmdEndRendering();
    ctx->submit(buf, ctx->getCurrentSwapchainTexture());
    }

The demo application should render a colored rotating ducky with a wireframe overlay, as shown in the following screenshot.

Figure 3.1: Rendering a mesh loaded with Assimp

The high-level part was easy. Now, let’s dive into the underlying implementation and explore how to build this streamlined buffer management interface using the Vulkan API.

Let’s examine the low-level Vulkan code to understand how buffers work. Our deep dive begins with exploring IContext::createBuffer(), which takes a buffer description structure BufferDesc as input.

  1. The declaration of BufferDesc looks as follows. The storage type can be one of three enum values: StorageType_Device, StorageType_HostVisible, and StorageType_Memoryless. These correspond to GPU local memory (which is usually not visible from the CPU side), host-visible memory, and memory that is not used for storage. The underlying LightweightVK code and the Vulkan Memory Allocator (VMA) library precisely select the appropriate Vulkan memory type.
    struct BufferDesc final {
    uint8_t usage = 0;
    StorageType storage = StorageType_HostVisible;
    size_t size = 0;
    const void* data = nullptr;
    const char* debugName = "";
    };
  2. The buffer usage mode is a combination of the following flags. These flags are highly flexible, allowing us to request any necessary combination, with the exception that uniform and storage buffers are mutually exclusive. LightweightVK also supports additional buffer usage modes for ray tracing, which are not explored in our book.
    enum BufferUsageBits : uint8_t {
    BufferUsageBits_Index = 1 << 0,
    BufferUsageBits_Vertex = 1 << 1,
    BufferUsageBits_Uniform = 1 << 2,
    BufferUsageBits_Storage = 1 << 3,
    BufferUsageBits_Indirect = 1 << 4,
    };

Let’s now examine the implementation of VulkanContext::createBuffer(), which converts the requested LightweightVK buffer properties into the corresponding supported Vulkan flags.

  1. First, we need to check if a staging buffer should be used to upload data into the new buffer. If the staging buffer is disabled—such as when our GPU has only one shared memory heap that is both host-visible and device-local—we override the requested device-local storage mode with StorageType_HostVisible. This is important to avoid the extra copy on GPUs with such memory configurations. Note In Vulkan, device-local memory is typically not accessible by the CPU on dedicated graphics cards. To populate such buffers with data, we need to create a host-visible buffer, known as a staging buffer, and first populate it from the CPU side. Then, we issue Vulkan commands to copy its contents into the actual device-local buffer.
Holder<BufferHandle> VulkanContext::createBuffer(
const BufferDesc& requestedDesc, Result* outResult) {
BufferDesc desc = requestedDesc;
if (!useStaging_ && (desc.storage == StorageType_Device))
desc.storage = StorageType_HostVisible;
  1. If the application requires a device-local buffer, we should use a staging buffer to transfer data into the device-local buffer. We need to set the appropriate Vulkan flags to ensure that data can be transferred to and from this buffer.
    VkBufferUsageFlags usageFlags =
    desc.storage == StorageType_Device ?
    VK_BUFFER_USAGE_TRANSFER_DST_BIT |
    VK_BUFFER_USAGE_TRANSFER_SRC_BIT : 0;
  2. For each requested usage flag, enable the corresponding set of necessary Vulkan usage flags. To use the Vulkan 1.2 buffer device address feature and access buffers by pointers from shaders, we need to add the flag VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT.
    if (desc.usage & BufferUsageBits_Index)
    usageFlags |= VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
    if (desc.usage & BufferUsageBits_Vertex)
    usageFlags |= VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
    if (desc.usage & BufferUsageBits_Uniform)
    usageFlags |= VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT |
    VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT;
    if (desc.usage & BufferUsageBits_Storage)
    usageFlags |= VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
    VK_BUFFER_USAGE_TRANSFER_DST_BIT |
    VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT;
    if (desc.usage & BufferUsageBits_Indirect)
    usageFlags |= VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT |
    VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT;
  3. Retrieve the required Vulkan memory properties using a helper function, and then call another overload of VulkanContext::createBuffer() that accepts only Vulkan flags. Delegating this step is useful because this function is also used inside the LightweightVK Vulkan backend to create internal auxiliary buffers. It checks buffer size limits and creates a VulkanBuffer object in the appropriate pool.
    const VkMemoryPropertyFlags memFlags =
    storageTypeToVkMemoryPropertyFlags(desc.storage);
    Result result;
    BufferHandle handle = createBuffer(
    desc.size, usageFlags, memFlags, &result, desc.debugName);
  4. In case some initial buffer data was provided, upload it immediately.
    if (desc.data) {
    upload(handle, desc.data, desc.size, 0);
    }
    Result::setResult(outResult, Result());
    return {this, handle};
    }

Let’s take a look at the declaration of VulkanBuffer, which encapsulates the Vulkan buffer management functionality.

  1. All previously obtained Vulkan flags are stored in VulkanBuffer to be stored in LightweightVK object pools. We will discuss these pools in more detail in subsequent chapters. VMA-related fields are used only when the VMA library is enabled.
    struct VulkanBuffer final {
    VkBuffer vkBuffer_ = VK_NULL_HANDLE;
    VkDeviceMemory vkMemory_ = VK_NULL_HANDLE;
    VmaAllocation vmaAllocation_ = VK_NULL_HANDLE;
    VkDeviceAddress vkDeviceAddress_ = 0;
    VkDeviceSize bufferSize_ = 0;
    VkBufferUsageFlags vkUsageFlags_ = 0;
    VkMemoryPropertyFlags vkMemFlags_ = 0;
    void* mappedPtr_ = nullptr;
    bool isCoherentMemory_ = false;
  2. A set of methods for transferring data to and from buffers. All host-visible buffers are automatically mapped, allowing us to access their data using normal C++ pointers.
    uint8_t* getMappedPtr() const { return (uint8_t*)mappedPtr_; }
    bool isMapped() const { return mappedPtr_ != nullptr; }
    void bufferSubData(const VulkanContext& ctx,
    size_t offset, size_t size, const void* data);
    void getBufferSubData(const VulkanContext& ctx,
    size_t offset, size_t size, void* data);
  3. The function flushMappedMemory() is required if the buffers on our system do not support coherent memory. This function is called to ensure that the data written into the mapped memory by the host becomes available to the GPU. It acts as a wrapper around vkFlushMappedMemoryRanges() and vmaFlushAllocation() when the VMA library is enabled. The function invalidateMappedMemory() is used for the opposite direction, from GPU to CPU, to ensure that data written by the GPU becomes available to the CPU. It serves as a wrapper around vkInvalidateMappedMemoryRanges() and vmaInvalidateAllocation(). We will use it in Chapter 11.

Note

Using the flushing and invalidation functions is mandatory for non-coherent memory, and their absence is a common mistake made by novice Vulkan developers. This error can often go unnoticed because the program may run correctly on discrete desktop GPUs (which often have coherent memory) but produce incorrect results on mobile GPUs.

void flushMappedMemory(const VulkanContext& ctx,
VkDeviceSize offset, VkDeviceSize size) const;
void invalidateMappedMemory(const VulkanContext& ctx,
VkDeviceSize offset, VkDeviceSize size) const;
};

Now we are ready to create the actual VkBuffer object. Let’s take a look at the code. Error handling is omitted for clarity and better understanding.

  1. Here’s the corresponding overload of VulkanContext::createBuffer() that does this. It begins by populating the VkBufferCreateInfo structure.
    BufferHandle lvk::VulkanContext::createBuffer(
    VkDeviceSize bufferSize,
    VkBufferUsageFlags usageFlags,
    VkMemoryPropertyFlags memFlags,
    lvk::Result* outResult,
    const char* debugName)
    {
    VulkanBuffer buf = {
    .bufferSize_ = bufferSize,
    .vkUsageFlags_ = usageFlags,
    .vkMemFlags_ = memFlags,
    };
    const VkBufferCreateInfo ci = {
    .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
    .flags = 0,
    .size = bufferSize,
    .usage = usageFlags,
    .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
    .queueFamilyIndexCount = 0,
    .pQueueFamilyIndices = nullptr,
    };
  2. Now, we decide whether to use Vulkan directly or let the Vulkan Memory Allocator (VMA) handle all memory allocation for us. VMA is the primary code path, while direct Vulkan calls are useful for debugging when necessary. If using VMA, we convert the flags once more.
    if (LVK_VULKAN_USE_VMA) {
    VmaAllocationCreateInfo vmaAllocInfo = {};
    if (memFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
    vmaAllocInfo = {
    .flags = VMA_ALLOCATION_CREATE_MAPPED_BIT |
    VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT,
    .requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
    .preferredFlags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
    VK_MEMORY_PROPERTY_HOST_CACHED_BIT };
    }
    if (memFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
    vkCreateBuffer(vkDevice_, &ci, nullptr, &buf.vkBuffer_);
    VkMemoryRequirements requirements = {};
    vkGetBufferMemoryRequirements(
    vkDevice_, buf.vkBuffer_, &requirements);
    vkDestroyBuffer(vkDevice_, buf.vkBuffer_, nullptr);
    buf.vkBuffer_ = VK_NULL_HANDLE;
    if (requirements.memoryTypeBits &
    VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) {
    vmaAllocInfo.requiredFlags |=
    VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
    buf.isCoherentMemory_ = true;
    }
    }
    vmaAllocInfo.usage = VMA_MEMORY_USAGE_AUTO;
    vmaCreateBuffer((VmaAllocator)getVmaAllocator(), &ci,
    &vmaAllocInfo, &buf.vkBuffer_,
    &buf.vmaAllocation_, nullptr);
  3. Handle host-visible memory-mapped buffers by using persistent mapping for the entire lifetime of the buffer.
    if (memFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
    vmaMapMemory((VmaAllocator)getVmaAllocator(),
    buf.vmaAllocation_, &buf.mappedPtr_);
    }
    }
  4. The direct Vulkan code path is straightforward but requires manual memory allocation. For full detailed error checking, refer to lvk/vulkan/VulkanClasses.cpp, as it is omitted here for clarity.
    else {
    vkCreateBuffer(vkDevice_, &ci, nullptr, &buf.vkBuffer_);
    VkMemoryRequirements requirements = {};
    vkGetBufferMemoryRequirements(
    vkDevice_, buf.vkBuffer_, &requirements);
    if (requirements.memoryTypeBits &
    VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) {
    buf.isCoherentMemory_ = true;
    }
    lvk::allocateMemory(vkPhysicalDevice_, vkDevice_,
    &requirements, memFlags, &buf.vkMemory_);
    vkBindBufferMemory(
    vkDevice_, buf.vkBuffer_, buf.vkMemory_, 0);
  5. Host-visible buffers are handled in a similar way.
    if (memFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
    vkMapMemory(vkDevice_, buf.vkMemory_, 0,
    buf.bufferSize_, 0, &buf.mappedPtr_);
    }
    }
  6. After the VkBuffer object is created, we set a user-provided debug name for the buffer and obtain a buffer device address, which can be used in shaders to access the buffer.
    lvk::setDebugObjectName(vkDevice_, VK_OBJECT_TYPE_BUFFER,
    (uint64_t)buf.vkBuffer_, debugName);
    if (usageFlags & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) {
    const VkBufferDeviceAddressInfo ai = {
    .sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO,
    .buffer = buf.vkBuffer_,
    };
    buf.vkDeviceAddress_ =
    vkGetBufferDeviceAddress(vkDevice_, &ai);
    }
    return buffersPool_.create(std::move(buf));
    }

The buffer destruction process is important to note because Vulkan buffers should not be deleted while they are still in use by the GPU. In addition to VMA and Vulkan calls for memory unmapping and deallocation, the destructor defers the actual deallocation until the buffer is no longer in use by the GPU.

  1. The destruction process occurs in VulkanContext::destroy(BufferHandle), which is invoked from the RAII wrapper Holder<BufferHandle>. The deferredTask() member function postpones the execution of its lambda argument until a later time, when all previously submitted command buffers have finished processing. We will explore this mechanism in subsequent chapters.
    void lvk::VulkanContext::destroy(BufferHandle handle) {
    SCOPE_EXIT { buffersPool_.destroy(handle); };
    lvk::VulkanBuffer* buf = buffersPool_.get(handle);
    if (!buf) return;
    if (LVK_VULKAN_USE_VMA) {
    if (buf->mappedPtr_) {
    vmaUnmapMemory(
    (VmaAllocator)getVmaAllocator(), buf->vmaAllocation_);
    }
    deferredTask(std::packaged_task<void()>(
    [vma = getVmaAllocator(),
    buffer = buf->vkBuffer_,
    allocation = buf->vmaAllocation_]() {
    vmaDestroyBuffer((VmaAllocator)vma, buffer, allocation);
    }));
    }
  2. A similar approach is used when we do not rely on VMA and instead interact with Vulkan directly.
    else {
    if (buf->mappedPtr_)
    vkUnmapMemory(vkDevice_, buf->vkMemory_);
    deferredTask(std::packaged_task<void()>(
    [device = vkDevice_,
    buffer = buf->vkBuffer_,
    memory = buf->vkMemory_]() {
    vkDestroyBuffer(device, buffer, nullptr);
    vkFreeMemory(device, memory, nullptr);
    }));
    }
    }

Three other member functions to mention here before we conclude how we work with Vulkan buffers.

  1. The function flushMappedMemory() is used to ensure that host writes to the buffer mapped memory become available to the GPU when the coherent memory is not supported.
    void lvk::VulkanBuffer::flushMappedMemory(
    const VulkanContext& ctx,
    VkDeviceSize offset,
    VkDeviceSize size) const
    {
    if (!LVK_VERIFY(isMapped())) return;
    if (LVK_VULKAN_USE_VMA) {
    vmaFlushAllocation((VmaAllocator)ctx.getVmaAllocator(),
    vmaAllocation_, offset, size);
    } else {
    const VkMappedMemoryRange range = {
    .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
    .memory = vkMemory_,
    .offset = offset,
    .size = size,
    };
    vkFlushMappedMemoryRanges(ctx.getVkDevice(), 1, &range);
    }
    }
  2. The function getBufferSubData() wraps a memcpy() operation in a convenient way. It only works with memory-mapped host-visible buffers, while device-local buffers are handled separately by VulkanContext using a staging buffer. We will discuss this mechanism in subsequent chapters.
    void lvk::VulkanBuffer::getBufferSubData(
    const VulkanContext& ctx,
    size_t offset,
    size_t size,
    void* data)
    {
    if (!mappedPtr_) return;
    if (!isCoherentMemory_) {
    invalidateMappedMemory(ctx, offset, size);
    }
    memcpy(data, (const uint8_t*)mappedPtr_ + offset, size);
    }
  3. The function bufferSubData() is a similar wrapper. It is straightforward for host-visible buffers. Note how memset() is used here to set the content of the buffer to 0.
    void lvk::VulkanBuffer::bufferSubData(
    const VulkanContext& ctx,
    size_t offset,
    size_t size,
    const void* data)
    {
    if (!mappedPtr_) return;
    if (data) {
    memcpy((uint8_t*)mappedPtr_ + offset, data, size);
    } else {
    memset((uint8_t*)mappedPtr_ + offset, 0, size);
    }
    if (!isCoherentMemory_) {
    flushMappedMemory(ctx, offset, size);
    }
    }

Now that we’ve covered all the Vulkan code necessary to run the app in Chapter03/01_Assimp, which renders a .obj 3D model loaded via Assimp, there are two small functions to mention. These functions bind the vertex and index buffers, respectively, and are part of the ICommandBuffer interface.

  1. The first function binds a vertex buffer via vkCmdBindVertexBuffers() to be used for vertex input. A few checks are necessary to ensure the correct usage of buffers. In subsequent chapters, we will learn how to omit vertex buffers altogether and explore the Programmable-Vertex-Pulling (PVP) approach.
    void lvk::CommandBuffer::cmdBindVertexBuffer(
    uint32_t index, BufferHandle buffer, uint64_t bufferOffset)
    {
    lvk::VulkanBuffer* buf = ctx_->buffersPool_.get(buffer);
    LVK_ASSERT(buf->vkUsageFlags_ & VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
    vkCmdBindVertexBuffers(
    wrapper_->cmdBuf_, index, 1, &buf->vkBuffer_, &bufferOffset);
    }
  2. The second function binds an index buffer using vkCmdBindIndexBuffer(). In addition to assertions, it includes some enum type conversions from LightweightVK to the Vulkan API.
    void lvk::CommandBuffer::cmdBindIndexBuffer(
    BufferHandle indexBuffer,
    IndexFormat indexFormat, uint64_t indexBufferOffset)
    {
    lvk::VulkanBuffer* buf = ctx_->buffersPool_.get(indexBuffer);
    LVK_ASSERT(buf->vkUsageFlags_ & VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
    const VkIndexType type = indexFormatToVkIndexType(indexFormat);
    vkCmdBindIndexBuffer(
    wrapper_->cmdBuf_, buf->vkBuffer_, indexBufferOffset, type);
    }

The application Chapter03/01_Assimp should render the following image.

Figure 3.2: Rendering a mesh loaded with Assimp

Now that we’ve covered some very basic Vulkan usage, we are ready to add textures to our examples.

Vulkan device-local buffers are often not visible from the host, meaning we can upload data into them only through various CPU-GPU-CPU transfer operations. In Vulkan, this is achieved by creating an auxiliary buffer, known as a staging buffer, which is CPU-visible (host-visible). We upload data into this staging buffer from the host and then issue GPU commands to copy the data from the staging buffer into a device-local buffer. Let’s learn how to implement this technique in Vulkan.

Before reading any further, check out the previous recipe Dealing with buffers in Vulkan to learn how to create different types of Vulkan buffers.

As usual, let’s start with the high-level interface of LightweightVK and then dive deep into the implementation. The interface class IContext, declared in lightweightvk/lvk/LVK.h, exposes the following virtual methods to operate on buffers.

class IContext {
public:
// ...
virtual Result upload(BufferHandle handle,
const void* data, size_t size, size_t offset = 0) = 0;
virtual Result download(BufferHandle handle,
void* data, size_t size, size_t offset) = 0;
virtual uint8_t* getMappedPtr(BufferHandle handle) const = 0;
virtual uint64_t gpuAddress(BufferHandle handle,
size_t offset = 0) const = 0;
virtual void flushMappedMemory(BufferHandle handle,
size_t offset, size_t size) const = 0;

These methods are implemented in a subclass VulkanContext, and roughly correspond to the implementation of VulkanBuffer, which was discussed in detail in the previous recipe. We also saw how VulkanContext::createBuffer() calls VulkanContext::upload() if there’s any initial data to be uploaded into a buffer. Let’s take a look at what’s inside that method.

  1. First, we need to convert a buffer handle into a pointer to a VulkanBuffer object. This is done by a pool that stores all VulkanBuffer objects in the system. The pool implementation will be discussed later in the recipe Storing Vulkan objects. For now, let’s treat it as an opaque mechanism that maps an integer handle to a VulkanBuffer object pointer.
    lvk::Result lvk::VulkanContext::upload(
    lvk::BufferHandle handle,
    const void* data, size_t size, size_t offset)
    {
    lvk::VulkanBuffer* buf = buffersPool_.get(handle);
  2. After performing some initial range checking, we delegate the work to the member function VulkanStagingDevice::bufferSubData().
    if (!LVK_VERIFY(offset + size <= buf->bufferSize_)) {
    return Result(Code::ArgumentOutOfRange, "Out of range");
    }
    stagingDevice_->bufferSubData(*buf, offset, size, data);
    return Result();
    }

The class VulkanStagingDevice encapsulates all the functionality necessary to manage Vulkan staging buffers.

  1. The staging device provides functionality to access device-local buffers and images. In this recipe, we will focus only on the buffers part and 2D images. While 3D image uploading is supported by LightweightVK, it is not used in our book, so we will skip that. If you’re interested in those details, you’re encouraged to check the actual source code of LightweightVK here: lvk/vulkan/VulkanClasses.cpp.
    class VulkanStagingDevice final {
    public:
    explicit VulkanStagingDevice(VulkanContext& ctx);
    void bufferSubData(VulkanBuffer& buffer,
    size_t dstOffset, size_t size, const void* data);
    void imageData2D(VulkanImage& image,
    const VkRect2D& imageRegion,
    uint32_t baseMipLevel,
    uint32_t numMipLevels,
    uint32_t layer,
    uint32_t numLayers,
    VkFormat format,
    const void* data);
    // … imageData3D() is skipped
  2. Each call to bufferSubData() or imageData2D() occupies some space in the staging buffer. The structure MemoryRegionDesc describes such a memory region, including the SubmitHandle used to upload data through it.
    private:
    struct MemoryRegionDesc {
    uint32_t offset_ = 0;
    uint32_t size_ = 0;
    SubmitHandle handle_ = {};
    };
  3. The function getNextFreeOffset() returns the next available memory region suitable for accommodating a specified number of bytes. The function ensureStagingBufferSize() grows the staging buffer size up to an internal limit, trying to accommodate as much of the uploading size as possible. The function waitAndReset() is used to wait until all memory regions become available. The default minimal buffer size minBufferSize_ is chosen to accommodate an RGBA 2K texture.
    MemoryRegionDesc getNextFreeOffset(uint32_t size);
    void ensureStagingBufferSize(uint32_t sizeNeeded);
    void waitAndReset();
    private:
    VulkanContext& ctx_;
    lvk::Holder<BufferHandle> stagingBuffer_;
    uint32_t stagingBufferSize_ = 0;
    uint32_t stagingBufferCounter_ = 0;
    uint32_t maxBufferSize_ = 0;
    const uint32_t minBufferSize_ = 4u * 2048u * 2048u;
    std::deque<MemoryRegionDesc> regions_;
    };

The uploading process is straightforward once we understand how the getNextFreeOffset() helper function works. Let’s take a look.

  1. Ensure the requested buffer size is aligned. Some compressed image formats require the size to be padded to 16 bytes, so we use that value greedily here. A simple binary arithmetic trick is used in getAlignedSize() to ensure the size value is aligned as required.
    MemoryRegionDesc VulkanStagingDevice::getNextFreeOffset(
    uint32_t size)
    {
    const uint32_t requestedAlignedSize = getAlignedSize(
    size, kStagingBufferAlignment);
    ensureStagingBufferSize(requestedAlignedSize);
  2. We track the most suitable memory region and check if we can reuse any previously used memory regions. This may cause some memory fragmentation in the staging buffer, but it’s not a concern since these suballocations have a very short lifespan.
    auto bestNextIt = regions_.begin();
    for (auto it = regions_.begin(); it != regions_.end(); ++it) {
    if (ctx_.immediate_->isReady(it->handle_)) {
    if (it->size_ >= requestedAlignedSize) {
  3. Here, we know that this region is available, as isReady() returned true, and large enough to accommodate our entire upload size.
    const uint32_t unusedSize = it->size_ - requestedAlignedSize;
    const uint32_t unusedOffset = it->offset_ + requestedAlignedSize;
  4. Return this region and add the remaining unused size back to the regions_ deque.
    SCOPE_EXIT {
    regions_.erase(it);
    if (unusedSize) {
    regions_.push_front(
    {unusedOffset, unusedSize, SubmitHandle()});
    }
    };
    return {
    it->offset_, requestedAlignedSize, SubmitHandle()};
    }
  5. Cache the largest available region that isn’t as big as the one we’re looking for.
    if (it->size_ > bestNextIt->size_) {
    bestNextIt = it;
    }
    }
    }
  6. We found a region that is available but smaller than the requested size. For now, it’s the best we can do. Return it, and the upload will proceed in chunks.
    if (bestNextIt != regions_.end() &&
    ctx_.immediate_->isReady(bestNextIt->handle_)) {
    SCOPE_EXIT {
    regions_.erase(bestNextIt);
    };
    return {
    bestNextIt->offset_, bestNextIt->size_, SubmitHandle()};
    };
  7. At this point, we know that no part of the staging buffer is available, and we cannot grow its size any further due to platform limits enforced in ensureStagingBufferSize(). Let’s give up and wait for the entire staging buffer to become free. The function waitAndReset() adds a region that spans the entire staging buffer. Since we’ll be using part of it, we need to replace it with a used block and a new unused portion. More information Here’s the code of waitAndReset() for your convenience:
    void lvk::VulkanStagingDevice::waitAndReset() {
    for (const MemoryRegionDesc& r : regions_) {
    ctx_.immediate_->wait(r.handle_);
    };
    regions_.clear();
    regions_.push_front(
    {0, stagingBufferSize_, SubmitHandle()});
    }
waitAndReset();
regions_.clear();
const uint32_t unusedSize =
stagingBufferSize_ > requestedAlignedSize ?
stagingBufferSize_ - requestedAlignedSize : 0;
if (unusedSize) {
const uint32_t unusedOffset =
stagingBufferSize_ - unusedSize;
regions_.push_front({
unusedOffset, unusedSize, SubmitHandle()});
}
return {
.offset_ = 0,
.size_ = stagingBufferSize_ - unusedSize,
.handle_ = SubmitHandle() };
}

Now we can implement the VulkanStagingDevice::bufferSubData() function. The main complexity here arises when the size of the data to upload is greater than the size of the staging buffer.

  1. If the destination buffer is host-visible, we simply perform a memory copy operation into it, as discussed in the previous recipe Dealing with buffers in Vulkan.
    void lvk::VulkanStagingDevice::bufferSubData(
    VulkanBuffer& buffer,
    size_t dstOffset,
    size_t size,
    const void* data)
    {
    if (buffer.isMapped()) {
    buffer.bufferSubData(ctx_, dstOffset, size, data);
    return;
    }
    lvk::VulkanBuffer* stagingBuffer =
    ctx_.buffersPool_.get(stagingBuffer_);
  2. We iterate while there’s still data left to upload. In each iteration, we attempt to acquire an available staging buffer memory region large enough to fit the remaining size. Based on the available space, we adjust the next chunk size accordingly. The staging buffer itself is always host-visible, allowing us to directly mem-copy the data into it using VulkanBuffer::bufferSubData() as explained earlier.
    while (size) {
    MemoryRegionDesc desc = getNextFreeOffset((uint32_t)size);
    const uint32_t chunkSize =
    std::min((uint32_t)size, desc.size_);
    stagingBuffer->bufferSubData(
    desc.srcOffset_, chunkSize, data);
  3. Acquire a command buffer and issue Vulkan commands to copy buffer data between the staging buffer and the destination buffer.
    const VulkanImmediateCommands::CommandBufferWrapper& wrapper =
    ctx_.immediate_->acquire();
    const VkBufferCopy copy = {
    .srcOffset = desc.offset_,
    .dstOffset = dstOffset,
    .size = chunkSize };
    vkCmdCopyBuffer(wrapper.cmdBuf_, stagingBuffer->vkBuffer_,
    buffer.vkBuffer_, 1, &copy);
  4. Before Vulkan can access data transferred by the command vkCmdCopyBuffer(), it requires a buffer memory barrier to ensure the transfer results become available. Here’s how we deduce different pipeline destination stage flags and memory access masks for the barrier based on the buffer usage flags. This approach is greedy and overspecifies the barrier but simplifies the high-level API and removes much of the burden from us.
    VkBufferMemoryBarrier barrier = {
    .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
    .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
    .dstAccessMask = 0,
    .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
    .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
    .buffer = buffer.vkBuffer_,
    .offset = dstOffset,
    .size = chunkSize,
    };
    VkPipelineStageFlags dstMask =
    VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
    if (buffer.vkUsageFlags_ &
    VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) {
    dstMask |= VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
    barrier.dstAccessMask |=
    VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
    }
    if (buffer.vkUsageFlags_ & VK_BUFFER_USAGE_INDEX_BUFFER_BIT) {
    dstMask |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
    barrier.dstAccessMask |= VK_ACCESS_INDEX_READ_BIT;
    }
    if (buffer.vkUsageFlags_ &VK_BUFFER_USAGE_VERTEX_BUFFER_BIT) {
    dstMask |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
    barrier.dstAccessMask |= VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
    }
    vkCmdPipelineBarrier(wrapper.cmdBuf_,
    VK_PIPELINE_STAGE_TRANSFER_BIT, dstMask,
    VkDependencyFlags{}, 0, nullptr, 1, &barrier, 0, nullptr);
    desc.handle_ = ctx_.immediate_->submit(wrapper);
  5. As the GPU is doing the copying, we add this memory region – together with its SubmitHandle – to the container of occupied memory regions.
    regions_.push_back(desc);
    size -= chunkSize;
    data = (uint8_t*)data + chunkSize;
    dstOffset += chunkSize;
    }
    }

Another crucial role of the staging buffer is to copy pixel data into Vulkan images. Let’s take a look at how it can be implemented. This function is significantly more complicated, so we omit all the error checking again here in the text for the sake of better understanding of the code.

  1. The imageData2D() function can upload multiple layers of an image in one go, starting from a specified layer, along with multiple mip-levels beginning from the baseMipLevel. LightweightVK assumes there’s a maximum possible number of mip-levels. We calculate the size in bytes for each mip-level. As we now the base mip-level that we want to update, we can calculate its dimensions from the Vulkan image extents by bit-shifting.
    void lvk::VulkanStagingDevice::imageData2D(
    VulkanImage& image,
    const VkRect2D& imageRegion,
    uint32_t baseMipLevel,
    uint32_t numMipLevels,
    uint32_t layer,
    uint32_t numLayers,
    VkFormat format,
    const void* data)
    {
    uint32_t width = image.vkExtent_.width >> baseMipLevel;
    uint32_t height = image.vkExtent_.height >> baseMipLevel;
    const Format texFormat(vkFormatToFormat(format));
  2. Now let us calculate per-layer storage sizes, which are necessary to accommodate all corresponding mip-levels of the image. The function getTextureBytesPerLayer() returns the size in bytes of a layer with the requested image format.
    uint32_t layerStorageSize = 0;
    for (uint32_t i = 0; i < numMipLevels; ++i) {
    const uint32_t mipSize = lvk::getTextureBytesPerLayer(
    image.vkExtent_.width, image.vkExtent_.height,
    texFormat, i);
    layerStorageSize += mipSize;
    width = width <= 1 ? 1 : width >> 1;
    height = height <= 1 ? 1 : height >> 1;
    }
    const uint32_t storageSize = layerStorageSize * numLayers;
  3. Now we know the size necessary to store the entire image data. Try to acquire the next memory region from the staging buffer. LightweightVK provides no support for copying image data in multiple smaller chunks. If we get a memory region smaller than storageSize, we should wait until a bigger memory region becomes available. One consequence of this is that LightweightVK is unable to upload images whose memory footprint is larger than the staging buffer size.
    ensureStagingBufferSize(storageSize);
    MemoryRegionDesc desc = getNextFreeOffset(storageSize);
    if (desc.size_ < storageSize) {
    waitAndReset();
    desc = getNextFreeOffset(storageSize);
    }
    LVK_ASSERT(desc.size_ >= storageSize);
  4. Now we can acquire a command buffer and copy the image data into the selected memory region in the staging buffer.
    const VulkanImmediateCommands::CommandBufferWrapper& wrapper =
    ctx_.immediate_->acquire();
    lvk::VulkanBuffer* stagingBuffer =
    ctx_.buffersPool_.get(stagingBuffer_);
    stagingBuffer->bufferSubData(
    ctx_, desc.offset_, storageSize, data);;
  5. LightweightVK supports uploading of multiplanar images, such as YUV images used for video decoding. However, we do not use this functionality in our book and will skip that part here due to the added complexity. We assume the number of image planes to be 1.
    uint32_t offset = 0;
    const uint32_t numPlanes = 1;
    VkImageAspectFlags imageAspect = VK_IMAGE_ASPECT_COLOR_BIT;
  6. Now we can iterate over the image’s mip-levels and layers and transition the image layout to VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, allowing us to use it as a destination in Vulkan transfer operations.
    for (uint32_t mipLevel = 0; mipLevel <numMipLevels; mipLevel++) {
    for (uint32_t layer = 0; layer != numLayers; layer++) {
    const uint32_t currentMipLevel = baseMipLevel + mipLevel;
    lvk::imageMemoryBarrier(
    wrapper.cmdBuf_,
    image.vkImage_,
    0,
    VK_ACCESS_TRANSFER_WRITE_BIT,
    VK_IMAGE_LAYOUT_UNDEFINED,
    VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
    VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
    VK_PIPELINE_STAGE_TRANSFER_BIT,
    VkImageSubresourceRange{
    imageAspect, currentMipLevel, 1, layer, 1});
  7. Copy the pixel data for this mip-level from the staging buffer into the corresponding Vulkan image subresource. The buffer offset for this mip-level is calculated by adding the size of all previous mip-levels being uploaded to the start of all mip-levels.
    const VkExtent2D extent = lvk::getImagePlaneExtent({
    .width = std::max(1u, imageRegion.extent.width >> mipLevel),
    .height = std::max(1u, imageRegion.extent.height >> mipLevel),
    },
    vkFormatToFormat(format), 0);
    const VkRect2D region = {
    .offset = {.x = imageRegion.offset.x >> mipLevel,
    .y = imageRegion.offset.y >> mipLevel},
    .extent = extent,
    };
  8. The bufferOffset value for this level is calculated by adding the size of all previous mip-levels being uploaded to the start of the mip-levels data.
    const VkBufferImageCopy copy = {
    .bufferOffset = desc.offset_ + offset,
    .bufferRowLength = 0,
    .bufferImageHeight = 0,
    .imageSubresource = VkImageSubresourceLayers{
    imageAspect, currentMipLevel, layer, 1},
    .imageOffset = { .x = region.offset.x,
    .y = region.offset.y,
    .z = 0},
    .imageExtent = { .width = region.extent.width,
    .height = region.extent.height,
    .depth = 1u },
    };
    vkCmdCopyBufferToImage(wrapper.cmdBuf_,
    stagingBuffer->vkBuffer_, image.vkImage_,
    VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy);
  9. Once the mip-level and layer are uploaded, we transition the subresource image layout from VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL to VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL. This ensures the image is ready for use in the normal rendering pipeline, as any subsequent operations in LightweightVK expect this layout.

Note

The Vulkan image layout is a property of each image subresource that defines how the data in memory is organized in a manner that is opaque to the user and specific to the Vulkan drivers. Correctly specifying the layout for various use cases is crucial; failing to do so can lead to undefined behavior, such as distorted images, because Vulkan can use this information to optimize memory access when the image is used.

lvk::imageMemoryBarrier(
wrapper.cmdBuf_,
image.vkImage_,
VK_ACCESS_TRANSFER_WRITE_BIT,
VK_ACCESS_SHADER_READ_BIT,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VkImageSubresourceRange{
imageAspect, currentMipLevel, 1, layer, 1});
  1. Advance the buffer offset to the next mip-level and layer.
    offset += lvk::getTextureBytesPerLayer(
    imageRegion.extent.width, imageRegion.extent.height,
    texFormat, currentMipLevel);
    }
    }
  2. Once the Vulkan commands are recorded in the command buffer, we submit it to copy the image data. Before exiting, we set the last image layout to VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL to ensure that future layout transitions are based on this information. It’s important to note that LightweightVK tracks the layout for the entire VkImage, not for its individual subresources. It is a tradeoff that simplifies handling and avoids the complexity of managing layouts for every individual subresource, but it can be a performance issue in some situations.

Note

This approach might lead to unnecessary image layout transitions or suboptimal memory usage if the image is accessed in ways that require different layouts for individual subresources. However, for many use cases, this simplification provides a good balance between ease of use and performance.

image.vkImageLayout_ = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
desc.handle_ = ctx_.immediate_->submit(wrapper);
regions_.push_back(desc);
}

This concludes the discussion on the staging buffers implementation and the process of uploading device-local buffer data and images via them. This technique is a critical part of working with Vulkan, especially when the GPU’s device-local memory is not directly accessible by the CPU.

LightweightVK includes a function VulkanStagingDevice::imageData3D() to upload 3D texture data using a staging buffer. This function, found in lvk/vulkan/VulkanClasses.cpp, follows a similar process as the 2D texture upload. Make sure to explore it.

A Vulkan memory heap can have the flags VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT. Some GPUs have a separate, relatively small memory heap with these properties, while others have the entire device memory marked as host-visible. This feature is known as Resizable BAR (ReBAR), which allows the CPU to access GPU device memory. If your system has such a memory heap, you can use it to directly write data to GPU local memory. Or, for example, you could allocate a staging buffer in that memory. If you want to learn more about Vulkan memory types and how to use them, here’s an excellent article by Adam Sawicki: https://asawicki.info/news_1740_vulkan_memory_types_on_pc_and_how_to_use_them.

Now that we have everything we need, let’s move on to the next recipe and learn how to use Vulkan images to create textures.

Before we can create meaningful 3D rendering applications with Vulkan, we need to understand how to work with textures. This recipe shows how to implement several functions for creating, destroying, and modifying texture objects, as well as managing the corresponding VkImage and VkImageView objects using the Vulkan API.

Uploading texture data to the GPU requires a staging buffer. Be sure to read the previous recipe, Implementing staging buffers, before continuing.

The source code for this recipe can be found in Chapter03/02_STB.

A Vulkan image is a type of object backed by memory, designed to store 1D, 2D, or 3D images, or arrays of these images. Readers familiar with OpenGL might wonder about cube maps. Cube maps are represented as an array of six 2D images and can be created by setting the VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT flag in the VkImageCreateInfo structure. We’ll revisit that later. For now, let’s focus on the basic use case with a 2D image. Again, we’ll begin with the high-level application code and work our way down to Vulkan image allocation.

  1. The application in Chapter03/02_STB loads pixel data from a .jpg file using the STB library https://github.com/nothings/stb. We enforce a conversion to 4 channels to simplify texture handling, as many Vulkan implementations do not support 3 -channel images.
    int w, h, comp;
    const uint8_t* img = stbi_load(
    "data/wood.jpg", &w, &h, &comp, 4);
  2. A handle to a texture object is created. Internally, our texture consists of a combination of VkImage and VkImageView, which we’ll examine shortly. The texture format is normalized unsigned 8-bit RGBA, corresponding to the Vulkan format VK_FORMAT_R8G8B8A8_UNORM. Since we intend to use this texture for sampling in shaders, we specify the texture usage flag TextureUsageBits_Sampled. Once the texture is created, do not forget to free the image memory.
    Holder<TextureHandle> texture = ctx->createTexture({
    .type = lvk::TextureType_2D,
    .format = lvk::Format_RGBA_UN8,
    .dimensions = { (uint32_t)w, (uint32_t)h },
    .usage = lvk::TextureUsageBits_Sampled,
    .data = img,
    .debugName = "03_STB.jpg",
    });
    stbi_image_free((void*)img);
  3. Let’s take a look at the main loop. LightweightVK is built around a bindless renderer design. Bindless rendering is a technique that enables more efficient GPU resource management by eliminating the need to explicitly bind resources like textures, buffers, or samplers. We’ll explore how this works in the recipe Using Vulkan descriptor sets later in this chapter. For now, here’s how we can pass texture data into shaders using push constants. After that, we render a quad formed by 4 triangle strip vertices.
    while (!glfwWindowShouldClose(window)) {
    // ... skipped GLFW code and matrices setup
    const struct PerFrameData {
    mat4 mvp;
    uint32_t textureId;
    } pc = {
    .mvp = p * m,
    .textureId = texture.index(),
    };
    lvk::ICommandBuffer& buf = ctx->acquireCommandBuffer();
    // …
    buf.cmdBindRenderPipeline(pipeline);
    buf.cmdPushConstants(pc);
    buf.cmdDraw(4);
    // …
    }
  4. The vertices are generated directly in the vertex shader, without any vertex input, in Chapter03/02_STB/src/main.vert, which looks as follows.
    #version 460 core
    layout(push_constant) uniform PerFrameData {
    uniform mat4 MVP;
    uint textureId;
    };
    layout (location=0) out vec2 uv;
    const vec2 pos[4] = vec2[4](
    vec2( 1.0, -1.0), vec2( 1.0, 1.0),
    vec2(-1.0, -1.0), vec2(-1.0, 1.0)
    );
    void main() {
    gl_Position = MVP * vec4(0.5 * pos[gl_VertexIndex], 0.0, 1.0);
    uv = 0.5 * (pos[gl_VertexIndex]+vec2(0.5));
    }
  5. The fragment shader is much more interesting. We need to declare an array of 2D textures, kTextures2D[], and an array of samplers, kSamplers[], both provided by LightweightVK. These arrays contain all the textures and samplers loaded at the current moment. The element at index 0 in both arrays corresponds to a dummy object, which is useful for safely handling null values as texture identifiers without branching. Our push constant, textureId, is simply an index into the kTextures2D[] array.
    #version 460 core
    #extension GL_EXT_nonuniform_qualifier : require
    layout (set = 0, binding = 0) uniform texture2D kTextures2D[];
    layout (set = 0, binding = 1) uniform sampler kSamplers[];
    layout (location=0) in vec2 uv;
    layout (location=0) out vec4 out_FragColor;
    layout(push_constant) uniform PerFrameData {
    uniform mat4 MVP;
    uint textureId;
    };
  6. Here’s a handy helper function, textureBindless2D(), that allows us to sample from a bindless 2D texture using a bindless sampler. We’ll use this function instead of the standard GLSL texture() to efficiently sample a texture.

Note

Here, we’ve provided the entire fragment shader GLSL source code ourselves. If we omit the #version directive at the beginning of the shader, LightweightVK will automatically inject this and many other helper functions into our GLSL source, along with kTextures2D[] and other declarations. We’ll use this feature in later chapters to simplify our GLSL code and avoid code duplication in the shaders. We’re listing this function here purely for educational purposes.

vec4 textureBindless2D(uint textureid, uint samplerid, vec2 uv) {
return texture(nonuniformEXT(
sampler2D(kTextures2D[textureid], kSamplers[samplerid])), uv);
}
void main() {
out_FragColor = textureBindless2D(textureId, 0, uv);
}

Note

When our texture indices are not dynamically uniform, the nonuniformEXT type qualifier must be used when indexing descriptor bindings, as required by the Vulkan API. It’s important to note that, to be fully correct, we must use nonuniformEXT(sampler2D()). The final argument in a function call like texture() determines whether the access is considered non-uniform.

The resulting application, Chapter03/02_STB, should render a textured, rotating quad, as shown in the following screenshot.

Figure 3.3: Rendering a textured quad

The high-level part was brief and straightforward, hiding all the Vulkan complexity from us. Now, let’s take a deep breath and prepare for a deep dive into the underlying Vulkan API implementation to understand how it works.

Vulkan textures, namely images and image views, are complex. Along with descriptor sets, they are essential for accessing texture data in shaders. The LightweightVK implementation of textures involves multiple layers. Let’s peel them back and examine each one to understand how they work.

The tip of the iceberg is the function VulkanContext::createTexture(), which returns a handle to a texture. The function is quite lengthy, so we’re omitting the error-checking code here to make it easier to understand.

  1. This function converts a LightweightVK texture description, TextureDesc, into various Vulkan flags for images and image views. The additional argument, debugName, provides a convenient way to override the TextureDesc::debugName field. This is particularly useful when creating multiple textures using the same TextureDesc object.
    struct TextureDesc {
    TextureType type = TextureType_2D;
    Format format = Format_Invalid;
    Dimensions dimensions = {1, 1, 1};
    uint32_t numLayers = 1;
    uint32_t numSamples = 1;
    uint8_t usage = TextureUsageBits_Sampled;
    uint32_t numMipLevels = 1;
    StorageType storage = StorageType_Device;
    ComponentMapping swizzle = {};
    const void* data = nullptr;
  2. This field defines how many mip-levels we want to upload. It’s useful when we only want to upload the first mip-level from the data member field and generate all the remaining mip-levels automatically. The generateMipmaps field forces the generation of all remaining mip-levels and works only when the data pointer is non-null.
    uint32_t dataNumMipLevels = 1;
    bool generateMipmaps = false;
    const char* debugName = "";
    };
    Holder<TextureHandle> VulkanContext::createTexture(
    const TextureDesc& requestedDesc,
    const char* debugName,
    Result* outResult)
    {
    TextureDesc desc(requestedDesc);
    if (debugName && *debugName) desc.debugName = debugName;
  3. Convert a LightweightVK image format into the Vulkan format. Vulkan provides stronger guarantees regarding the support of color formats, so depth formats are converted based on actual availability, while color formats are converted as-is.
    const VkFormat vkFormat =
    lvk::isDepthOrStencilFormat(desc.format) ?
    getClosestDepthStencilFormat(desc.format) :
    formatToVkFormat(desc.format);
    const lvk::TextureType type = desc.type;
  4. If the image is going to be allocated in the GPU device memory, we should set the VK_IMAGE_USAGE_TRANSFER_DST_BIT to allow Vulkan to transfer data into it. Other Vulkan image usage flags are set according to the LightweightVK usage flags.
    VkImageUsageFlags usageFlags =
    (desc.storage == StorageType_Device) ?
    VK_IMAGE_USAGE_TRANSFER_DST_BIT : 0;
    if (desc.usage & lvk::TextureUsageBits_Sampled) {
    usageFlags |= VK_IMAGE_USAGE_SAMPLED_BIT;
    }
    if (desc.usage & lvk::TextureUsageBits_Storage) {
    usageFlags |= VK_IMAGE_USAGE_STORAGE_BIT;
    }
    if (desc.usage & lvk::TextureUsageBits_Attachment) {
    usageFlags |= lvk::isDepthOrStencilFormat(desc.format) ?
    VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT :
    VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  5. Memoryless images correspond to Vulkan transient attachments and lazily allocated memory, meaning transient attachments used during a single render pass do not require physical storage. This is particularly useful for MSAA multisampling, and we will explore it further in Chapter 10. For convenience, we always allow an image to be read back from the GPU to the CPU by setting VK_IMAGE_USAGE_TRANSFER_SRC_BIT for everything except transient attachments. However, it’s worth verifying if this image usage flag is supported for the specific image format. The memory property flags are chosen in the same way as described earlier in the recipe Dealing with buffers in Vulkan.
    if (desc.storage == lvk::StorageType_Memoryless) {
    usageFlags |= VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT;
    }
    }
    if (desc.storage != lvk::StorageType_Memoryless) {
    usageFlags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
    };
    const VkMemoryPropertyFlags memFlags =
    storageTypeToVkMemoryPropertyFlags(desc.storage);
  6. Generate debug names for Vulkan image and image view objects by prefixing the provided debugName string. This is crucial when using debugging tools like RenderDoc or Vulkan Validation Layers.
    const bool hasDebugName = desc.debugName && *desc.debugName;
    char debugNameImage[256] = {0};
    char debugNameImageView[256] = {0};
    if (hasDebugName) {
    snprintf(debugNameImage, sizeof(debugNameImage) - 1,
    "Image: %s", desc.debugName);
    snprintf(debugNameImageView, sizeof(debugNameImageView) - 1,
    "Image View: %s", desc.debugName);
    }
  7. Now we can proceed to determine the VkImageCreateFlags and the types of the Vulkan image and image view. Note that 2D images can be multisampled https://en.wikipedia.org/wiki/Multisample_anti-aliasing. We will use multisampling in Chapter 10.
    VkImageCreateFlags vkCreateFlags = 0;
    VkImageViewType vkImageViewType;
    VkImageType vkImageType;
    VkSampleCountFlagBits vkSamples = VK_SAMPLE_COUNT_1_BIT;
    uint32_t numLayers = desc.numLayers;
    switch (desc.type) {
    case TextureType_2D:
    vkImageViewType = numLayers > 1 ?
    VK_IMAGE_VIEW_TYPE_2D_ARRAY :
    VK_IMAGE_VIEW_TYPE_2D;
    vkImageType = VK_IMAGE_TYPE_2D;
    vkSamples = lvk::getVulkanSampleCountFlags(
    desc.numSamples, getFramebufferMSAABitMask());
    break;
    case TextureType_3D:
    vkImageViewType = VK_IMAGE_VIEW_TYPE_3D;
    vkImageType = VK_IMAGE_TYPE_3D;
    break;
  8. In Vulkan, cube textures are represented by an image view of type VK_IMAGE_VIEW_TYPE_CUBE and a 2D image with the VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT flag. The number of layers is multiplied by 6 to account for all cube map faces, as required by the Vulkan API specification.
    case TextureType_Cube:
    vkImageViewType = numLayers > 1 ?
    VK_IMAGE_VIEW_TYPE_CUBE_ARRAY : VK_IMAGE_VIEW_TYPE_CUBE;
    vkImageType = VK_IMAGE_TYPE_2D;
    vkCreateFlags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
    numLayers *= 6;
    break;
    }
  9. Now we can create a wrapper object, VulkanImage, which encapsulates all the necessary VkImage -related properties. We’ll examine its remaining members in a moment.
    const VkExtent3D vkExtent{
    desc.dimensions.width,
    desc.dimensions.height,
    desc.dimensions.depth };
    const uint32_t numLevels = desc.numMipLevels;
    lvk::VulkanImage image = {
    .vkUsageFlags_ = usageFlags,
    .vkExtent_ = vkExtent,
    .vkType_ = vkImageType,
    .vkImageFormat_ = vkFormat,
    .vkSamples_ = vkSamples,
    .numLevels_ = numLevels,
    .numLayers_ = numLayers,
    .isDepthFormat_ = VulkanImage::isDepthFormat(vkFormat),
    .isStencilFormat_ = VulkanImage::isStencilFormat(vkFormat),
    };
    More information Here’s the declaration of the VulkanImage structure for your convenience, with some minor parts omitted. Setting numLevels to a non-zero value will override the number of mip-levels from the original Vulkan image and can be used to create image views with a different number of levels.
    struct VulkanImage final {
    VkImageView createImageView(
    VkDevice device,
    VkImageViewType type,
    VkFormat format,
    VkImageAspectFlags aspectMask,
    uint32_t baseLevel,
    uint32_t numLevels = VK_REMAINING_MIP_LEVELS,
    uint32_t baseLayer = 0,
uint32_t numLayers = 1,
const VkComponentMapping mapping = {
.r = VK_COMPONENT_SWIZZLE_IDENTITY,
.g = VK_COMPONENT_SWIZZLE_IDENTITY,
.b = VK_COMPONENT_SWIZZLE_IDENTITY,
.a = VK_COMPONENT_SWIZZLE_IDENTITY },
const VkSamplerYcbcrConversionInfo* ycbcr = nullptr,
const char* debugName = nullptr) const;
VkImageView getOrCreateVkImageViewForFramebuffer(
VulkanContext& ctx, uint8_t level, uint16_t layer);
// ...
VkImage vkImage_ = VK_NULL_HANDLE;
VkImageUsageFlags vkUsageFlags_ = 0;
VkDeviceMemory vkMemory_[1] = {VK_NULL_HANDLE };
VmaAllocation vmaAllocation_ = VK_NULL_HANDLE;
VkFormatProperties vkFormatProperties_ = {};
VkExtent3D vkExtent_ = {0, 0, 0};
VkImageType vkType_ = VK_IMAGE_TYPE_MAX_ENUM;
VkFormat vkImageFormat_ = VK_FORMAT_UNDEFINED;
VkSampleCountFlagBits vkSamples_ = VK_SAMPLE_COUNT_1_BIT;
void* mappedPtr_ = nullptr;
bool isSwapchainImage_ = false;
bool isOwningVkImage_ = true;
uint32_t numLevels_ = 1u;
uint32_t numLayers_ = 1u;
bool isDepthFormat_ = false;
bool isStencilFormat_ = false;
// current image layout
mutable VkImageLayout vkImageLayout_ =
VK_IMAGE_LAYOUT_UNDEFINED;
// precached image views - owned by this VulkanImage
VkImageView imageView_ = VK_NULL_HANDLE; // all levels
VkImageView imageViewStorage_ =
VK_NULL_HANDLE; // identity swizzle
VkImageView
imageViewForFramebuffer_[LVK_MAX_MIP_LEVELS][6] = {};
};

As you can see, the VulkanImage structure is simply a data container. One interesting part is the getOrCreateVkImageViewForFramebuffer() member function. Image views used as framebuffer attachments should have only 1 mip-level and 1 layer. This function precaches such image views inside the array imageViewForFramebuffer_[][]. It supports a maximum of 6 layers, which is just enough for rendering to the faces of a cube map.

  1. To create a VkImage object, we need to fill out the VkImageCreateInfo structure and call vmaCreateImage() or use the raw Vulkan API directly. The image creation code in LightweightVK includes a code path for handling multiplanar images, but we will omit that part in this book. LightweightVK does not work with multiple Vulkan queues so it sets the sharing mode to VK_SHARING_MODE_EXCLUSIVE.
    const VkImageCreateInfo ci = {
    .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
    .flags = vkCreateFlags,
    .imageType = vkImageType,
    .format = vkFormat,
    .extent = vkExtent,
    .mipLevels = numLevels,
    .arrayLayers = numLayers,
    .samples = vkSamples,
    .tiling = VK_IMAGE_TILING_OPTIMAL,
    .usage = usageFlags,
    .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
    .queueFamilyIndexCount = 0,
    .pQueueFamilyIndices = nullptr,
    .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
    };
  2. Similar to how we handled buffers in the recipe Dealing with buffers in Vulkan, we have two code paths for Vulkan images. One uses the Vulkan Memory Allocator library, while the other calls Vulkan directly to allocate memory. This provides a useful option for debugging purposes. We can have memory-mapped images in the same way we have memory-mapped buffers. However, this is only useful for non-tiled image layouts.
    if (LVK_VULKAN_USE_VMA) {
    VmaAllocationCreateInfo vmaAllocInfo = {
    .usage = memFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT ?
    VMA_MEMORY_USAGE_CPU_TO_GPU : VMA_MEMORY_USAGE_AUTO,
    };
    vmaCreateImage((VmaAllocator)getVmaAllocator(), &ci,
    &vmaAllocInfo, &image.vkImage_,
    &image.vmaAllocation_, nullptr);
    if (memFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
    vmaMapMemory((VmaAllocator)getVmaAllocator(),
    image.vmaAllocation_, &image.mappedPtr_);
    }
    }
  3. When creating a VkImage object using the raw Vulkan API, we need to manually allocate memory for it. Here, we only use the code path for a single image plane. To learn how to extend this for multiplanar images, refer to the implementation in lvk/vulkan/VulkanClasses.cpp.
    else {
    const uint32_t numPlanes = 1; // simplified code path
    vkCreateImage(vkDevice_, &ci, nullptr, &image.vkImage_);
    constexpr uint32_t kNumMaxImagePlanes = 1;
    VkMemoryRequirements2 memRequirements[kNumMaxImagePlanes] = {
    { .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2 },
    };
    const VkImagePlaneMemoryRequirementsInfo
    planes[kNumMaxImagePlanes] = {
    { .sType = VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO,
    .planeAspect = VK_IMAGE_ASPECT_PLANE_0_BIT },
    };
    const VkImage img = image.vkImage_;
    const VkImageMemoryRequirementsInfo2
    imgRequirements[kNumMaxImagePlanes] = {
    { .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
    .pNext = numPlanes > 0 ? &planes[0] : nullptr,
    .image = img },
    };
    for (uint32_t p = 0; p != numPlanes; p++) {
    vkGetImageMemoryRequirements2(vkDevice_,
    &imgRequirements[p], &memRequirements[p]);
    lvk::allocateMemory2(vkPhysicalDevice_, vkDevice_,
    &memRequirements[p], memFlags, &image.vkMemory_[p]));
    }
    const VkBindImagePlaneMemoryInfo
    bindImagePlaneMemoryInfo[kNumMaxImagePlanes] = {
    { .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO,
    .planeAspect = VK_IMAGE_ASPECT_PLANE_0_BIT },
    };
    const VkBindImageMemoryInfo bindInfo[kNumMaxImagePlanes] = {
    lvk::getBindImageMemoryInfo(
    nullptr, img, image.vkMemory_[0]),
    };
  4. Note that memory can only be bound to a VkImage once. Therefore, the code above handles binding disjoint memory locations in a single call to vkBindMemory2() by chaining everything together using pNext pointers. For details on handling multiplanar images, refer to the implementation in lvk/vulkan/VulkanClasses.cpp.
    vkBindImageMemory2(vkDevice_, numPlanes, bindInfo);
    if (memFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT &&
    numPlanes == 1) {
    vkMapMemory(vkDevice_, image.vkMemory_[0], 0,
    VK_WHOLE_SIZE, 0, &image.mappedPtr_);
    }
    }
  5. Once the VkImage object is created, we can set its debug name and store its format properties in our VulkanImage structure.
    lvk::setDebugObjectName(vkDevice_, VK_OBJECT_TYPE_IMAGE,
    (uint64_t)image.vkImage_, debugNameImage);
    vkGetPhysicalDeviceFormatProperties(vkPhysicalDevice_,
    image.vkImageFormat_, &image.vkFormatProperties_);
  6. To access a Vulkan image from shaders, we need to create a VkImageView object. In doing so, we must decide which image “aspect” should be included in the view. Vulkan images can have multiple aspects simultaneously, such as combined depth-stencil images, where depth and stencil bits are handled separately. Additionally, Vulkan supports image view component swizzling, which we’ll explore in Chapter 10. For now, here’s the code to initialize it.
    VkImageAspectFlags aspect = 0;
    if (image.isDepthFormat_ || image.isStencilFormat_) {
    if (image.isDepthFormat_) {
    aspect |= VK_IMAGE_ASPECT_DEPTH_BIT;
    } else if (image.isStencilFormat_) {
    aspect |= VK_IMAGE_ASPECT_STENCIL_BIT;
    }
    } else {
    aspect = VK_IMAGE_ASPECT_COLOR_BIT;
    }
    const VkComponentMapping mapping = {
    .r = VkComponentSwizzle(desc.swizzle.r),
    .g = VkComponentSwizzle(desc.swizzle.g),
    .b = VkComponentSwizzle(desc.swizzle.b),
    .a = VkComponentSwizzle(desc.swizzle.a),
    };
  7. An image view can control which mip-levels and layers are included. Here, we create an image view that includes all levels and layers of the image. Later, we’ll need separate image views for framebuffer attachments, which will contain only one layer and one mip-level. Storage images do not support swizzling, so we need to create a separate image view for them.
    image.imageView_ = image.createImageView(
    vkDevice_, vkImageViewType, vkFormat, aspect, 0,
    VK_REMAINING_MIP_LEVELS, 0, numLayers,
    mapping, nullptr, debugNameImageView);
    if (image.vkUsageFlags_ & VK_IMAGE_USAGE_STORAGE_BIT) {
    if (!desc.swizzle.identity()) {
    image.imageViewStorage_ = image.createImageView(
    vkDevice_, vkImageViewType, vkFormat, aspect, 0,
    VK_REMAINING_MIP_LEVELS, 0, numLayers,
    {}, nullptr, debugNameImageView);
    }
    }
  8. LightweightVK refers to a pair of objects— VkImage, wrapped in the VulkanImage struct, and VkImageView —as a texture. The Boolean flag awaitingCreation_ signals to VulkanContext that a texture has been created and that the bindless descriptor set needs to be updated. We’ll explore this further in the recipe Using Vulkan descriptor indexing. Before returning the texture handle of the newly created texture, let’s upload the initial texture data.
    TextureHandle handle = texturesPool_.create(std::move(image));
    awaitingCreation_ = true;
    if (desc.data) {
    const uint32_t numLayers = desc.type==TextureType_Cube ? 6:1;
    upload(handle, {.dimensions = desc.dimensions,
    .numLayers = numLayers,
    .numMipLevels = desc.dataNumMipLevels},
    desc.data);
    if (desc.generateMipmaps) this->generateMipmap(handle);
    }
    return {this, handle};
    }
  9. Now that we’ve created a texture, one major step we omitted is the actual process of creating VkImageView objects. Here’s the function VulkanImage::createImageView() that handles this. This function does not use any wrappers and creates a VkImageView object directly. It supports working with Vulkan YCbCr samplers, but this functionality is not used in the book samples, so we’ll omit it here (together with the error checking code).
    VkImageView lvk::VulkanImage::createImageView(
    VkDevice device,
    VkImageViewType type,
    VkFormat format,
    VkImageAspectFlags aspectMask,
    uint32_t baseLevel,
    uint32_t numLevels,
    uint32_t baseLayer,
    uint32_t numLayers,
    const VkComponentMapping mapping,
    const VkSamplerYcbcrConversionInfo* ycbcr,
    const char* debugName) const
    {
    const VkImageViewCreateInfo ci = {
    .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
    .pNext = ycbcr,
    .image = vkImage_,
    .viewType = type,
    .format = format,
    .components = mapping,
    .subresourceRange = { aspectMask, baseLevel,
    numLevels ? numLevels : numLevels_, baseLayer, numLayers},
    };
    VkImageView vkView = VK_NULL_HANDLE;
    vkCreateImageView(device, &ci, nullptr, &vkView);
    lvk::setDebugObjectName(device, VK_OBJECT_TYPE_IMAGE_VIEW,
    (uint64_t)vkView, debugName);
    return vkView;
    }
  10. Another important aspect is the destruction of VulkanImage objects we created. The VulkanContext::destroy() function handles this and is called from the RAII wrapper Holder<TextureHandle>. Here it is for completeness, with multiplanar image support and error checking removed.
    void lvk::VulkanContext::destroy(lvk::TextureHandle handle) {
    SCOPE_EXIT {
    texturesPool_.destroy(handle);
    awaitingCreation_ = true;
    };
    lvk::VulkanImage* tex = texturesPool_.get(handle);
    if (!tex) return;
    deferredTask(std::packaged_task<void()>(
    [device = getVkDevice(),
    imageView = tex->imageView_]() {
    vkDestroyImageView(device, imageView, nullptr); }));
    if (tex->imageViewStorage_) {
    deferredTask(std::packaged_task<void()>(
    [device = getVkDevice(),
    imageView = tex->imageViewStorage_]() {
    vkDestroyImageView(device, imageView, nullptr); }));
    }
    for (size_t i = 0; i != LVK_MAX_MIP_LEVELS; i++) {
    for (size_t j = 0; j != LVK_ARRAY_NUM_ELEMENTS(
    tex->imageViewForFramebuffer_[0]); j++)
    {
    VkImageView v = tex->imageViewForFramebuffer_[i][j];
    if (v) {
    deferredTask(std::packaged_task<void()>(
    [device = getVkDevice(), imageView = v]() {
    vkDestroyImageView(device, imageView, nullptr); }));
    }
    }
    }
    if (!tex->isOwningVkImage_) return;
    if (LVK_VULKAN_USE_VMA) {
    if (tex->mappedPtr_) vmaUnmapMemory(
    (VmaAllocator)getVmaAllocator(), tex->vmaAllocation_);
    deferredTask(std::packaged_task<void()>(
    [vma = getVmaAllocator(),
    image = tex->vkImage_,
    allocation = tex->vmaAllocation_]() {
    vmaDestroyImage((VmaAllocator)vma, image, allocation);
    }));
    } else {
    if (tex->mappedPtr_)
    vkUnmapMemory(vkDevice_, tex->vkMemory_[0]);
    deferredTask(std::packaged_task<void()>(
    [device = vkDevice_,
    image = tex->vkImage_,
    memory0 = tex->vkMemory_[0]]() {
    vkDestroyImage(device, image, nullptr);
    if (memory0) vkFreeMemory(device, memory0, nullptr);
    }
    }));
    }
    }

While technically all of the above code is sufficient to create VkImage and VkImageView objects, we still cannot access them from shaders. To do that, we need to learn how to store these objects and how to put them into Vulkan descriptor sets. Let’s move on to the next recipes to explore this.

You may have noticed that the Boolean flag VulkanImage::isOwningVkImage_ prevents the VulkanContext::destroy(TextureHandle) function from destroying the VkImage and VkDeviceMemory objects. This allows us to create as many non-owning copies of a VulkanImage object as we need, which is very useful when we want to create multiple custom image views of the same VkImage. Check the method VulkanContext::createTextureView(), which is also a part of the IContext interface, to learn how to do this. We will use this functionality in Chapters 10 and 11.

In the previous recipes, we mentioned a plethora of lvk::…Handle classes wrapped into a templated unique-pointer-like class Holder<>. These are central to how LightweightVK manages Vulkan objects and other resources. Handles are lightweight value types that are inexpensive to pass around as integers, and we don’t incur the overhead of shared ownership with atomic counters, as we would with std::shared_ptr or other reference-counted smart pointers. When ownership of an object is desirable, we wrap handles into the Holder<> class, which is a RAII wrapper and conceptually resembles std::unique_ptr.

The LightweightVK implementation of handles is inspired by Sebastian Aaltonen`s SIGGRAPH 2023 presentation HypeHype Mobile Rendering Architecture. If you want to learn more low-level interesting details about an API design using handles, make sure to read it: https://advances.realtimerendering.com/s2023/AaltonenHypeHypeAdvances2023.pdf

Let’s learn how to implement lightweight handles, which are represented by a templated class Handle<>.

  1. Handles are designed to serve akin pointers to objects which are stored in arrays. An index into an array is sufficient to identify an object. To handle situations where objects are deallocated and then replaced by new ones, we introduce a value gen_ which represents object`s “generation” and is incremented each time a new object is assign to the same element in the storage array.
    template<typename ObjectType> class Handle final {
    uint32_t index_ = 0;
    uint32_t gen_ = 0;
  2. These values are private so that handles can be constructed only by a friendly Pool<> class. The Pool<> class is templated and is parametrized by two types, one corresponds to the handle`s object type and the other is the type stored inside the implementation array. It is not visible from the Handle<> interface and cannot be used without a Pool<> object.
    Handle(uint32_t index, uint32_t gen) :
    index_(index), gen_(gen){};
    template<typename ObjectType,
    typename ImplObjectType> friend class Pool;
    public:
    Handle() = default;
  3. The interface contract is that handles with a generation equal to zero are considered empty null-handles.
    bool empty() const { return gen_ == 0; }
    bool valid() const { return gen_ != 0; }
    uint32_t index() const { return index_; }
    uint32_t gen() const { return gen_; }
  4. The indexAsVoid() function is helpful when we need to pass a handle through some third-party C-style interface which accepts void* parameters. One example used in this book would be ImGui integration which is discussed in the next chapter Adding User Interaction and Productivity Tools.
    void* indexAsVoid() const {
    return reinterpret_cast<void*>(
    static_cast<ptrdiff_t>(index_));
    }
    bool operator==(const Handle<ObjectType>& other) const
    { return index_ == other.index_ && gen_ == other.gen_; }
    bool operator!=(const Handle<ObjectType>& other) const
    { return index_ != other.index_ || gen_ != other.gen_; }
  5. The explicit conversion to bool is necessary to allow usage of handles in conditional statements such as if (handle) {…}. We also ensure the size of Handle<> is 8 bytes.
    explicit operator bool() const { return gen_ != 0; }
    };
    static_assert(sizeof(Handle<class Foo>) == sizeof(uint64_t));
  6. The Handle<> template can be parameterized with a forward-declared type that does not have an actual complete definition. Such types are known as “tags.” This ensures type safety, preventing heterogeneous handles from being mixed with each other. Here’s how LightweightVK declares all its Handle<> types. The structs ComputePipeline, RenderPipeline, and others do not exist.
    using ComputePipelineHandle = Handle<struct ComputePipeline>;
    using RenderPipelineHandle = Handle<struct RenderPipeline>;
    using ShaderModuleHandle = Handle<struct ShaderModule>;
    using SamplerHandle = Handle<struct Sampler>;
    using BufferHandle = Handle<struct Buffer>;
    using TextureHandle = Handle<struct Texture>;
    using QueryPoolHandle = Handle<struct QueryPool>;

Handles do not own objects they point to. Only the Holder<> class does. Let’s take a look at its implementation.

  1. The Holder<> class is templated with a Handle type it can hold. The constructor accepts a handle and a pointer to lvk::IContext to ensure the handle can be destroyed properly. The class has move-only semantics similar to std::unique_ptr. We skip definitions of the move-constructor and move-assignment for the sake of brevity.
    template<typename HandleType> class Holder final {
    public:
    Holder() = default;
    Holder(lvk::IContext* ctx, HandleType handle)
    : ctx_(ctx), handle_(handle) {}
  2. We do not have a declaration of the IContext class here. That is why we use an overloaded forward-declared function lvk::destroy() to deallocate the handle. There should be one lvk::destroy() overload for each type we want to instantiate the Holder<> class with.
    ~Holder() { lvk::destroy(ctx_, handle_); }
    Holder(const Holder&) = delete;
    Holder(Holder&& other)
    : ctx_(other.ctx_)
    , handle_(other.handle_) { ... }
    Holder& operator=(const Holder&) = delete;
    Holder& operator=(Holder&& other) { … }
  3. Assigning nullptr to this Holder<>.
    Holder& operator=(std::nullptr_t) { reset(); return *this; }
    inline operator HandleType() const { return handle_; }
    bool valid() const { return handle_.valid(); }
    bool empty() const { return handle_.empty(); }
  4. Manually reset this Holder<> and make it deallocate the stored handle or just return the handle and release ownership when necessary.
    void reset() {
    lvk::destroy(ctx_, handle_);
    ctx_ = nullptr;
    handle_ = HandleType{};
    }
    HandleType release() {
    ctx_ = nullptr;
    return std::exchange(handle_, HandleType{});
    }
    uint32_t index() const { return handle_.index(); }
    void* indexAsVoid() const { return handle_.indexAsVoid(); }
    private:
    lvk::IContext* ctx_ = nullptr;
    HandleType handle_;
    };
  5. The Holder class calls a family of overloaded destroy() functions. Here is how LightweightVK defines them. One function per each handle type.
    void destroy(lvk::IContext* ctx, ComputePipelineHandle handle);
    void destroy(lvk::IContext* ctx, RenderPipelineHandle handle);
    void destroy(lvk::IContext* ctx, ShaderModuleHandle handle);
    void destroy(lvk::IContext* ctx, SamplerHandle handle);
    void destroy(lvk::IContext* ctx, BufferHandle handle);
    void destroy(lvk::IContext* ctx, TextureHandle handle);
    void destroy(lvk::IContext* ctx, QueryPoolHandle handle);
  6. Implementations of these functions are located in lightweightvk/lvk/LVK.cpp and they all look very similar. Each function calls a corresponding overloaded method in IContext. While it may seem unnecessary, this actually helps to avoid a circular dependency between the Holder<> class and IContext, making the interface much cleaner.
    void destroy(lvk::IContext* ctx, ComputePipelineHandle handle) {
    if (ctx) ctx->destroy(handle);
    }
    // ... same for other handle types

That is all there is to discuss about the Holder<> class and the portion of the Handle-Holder mechanism exposed in the interface. Now, let’s dive into the implementation and understand how object Pool s can be implemented.

The implementation starts with a class Pool<> which is located in lightweightvk/lvk/Pool.h. It stores a collection of objects of type ImplObjectType inside std::vector and can manage handles to these objects. Let’s look at the implementation details.

  1. Every array element is a struct PoolEntry which stores an ImplObjectType object by value together with its generation used to check handles which point to this element. The field nextFree_ is used to maintain a linked list of free elements inside the array. Once a handle is deallocated, a corresponding array element is added to the free list. The field freeListHead_ stores an index of the first free element or kListEndSentinel in case there are no free elements.
    template<typename ObjectType, typename ImplObjectType>
    class Pool {
    static constexpr uint32_t kListEndSentinel = 0xffffffff;
    struct PoolEntry {
    explicit PoolEntry(ImplObjectType& obj)
    : obj_(std::move(obj)) {}
    ImplObjectType obj_ = {};
    uint32_t gen_ = 1;
    uint32_t nextFree_ = kListEndSentinel;
    };
    uint32_t freeListHead_ = kListEndSentinel;
    public:
    std::vector<PoolEntry> objects_;
    Note Proponents of Data-Oriented Design may argue that this structure minimizes cache utilization by interleaving the payload of ImplObjectType with utility values gen_ and nextFree_. This is indeed true. One approach mitigate to this is to store (memory alias) the nextFree_ element in-place of the unused object in the pool. Another approach to is to maintain two separate arrays. The first array can tightly pack ImplObjectType values, while the second one can store the necessary metadata for bookkeeping. In fact, it can go a step further, as mentioned in the original presentation by Sebastian Aaltonen, by separating a high-frequency accessed “hot” object type from a low-frequency accessed “cold” type, which can be stored in different arrays. However, for the sake of simplicity, we will leave this as an exercise for our readers.
  2. The method create() takes an R-value reference. It checks the head of the free list. If there is a free element within the array, we can immediately place our object into it and remove the front element from the free list.
    Handle<ObjectType> create(ImplObjectType&& obj) {
    uint32_t idx = 0;
    if (freeListHead_ != kListEndSentinel) {
    idx = freeListHead_;
    freeListHead_ = objects_[idx].nextFree_;
    objects_[idx].obj_ = std::move(obj);
    } else {
  3. If there’s no space inside, append a new element to the std::vector container.
    idx = (uint32_t)objects_.size();
    objects_.emplace_back(obj);
    }
    numObjects_++;
    return Handle<ObjectType>(idx, objects_[idx].gen_);
    }
  4. Destruction is straightforward but involves additional error checking. Empty handles should not be destroyed. Attempting to remove a non-empty handle from an empty pool indicates a logic error and should trigger an assertion. If the generation of the handle does not match the generation of the corresponding array element, it means we are attempting double-deletion.
    void destroy(Handle<ObjectType> handle) {
    if (handle.empty()) return;
    assert(numObjects_ > 0);
    const uint32_t index = handle.index();
    assert(index < objects_.size());
    // double deletion
    assert(handle.gen() == objects_[index].gen_);
  5. If all the checks are successful, replace the stored object with an empty, default-constructed object and increment its generation. Then, place this array element at the front of the free list.
    objects_[index].obj_ = ImplObjectType{};
    objects_[index].gen_++;
    objects_[index].nextFree_ = freeListHead_;
    freeListHead_ = index;
    numObjects_--;
    }
  6. Dereferencing a handle is done via the get() method, which has both const and non- const implementations. They are identical, so we only need to check one. A mismatch in the generation helps identify access to a deleted object.
    ImplObjectType* get(Handle<ObjectType> handle) {
    if (handle.empty()) return nullptr;
    const uint32_t index = handle.index();
    assert(index < objects_.size());
    // accessing a deleted object
    assert(handle.gen() == objects_[index].gen_);
    return &objects_[index].obj_;
    }
  7. A pool can be manually cleared, causing a destructor to be called for every object.
    void clear() {
    objects_.clear();
    freeListHead_ = kListEndSentinel;
    numObjects_ = 0;
    }
  8. Sometimes, it is convenient to construct a Handle<> object knowing its index in the pool, regardless of the generation value. This is unsafe and should only be used for debugging.
    Handle<ObjectType> getHandle(uint32_t index) const {
    assert(index < objects_.size());
    if (index >= objects_.size()) return {};
    return Handle<ObjectType>(index, objects_[index].gen_);
    }
  9. We can also check if a specific object is in the pool and obtain a handle to it. An empty handle is returned if there’s no object.
    Handle<ObjectType> findObject(const ImplObjectType* obj) {
    if (!obj) return {};
    for (size_t idx = 0; idx != objects_.size(); idx++) {
    if (objects_[idx].obj_ == *obj) {
    return Handle<ObjectType>(
    (uint32_t)idx, objects_[idx].gen_);
    }
    }
    return {};
    }
  10. The member field numObjects_ is used to track memory leaks and prevent deallocations inside an empty pool.
    uint32_t numObjects() const {
    return numObjects_;
    }
    uint32_t numObjects_ = 0;
    };

That is how Pool s work. The LightweightVK implementation in VulkanContext uses them to store all implementation-specific objects that are accessible by handles from the interface side. These declarations can be found in lvk/vulkan/VulkanClasses.h. In many situations, Vulkan objects such as VkShaderModule and VkSampler can be stored directly. However, if additional bookkeeping is required, a wrapper object is stored instead.

Pool<ShaderModule, ShaderModuleState> shaderModulesPool_;
Pool<RenderPipeline, RenderPipelineState> renderPipelinesPool_;
Pool<ComputePipeline, ComputePipelineState> computePipelinesPool_;
Pool<Sampler, VkSampler> samplersPool_;
Pool<Buffer, VulkanBuffer> buffersPool_;
Pool<Texture, VulkanImage> texturesPool_;
Pool<QueryPool, VkQueryPool> queriesPool_;

Now we know how to store various objects in Pool s and expose access to them via Handle s. Before concluding the topic of this chapter and finishing our introduction to Vulkan, let’s take a look at how to construct bindless descriptor sets to access textures from GLSL shaders and create a simple texture mapping rendering application.

Descriptor indexing became part of the Vulkan core in version 1.2 as an optional feature, and it was made mandatory in Vulkan 1.3. This feature allows applications to place all their resources into one large descriptor set and make it available to all shaders. There’s no need to manage descriptor pools or construct per-shader descriptor sets. Everything is accessible to shaders at once. Shaders can access all resources in the system, and the only practical limit is performance. Let’s learn how to work with descriptor sets and descriptor indexing in Vulkan by exploring the LightweightVK framework.

Let’s examine the parts of the VulkanContext class that manage descriptors, as declared in lvk/vulkan/VulkanClasses.h. Integer variables currentMaxTextures_ and currentMaxSamplers_ define the maximum number of resources that can be stored in the descriptor set, referred to as vkDSet _. This descriptor set is allocated from a descriptor pool named vkDPool_, which is created based on the descriptor set layout specified by vkDSL_. Additionally, the lastSubmitHandle_ field tracks the most recent submit operation that involved this descriptor set. This submit handle concept was discussed earlier in the previous chapter in the recipe Using Vulkan command buffers.

class VulkanContext final : public IContext {
// ...
uint32_t currentMaxTextures_ = 16;
uint32_t currentMaxSamplers_ = 16;
VkDescriptorSetLayout vkDSL_ = VK_NULL_HANDLE;
VkDescriptorPool vkDPool_ = VK_NULL_HANDLE;
VkDescriptorSet vkDSet_ = VK_NULL_HANDLE;
SubmitHandle lastSubmitHandle = SubmitHandle();
// ...
}

Our exploration begins with the growDescriptorPool() function, which is responsible for recreating Vulkan objects when necessary to handle the requested number of textures and samplers. To maintain readability, extensive error-checking code has been omitted.

  1. First, ensure the number of resources is withing the hardware specific limits.
    lvk::Result lvk::VulkanContext::growDescriptorPool(uint32_t maxTextures, uint32_t maxSamplers, uint32_t maxAccelStructs) {
    currentMaxTextures_ = maxTextures;
    currentMaxSamplers_ = maxSamplers;
    currentMaxAccelStructs_ = maxAccelStructs;
    if (!LVK_VERIFY(maxTextures <=
    vkPhysicalDeviceVulkan12Properties_.
    maxDescriptorSetUpdateAfterBindSampledImages))
    {
    LLOGW("Max Textures exceeded: %u (max %u)",
    maxTextures,
    vkPhysicalDeviceVulkan12Properties_.
    maxDescriptorSetUpdateAfterBindSampledImages);
    }
    if (!LVK_VERIFY(maxSamplers <=
    vkPhysicalDeviceVulkan12Properties_.
    maxDescriptorSetUpdateAfterBindSamplers))
    {
    LLOGW("Max Samplers exceeded %u (max %u)",
    maxSamplers,
    vkPhysicalDeviceVulkan12Properties_.
    maxDescriptorSetUpdateAfterBindSamplers);
    }
  2. Next, the function deallocates any existing Vulkan descriptor set layout and descriptor pool.
    if (vkDSL_ != VK_NULL_HANDLE) {
    deferredTask(std::packaged_task<void()>(
    [device = vkDevice_, dsl = vkDSL_]() {
    vkDestroyDescriptorSetLayout(device, dsl, nullptr); }));
    }
    if (vkDPool_ != VK_NULL_HANDLE) {
    deferredTask(std::packaged_task<void()>(
    [device = vkDevice_, dp = vkDPool_]() {
    vkDestroyDescriptorPool(device, dp, nullptr); }));
    }
  3. The function creates a new descriptor set layout to be shared across all Vulkan pipelines. This layout includes bindings for all supported Vulkan resources such as sampled images, samplers, and storage images. Ray tracing-related resources are not covered here, and so are YUV images, as they are beyond the scope of the book.
    VkShaderStageFlags stageFlags =
    VK_SHADER_STAGE_VERTEX_BIT |
    VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT |
    VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT |
    VK_SHADER_STAGE_FRAGMENT_BIT |
    VK_SHADER_STAGE_COMPUTE_BIT;
    const VkDescriptorSetLayoutBinding
    bindings[kBinding_NumBindings] = {
    getDSLBinding(kBinding_Textures,
    VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, maxTextures, stageFlags),
    getDSLBinding(kBinding_Samplers,
    VK_DESCRIPTOR_TYPE_SAMPLER, maxSamplers, stageFlags),
    getDSLBinding(kBinding_StorageImages,
    VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, maxTextures, stageFlags),
    };
  4. The Vulkan descriptor indexing feature enables descriptor sets to be updated after they have been bound.
    const uint32_t flags =
    VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
    VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT |
    VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT;
    VkDescriptorBindingFlags bindingFlags[kBinding_NumBindings];
    for (int i = 0; i < kBinding_NumBindings; ++i)
    bindingFlags[i] = flags;
  5. A chain of Vulkan Vk…CreateInfo structures should be prepared to create a desired VkDesciptorSetLayout object.
    const VkDescriptorSetLayoutBindingFlagsCreateInfo
    setLayoutBindingFlagsCI = {
    .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_
    CREATE_INFO_EXT,
    .bindingCount = kBinding_NumBindings,
    .pBindingFlags = bindingFlags,
    };
    const VkDescriptorSetLayoutCreateInfo dslci = {
    .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
    .pNext = &setLayoutBindingFlagsCI,
    .flags =
    VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT,
    .bindingCount = kBinding_NumBindings,
    .pBindings = bindings,
    };
    vkCreateDescriptorSetLayout(vkDevice_, &dslci, nullptr, &vkDSL_);
  6. Using the newly created descriptor set layout, we can now create a descriptor pool. Be sure to include the flag VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT, as it is necessary to support the corresponding VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT flag in the descriptor set layout.
    const VkDescriptorPoolSize poolSizes[kBinding_NumBindings]{
    VkDescriptorPoolSize{
    VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, maxTextures},
    VkDescriptorPoolSize{
    VK_DESCRIPTOR_TYPE_SAMPLER, maxSamplers},
    VkDescriptorPoolSize{
    VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, maxTextures},
    };
    const VkDescriptorPoolCreateInfo ci = {
    .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
    .flags = VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT,
    .maxSets = 1,
    .poolSizeCount = kBinding_NumBindings,
    .pPoolSizes = poolSizes,
    };
    vkCreateDescriptorPool(vkDevice_, &ci, nullptr, &vkDPool_);
  7. Now we can allocate a descriptor set from the vkDPool_ descriptor pool.
    const VkDescriptorSetAllocateInfo ai = {
    .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
    .descriptorPool = vkDPool_,
    .descriptorSetCount = 1,
    .pSetLayouts = &vkDSL_,
    };
    vkAllocateDescriptorSets(vkDevice_, &ai, &vkDSet_);
    return Result();
    }

To create Vulkan pipelines, we need a pipeline layout. In LightweightVK, the pipeline layout is stored for each pipeline in the RenderPipelineState structure. We covered how to set this up in the previous Chapter 2, in the recipe Initializing Vulkan pipelines using the vkDSL_ descriptor set layout created above.

The growDescriptorPool() function was the first step in our descriptor set management mechanism. Now, we have a descriptor set, vkDSet_, which must be updated before it can be used. This updating process is handled by another function, checkAndUpdateDescriptorSets(), which is called before dispatching Vulkan draw calls. Let’s take a closer look at it. As before, some parts of the error checking have been omitted.

  1. Newly created resources, such as textures and samplers, can be used immediately—just make sure they are added to descriptor sets. We covered the texture creation process earlier in the recipe Using texture data in Vulkan. Once a new texture is created, the awaitingCreation_ flag is set to indicate that the descriptor set needs to be updated. If there are no new textures or samplers, no updates to the descriptor set are necessary.
    void VulkanContext::checkAndUpdateDescriptorSets() {
    if (!awaitingCreation_) return;
  2. As we learned in the previous recipe, Storing Vulkan Objects, textures and samplers are stored in pools within VulkanContext. Here, we grow the Vulkan descriptor pool as needed to accommodate all the textures and samplers from these pools.
    uint32_t newMaxTextures = currentMaxTextures_;
    uint32_t newMaxSamplers = currentMaxSamplers_;
    while (texturesPool_.objects_.size() > newMaxTextures)
    newMaxTextures *= 2;
    while (samplersPool_.objects_.size() > newMaxSamplers)
    newMaxSamplers *= 2;
    if (newMaxTextures != currentMaxTextures_ ||
    newMaxSamplers != currentMaxSamplers_) {
    growDescriptorPool(newMaxTextures, newMaxSamplers);
    }
  3. Let’s prepare the Vulkan structures to update the descriptor set with sampled and storage images. LightweightVK always stores a dummy texture at index 0 to prevent sparse arrays in GLSL shaders and ensure that all shaders can safely sample non-existing textures.
    std::vector<VkDescriptorImageInfo> infoSampledImages;
    std::vector<VkDescriptorImageInfo> infoStorageImages;
    infoSampledImages.reserve(texturesPool_.numObjects());
    infoStorageImages.reserve(texturesPool_.numObjects());
    VkImageView dummyImageView =
    texturesPool_.objects_[0].obj_.imageView_;
  4. Iterate over the texture pool and populate the VkDescriptorImageInfo structures based on the image properties. Multisampled images can only be accessed from shaders using texelFetch(), which is not supported by LightweightVK, so we skip them here.
    for (const auto& obj : texturesPool_.objects_) {
    const VulkanImage& img = obj.obj_;
    const VkImageView view = obj.obj_.imageView_;
    const VkImageView storageView = obj.obj_.imageViewStorage_ ?
    obj.obj_.imageViewStorage_ : view;
    const bool isTextureAvailable = VK_SAMPLE_COUNT_1_BIT ==
    (img.vkSamples_ & VK_SAMPLE_COUNT_1_BIT);
    const bool isSampledImage =
    isTextureAvailable && img.isSampledImage();
    const bool isStorageImage =
    isTextureAvailable && img.isStorageImage();
  5. Images are expected to be in specific layouts. Sampled images should use VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, while storage images should use VK_IMAGE_LAYOUT_GENERAL. LightweightVK automatically handles the necessary image layout conversions, which we will discuss in later chapters.
    infoSampledImages.push_back(VkDescriptorImageInfo{
    .sampler = VK_NULL_HANDLE,
    .imageView = isSampledImage ? view : dummyImageView,
    .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
    });
    infoStorageImages.push_back(VkDescriptorImageInfo{
    .sampler = VK_NULL_HANDLE,
    .imageView = isStorageImage ? storageView : dummyImageView,
    .imageLayout = VK_IMAGE_LAYOUT_GENERAL,
    });
    }
  6. Samplers are handled in a very similar manner.
    std::vector<VkDescriptorImageInfo> infoSamplers;
    infoSamplers.reserve(samplersPool_.objects_.size());
    for (const auto& sampler : samplersPool_.objects_) {
    infoSamplers.push_back({
    .sampler = sampler.obj_ ?
    sampler.obj_ : samplersPool_.objects_[0].obj_,
    .imageView = VK_NULL_HANDLE,
    .imageLayout = VK_IMAGE_LAYOUT_UNDEFINED,
    });
    }
  7. The VkWriteDescriptorSet structure specifies the parameters for a descriptor set write operation. We need to fill in one structure for each of our three bindings, corresponding to three different descriptor types: VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, VK_DESCRIPTOR_TYPE_SAMPLER, and VK_DESCRIPTOR_TYPE_STORAGE_IMAGE. This code snippet is straightforward but somewhat lengthy, so we include it here in its entirety for your reference.
    VkWriteDescriptorSet write[kBinding_NumBindings] = {};
    uint32_t numWrites = 0;
    if (!infoSampledImages.empty())
    write[numWrites++] = VkWriteDescriptorSet{
    .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
    .dstSet = vkDSet_,
    .dstBinding = kBinding_Textures,
    .dstArrayElement = 0,
    .descriptorCount = (uint32_t)infoSampledImages.size(),
    .descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
    .pImageInfo = infoSampledImages.data(),
    };
    if (!infoSamplers.empty())
    write[numWrites++] = VkWriteDescriptorSet{
    .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
    .dstSet = vkDSet_,
    .dstBinding = kBinding_Samplers,
    .dstArrayElement = 0,
    .descriptorCount = (uint32_t)infoSamplers.size(),
    .descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER,
    .pImageInfo = infoSamplers.data(),
    };
    if (!infoStorageImages.empty())
    write[numWrites++] = VkWriteDescriptorSet{
    .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
    .dstSet = vkDSet_,
    .dstBinding = kBinding_StorageImages,
    .dstArrayElement = 0,
    .descriptorCount = (uint32_t)infoStorageImages.size(),
    .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE,
    .pImageInfo = infoStorageImages.data(),
    };
  8. If we have filled in any VkWriteDescriptorSet structures, invoke the Vulkan function vkUpdateDescriptorSets() to update the descriptor set. Since we are updating the entire descriptor set, it is essential to ensure that Vulkan is not using it by waiting on a fence and calling wait() with the last known submit handle. This mechanism was discussed earlier in the previous chapter in the recipe Using Vulkan command buffers.
    if (numWrites) {
    immediate_->wait(immediate_->getLastSubmitHandle());
    vkUpdateDescriptorSets(vkDevice_, numWrites, write, 0, nullptr);
    }
    awaitingCreation_ = false;
    }

The C++ portion of the descriptor set updating process is complete. The only remaining step is to clarify how to access these descriptor sets from GLSL shaders. Let’s explore how this works.

VulkanContext injects helper code into GLSL shaders to simplify working with our bindless descriptor sets. Let’s revisit the VulkanContext::createShaderModuleFromGLSL() function, which handles the injection. Here’s the GLSL code it automatically adds to every fragment shader. We skip the automatically added GLSL extensions for the sake of brevity.

  1. First, it declares some unbound arrays that are stored in our bindless descriptor set. You’ll notice that the descriptor set ID ranges from 0 to 2. However, don’t be misled by this; it’s the same descriptor set bound to three different locations. As shown earlier in this recipe, this is necessary for compatibility with MoltenVK as it does not support descriptor aliasing.
    layout(set = 0, binding = 0) uniform texture2D kTextures2D[];
    layout(set = 1, binding = 0) uniform texture3D kTextures3D[];
    layout(set = 2, binding = 0) uniform textureCube kTexturesCube[];
    layout(set = 3, binding = 0) uniform texture2D kTextures2DShadow[];
    layout(set = 0, binding = 1) uniform sampler kSamplers[];
    layout(set = 1, binding = 1) uniform samplerShadow kSamplersShadow[];
  2. Next, some helper functions are added. These functions correspond to standard GLSL functions like texture(), textureLod(), and others. They simplify the process of working with bindless textures and descriptor indexing. We’ve listed just a few of them here to give you an overall picture.
    vec4 textureBindless2D(uint textureid, uint samplerid, vec2 uv) {
    return texture(nonuniformEXT(sampler2D(
    kTextures2D[textureid], kSamplers[samplerid])), uv);
    }
    vec4 textureBindless2DLod(
    uint textureid, uint samplerid, vec2 uv, float lod) {
    return textureLod(nonuniformEXT(sampler2D(
    kTextures2D[textureid], kSamplers[samplerid])), uv, lod);
    }
    float textureBindless2DShadow(uint textureid, uint samplerid, vec3 uvw) {
    return texture(nonuniformEXT(sampler2DShadow(
    kTextures2DShadow[textureid], kSamplersShadow[samplerid])), uvw);
    }
    ivec2 textureBindlessSize2D(uint textureid) {
    return textureSize(nonuniformEXT(kTextures2D[textureid]), 0);
    }

Note how nonuniformEXT(sampler2D()) should be used here. The final argument in a function call like texture() determines whether the access is considered non-uniform.

  1. With this, our GLSL fragment shader Chapter03/02_STB/main.frag can be rewritten as follows, without the need for manually declaring the lengthy data structures.
    layout (location=0) in vec2 uv;
    layout (location=0) out vec4 out_FragColor;
    layout(push_constant) uniform PerFrameData {
    uniform mat4 MVP;
    uint textureId;
    };
    void main() {
    out_FragColor = textureBindless2D(textureId, 0, uv);
    };

With the bindless descriptor set code in place, we can now render textured objects, like the one in the following image.

Figure 3.4: Rendering a textured quad

Now, let’s move on to the next chapter and learn how to add user interaction and productivity tools to our examples.

The topic of efficient resource management in Vulkan is vast and complex. We will revisit descriptor set management later when we cover 3D scene data management and the rendering of complex multitextured materials.

There are two major improvements that can be made to this code to prevent stalling when updating the descriptor set and boost its update performance. The first improvement is to use a couple of round-robin descriptor sets and switch between them, eliminating the need for the heavy wait() function call before writing descriptor sets. Another important improvement is to perform incremental updates of descriptor sets. This is crucial when creating new textures or samplers, as it allows the update to be done without any waiting by simply placing new descriptors into the available elements of the descriptor set, using the VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT functionality.