Writing

Vulkan Series: 05 - Textured Quad

Putting a texture on our quad with images, layout transitions, descriptor sets and samplers in Vulkan 1.3

graphicsvulkanc++vmatexturesimagesdescriptor setssamplersrenderdocvulkan 1.3

What we’ll build here

End Result
End Result

The same quad as last time, but now with a texture on it! Instead of blending colours between its corners, every pixel of our quad now comes from an actual image living in GPU memory.

It looks like a small change on screen, but there’s quite a lot going on behind it. In this post, we’ll:

  1. Write an Image class on top of VMA
  2. Generate some pixels for a checkerboard texture
  3. Get those pixels into the image using layout transitions and our trusty staging buffer
  4. Check our work with RenderDoc, before we’ve written a single line of shader code for it
  5. Add texture coordinates to our vertices
  6. Learn how shaders get access to resources through descriptors, and wrap them up in a ShaderDataTable class
  7. Create a sampler, and finally sample our texture in the fragment shader
  8. Swap our checkerboard for a real image, loaded from a file with stb_image
  9. Stop embedding our shaders, and load them from files too

This post builds directly on top of the previous post, where we set up our Buffer class, the staging buffer and execute_single_shot_commands, so if you haven’t gone through that one yet, I’d strongly recommend doing so first.

Just want the source code? Find it on GitHub or at the end of this post.

Setup

Nothing new to install, apart from RenderDoc, which is optional (but highly recommended!). We’ll get to it later in the post. We’ll also be grabbing a single header from stb, but we won’t need it until the very end.

We’ll be adding two new source files this time, image.cpp and shader_data_table.cpp, so they go into our CMakeLists.txt:

add_executable(App
    vma.cpp
    main.cpp
    image.cpp
    buffer.cpp
    sample.cpp
    pipeline.cpp
    shader_data_table.cpp
)

And we’ll be needing std::map and std::deque, so they go into the includes at the top of common.hpp:

#include <map>
#include <span>
#include <deque>
#include <cstdio>
#include <memory>
#include <string>
#include <cstddef>
#include <variant>
#include <cassert>
#include <type_traits>

THEORY: Images and image views

We’ve actually been using images since the very first post: every swapchain image is one. But those were created for us by the swapchain. This time, we create one ourselves.

A Vulkan image (VkImage) is a lot like a buffer: a chunk of GPU memory with a handle. The difference is that an image knows its shape. It has a width, a height (and a depth, for 3D images), a format that says what each pixel (or texel, as pixels in a texture are usually called) looks like, and optionally mip levels and array layers. Knowing all this lets the GPU store the image in whatever way is fastest for it, and do things like filtering when we read from it, which we’ll see when we get to samplers.

And just like buffers, we can’t put anything into an image’s memory before allocating it. We’ll let VMA do that for us, same as with our buffers.

On its own though, an image can’t be used by shaders, or as an attachment. For that, we need an image view (VkImageView), which says how to look at the image: as a 2D image or a cube map, which mip levels and array layers, which aspect (colour or depth), and so on. We’ve already created image views for our swapchain images, so this part should look familiar.

The Image class

Same as with buffers, we’ll wrap images into a little class of their own. Here’s the start of image.hpp:

// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include "common.hpp"

class Image
{
public:
  static Result<Box<Image>> create(VkDevice device, VmaAllocator allocator, VkFormat format, VkExtent2D extent, VkImageUsageFlags usage);

  Image(const Image&) = delete;
  ~Image();

private:
  Image(VkDevice device, VmaAllocator allocator): m_device(device), m_allocator(allocator) {}

private:
  VkDevice m_device{};
  VmaAllocator m_allocator{};

  VkImage m_handle{};
  VkImageView m_view_handle{};
  VkFormat m_format{};
  VkExtent2D m_extent{};
  VmaAllocation m_allocation{};
};

Same pattern as our Buffer and Pipeline classes: a static create returning a Result<Box<Image>>, a private constructor, no copying, and a destructor that cleans up. This time we need the VkDevice too, along with the allocator, since image views are created and destroyed through the device.

Here’s Image::create, in the new image.cpp:

// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#include "image.hpp"

Result<Box<Image>> Image::create(VkDevice device, VmaAllocator allocator, VkFormat format, VkExtent2D extent, VkImageUsageFlags usage)
{
  Box<Image> image(new Image(device, allocator));

  image->m_format = format;
  image->m_extent = extent;

  VkImageCreateInfo create_info{
    .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
    .imageType = VK_IMAGE_TYPE_2D, // for now we'll only need 2D images
    .format = format,
    .extent = VkExtent3D(extent.width, extent.height, 1),
    .mipLevels = 1, // we won't be bothering with mip mapping for now
    .arrayLayers = 1,
    .samples = VK_SAMPLE_COUNT_1_BIT, // we won't be bothering with multisampling for now either
    .tiling = VK_IMAGE_TILING_OPTIMAL, // we don't have any specific tiling we need so let vulkan pick the optimal one
    .usage = usage,
    .sharingMode = VK_SHARING_MODE_EXCLUSIVE, // we only need to use our images from a single queue family at a time
    .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
  };

  VmaAllocationCreateInfo alloc_create_info{
    .usage = VMA_MEMORY_USAGE_AUTO,
  };
  if (vmaCreateImage(allocator, &create_info, &alloc_create_info, &image->m_handle, &image->m_allocation, nullptr) != VK_SUCCESS)
    return "Failed to create the image";
  • imageType, format and extent: A 2D image of the given format and size. VkExtent3D has a depth too, which is always 1 for a 2D image.
  • mipLevels and arrayLayers: Just the one of each. We’ll get to mip mapping in a later post.
  • samples: Used for multisampling (MSAA), which we don’t need, so it’s 1 sample per texel.
  • tiling: VK_IMAGE_TILING_OPTIMAL lets the GPU arrange the texels in memory however it likes. The other option, VK_IMAGE_TILING_LINEAR, forces a plain row after row layout that the CPU could read and write directly, but it’s slower for the GPU and very limited in what it can be used for. We’ll never be touching the image’s memory from the CPU directly anyway, as we’ll see.
  • usage: Same idea as with buffers: we declare everything we’ll use the image for upfront. We let the caller pass this in.
  • initialLayout: The layout the image starts in. More on layouts in a bit.
  • vmaCreateImage: The image version of vmaCreateBuffer. It creates the image, picks a memory type, allocates the memory and binds it, all in one call. No CPU access flags means VMA puts it in fast GPU memory, like our vertex and index buffers.

And then the image view:

  VkImageViewCreateInfo view_create_info{
    .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
    .image = image->m_handle,
    .viewType = VK_IMAGE_VIEW_TYPE_2D,
    .format = image->m_format,
    .subresourceRange = {
      .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
      .baseMipLevel = 0,
      .levelCount = 1,
      .baseArrayLayer = 0,
      .layerCount = 1,
    },
  };
  if (vkCreateImageView(device, &view_create_info, nullptr, &image->m_view_handle) != VK_SUCCESS)
    return "Failed to create the image view";

  return image;
}

This is almost exactly what we do for our swapchain images: a 2D view of the colour aspect, covering our one and only mip level and array layer. We leave out components, so it defaults to the identity swizzle (red is red, green is green, and so on).

The destructor destroys the two in the reverse order:

Image::~Image()
{
  if (m_device && m_view_handle)
    vkDestroyImageView(m_device, m_view_handle, nullptr);

  if (m_allocator && m_allocation && m_handle)
    vmaDestroyImage(m_allocator, m_handle, m_allocation);
}

The view refers to the image, so it has to go first. vmaDestroyImage then frees both the image and its memory.

Creating our texture

Let’s add the image to SampleVulkan, along with an #include "image.hpp" at the top of sample.hpp:

  Box<Image> m_texture_image{};

Like our buffers, the image has to be freed before the allocator is destroyed, so we reset it in the destructor, right after vkDeviceWaitIdle:

    m_texture_image.reset();

We’ll create it in a moment, once we have some pixels to put in it. But first, there’s a function from the first post that really belongs in our new class.

Moving transition_image_layout into Image

transition_image_layout has been a member of SampleVulkan since the start, but it has nothing to do with our sample in particular. It’s all about images, so let’s move it into the Image class. Remove its declaration from sample.hpp, and add it to image.hpp, along with a new member function, and a new member to keep track of the image’s current layout:

class Image
{
public:
  static bool transition_image_layout(VkCommandBuffer cmd, VkImage image, VkImageLayout old_layout, VkImageLayout new_layout,
        uint32_t base_mip_level = 0, uint32_t level_count = 1, uint32_t base_array_layer = 0,
        uint32_t layer_count = 1);

public:
  static Result<Box<Image>> create(VkDevice device, VmaAllocator allocator, VkFormat format, VkExtent2D extent, VkImageUsageFlags usage);

  Image(const Image&) = delete;
  ~Image();

  bool transition_layout(VkCommandBuffer cmd, VkImageLayout new_layout);
  VkImageLayout m_layout{VK_IMAGE_LAYOUT_UNDEFINED};

transition_image_layout is now static, since our swapchain images aren’t Image objects (the swapchain owns them), and we still need to transition them every frame. Move the function body over to image.cpp as is, just changing SampleVulkan:: to Image:::

bool Image::transition_image_layout(VkCommandBuffer cmd, VkImage image, VkImageLayout old_layout,
                                           VkImageLayout new_layout, uint32_t base_mip_level, uint32_t level_count,
                                           uint32_t base_array_layer, uint32_t layer_count)

And update the two calls in render:

  if (!Image::transition_image_layout(current_frame.cmd_buffer, m_swapchain_images[image_index], VK_IMAGE_LAYOUT_UNDEFINED,
                               VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL))
  if (!Image::transition_image_layout(current_frame.cmd_buffer, m_swapchain_images[image_index],
                               VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR))

For our own images, the new transition_layout member is much nicer to use:

bool Image::transition_layout(VkCommandBuffer cmd, VkImageLayout new_layout)
{
  if (transition_image_layout(cmd, m_handle, m_layout, new_layout)) {
    m_layout = new_layout;
    return true;
  }

  return false;
}

Since the image keeps track of its own layout, all we have to say is where we want it to go. It fills in the old layout for us, and remembers the new one if the transition succeeds.

We use the same member for the initialLayout in Image::create, so the two always agree:

    .initialLayout = image->m_layout,

NOTE: m_layout tracks the layout as of the last recorded transition, not the layout the image is in on the GPU right now. That’s fine for us, as we submit and wait for our commands right away, but it’s something to keep in mind if you record command buffers and hold on to them.

Generating the pixels

Now we need some pixels to put in our texture. Normally, they’d come from an image file, like a PNG, but loading one of those means pulling in a library to decode it. We’ll do that at the end of this post. For now, let’s keep the focus on Vulkan and just generate a checkerboard pattern ourselves. At the top of sample.cpp:

// Create checkerboard pattern pixels (violet and white)
static std::vector<uint8_t> get_checkerboard_pattern_pixels(uint32_t width, uint32_t height, uint32_t checker_size = 4)
{
  std::vector<uint8_t> rgba_data(width * height * 4);

  for (uint32_t y = 0; y < height; ++y)
  {
    for (uint32_t x = 0; x < width; ++x)
    {
      const bool is_violet = ((x / checker_size) % 2) == ((y / checker_size) % 2);
      uint32_t index = (y * width + x) * 4;
      if (is_violet)
      {
        rgba_data[index + 0] = 255;
        rgba_data[index + 1] = 0;
        rgba_data[index + 2] = 255;
        rgba_data[index + 3] = 255;
      }
      else
      {
        rgba_data[index + 0] = 255;
        rgba_data[index + 1] = 255;
        rgba_data[index + 2] = 255;
        rgba_data[index + 3] = 255;
      }
    }
  }

  return rgba_data;
}

Every texel is 4 bytes: red, green, blue and alpha, from 0 to 255 each. They’re stored row after row, so the texel at (x, y) starts at byte (y * width + x) * 4. Dividing x and y by checker_size tells us which square a texel is in, and a texel is violet when its square’s column and row are both even or both odd. That’s what gives us the checkerboard.

With that, we can create our image at the end of initialize:

  {
    const uint32_t w = 32;
    const uint32_t h = 32;

    const auto pixels = get_checkerboard_pattern_pixels(w, h);

    CHECK_RESULT(
      Image::create(
        m_device,
        m_allocator,
        VK_FORMAT_R8G8B8A8_SRGB,
        {.width = w, .height = h},
        VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT // We want to sample this image from fragment shader and
                                                                          // copy data from staging buffer into this image.
      ),
    m_texture_image);
  }

A 32×32 image, with 4×4 texel squares, gives us an 8×8 checkerboard.

  • VK_FORMAT_R8G8B8A8_SRGB: 4 channels of 8 bits each, in the same R, G, B, A order as our pixels. The format has to match the data we put in. If we picked, say, a format with 32-bit floats per channel, the GPU would read our 4096 bytes as a quarter of the texels it expects, and we’d get garbage. The SRGB part says our colour values are stored in the sRGB colour space, which is what image files (and colour pickers) use. When a shader reads from the image, the GPU converts the values to linear for us, which is what shader maths should be done in. For our pure 0 and 255 values it makes no difference, but it will once we load real images.
  • VK_IMAGE_USAGE_SAMPLED_BIT: We’ll be sampling this image in our fragment shader.
  • VK_IMAGE_USAGE_TRANSFER_DST_BIT: We’ll be copying our pixels into it, which makes it the destination of a transfer. Same as with our vertex and index buffers.

Getting pixels into an image

Our image lives in fast GPU memory, which the CPU usually can’t write to. Sound familiar? It’s the same problem we had with our vertex and index buffers, and the solution is the same: the staging buffer.

CPU Memory -> Staging Buffer -> Image
  1. The CPU writes our pixels into a staging buffer
  2. The GPU copies them from there into the image, with vkCmdCopyBufferToImage

But there’s one more thing to take care of with images: their layout. Remember from the first post? Before using an image for something, it has to be in a layout that supports that use. Our image is created in VK_IMAGE_LAYOUT_UNDEFINED, which can’t be used for anything really. So the full flow looks like this:

  1. Transition the image from UNDEFINED to TRANSFER_DST_OPTIMAL, the layout for being the destination of a copy
  2. Copy the pixels from the staging buffer into the image
  3. Transition the image from TRANSFER_DST_OPTIMAL to SHADER_READ_ONLY_OPTIMAL, the layout for being read by shaders

All three are GPU commands, so they go into a command buffer, which is what execute_single_shot_commands is for. Before we use it though, there’s a small problem to fix.

Error handling in our single shot commands

Our callback for execute_single_shot_commands currently returns void. That was fine for copying buffers, but transition_layout can fail, and right now we’d have no way of reporting that. Our Result type to the rescue! Let’s have the callback return a Result<>, in both sample.hpp and sample.cpp:

  bool execute_single_shot_commands(std::function<Result<>(VkCommandBuffer)> commands);

And check it, right after calling it:

  const auto result = commands(m_single_shot_command_buffer);
  if (result.is_error()) {
    printf("%s\n", result.get_error().c_str());
    return false;
  }

If the callback fails, we print its error and bail out, without submitting anything.

Our two existing callbacks just need to return Ok{} at the end, along with a -> Result<> return type on the lambda:

    const auto success = execute_single_shot_commands([&](VkCommandBuffer cmd) -> Result<>
    {
      VkBufferCopy copy_region{
        .srcOffset = 0,
        .dstOffset = 0,
        .size = m_vertex_buffer->get_size(),
      };

      vkCmdCopyBuffer(cmd, m_staging_buffer->get_handle(), m_vertex_buffer->get_handle(), 1, &copy_region);

      VkMemoryBarrier barrier{
        .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER,
        .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
        .dstAccessMask = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT,
      };
      vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,
                          0, 1, &barrier, 0, nullptr, 0, nullptr);

      return Ok{};
    });

Why the explicit return type? Without it, the compiler deduces a lambda’s return type from its return statements, and they all have to agree. As we’ll see in a second, our callbacks will return both error strings and Ok{}, which are different types. With -> Result<>, both get converted to a Result<> for us.

Layout transitions

Here’s our image’s callback, right after creating it:

    const auto success = execute_single_shot_commands([&](VkCommandBuffer cmd) -> Result<>
    {
      if (!m_texture_image->transition_layout(cmd, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL))
        return "Failed to transition texture image to VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL";

      if (!m_texture_image->transition_layout(cmd, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL))
        return "Failed to transition texture image to VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL";

      return Ok{};
    });
    if (!success) {
      printf("Failed to copy pixels to the image\n");
      return false;
    }

Steps 1 and 3 from our flow, with the copy to come in between. If you run this now though, all you’ll get is Unknown layout transition. transition_image_layout only knows about the transitions we’ve needed so far, so let’s teach it these two, in image.cpp, right before the else:

  else if (_is_layout_pair(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL)) {
    src_stage = VK_PIPELINE_STAGE_2_NONE;
    src_access = VK_ACCESS_2_NONE;

    dst_stage = VK_PIPELINE_STAGE_2_COPY_BIT;
    dst_access = VK_ACCESS_2_TRANSFER_WRITE_BIT;
  }
  else if (_is_layout_pair(VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)) {
    src_stage = VK_PIPELINE_STAGE_2_COPY_BIT;
    src_access = VK_ACCESS_2_TRANSFER_WRITE_BIT;

    dst_stage = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT;
    dst_access = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT;
  }

Same as before, the src_* side says what has to be done before the transition, and the dst_* side says what has to wait for it.

  1. UNDEFINED → TRANSFER_DST_OPTIMAL: Our image was just created, so nothing before the barrier touches it, and there’s nothing to wait for: the source is NONE. Unlike our swapchain image’s UNDEFINED transition, there’s no semaphore to tie it to either. On the destination side, the copy’s writes must wait for the transition. VK_PIPELINE_STAGE_2_COPY_BIT is one of the finer grained stages that synchronization2 gives us. The older TRANSFER stage covers all transfer commands (copies, blits, clears and resolves), and COPY is just the copies.

  2. TRANSFER_DST_OPTIMAL → SHADER_READ_ONLY_OPTIMAL: The copy’s writes must be done (and made visible) before the transition, and our fragment shader’s reads must wait for it. VK_ACCESS_2_SHADER_SAMPLED_READ_BIT is, again, more specific than the older SHADER_READ: it’s a read done through a sampler, which is exactly what we’ll be doing. If we wanted to sample the image in the vertex shader too, we’d add the vertex shader stage to dst_stage.

That second barrier is doing the same job as the barriers after our buffer copies in the previous post: making sure the copy’s writes are visible to whoever reads the data next. Here, it also changes the layout while it’s at it.

Copying the pixels

Now for step 2. We’ll add a copy_from_cpu to Image, similar to the one in Buffer. Except this one does both halves of the copy flow: writing the pixels into a staging buffer, and recording the copy from there into the image. Which staging buffer though? The one in SampleVulkan is only as big as our largest vertex or index upload, and it’d be odd for an image to reach into our sample for it. So each image gets its own, created the first time it’s needed. In image.hpp, replace #include "common.hpp" with #include "buffer.hpp", and add:

  // make sure the image is in VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL layout before
  // calling this function
  bool copy_from_cpu(VkCommandBuffer cmd, const void* data, VkDeviceSize size);
  Box<Buffer> m_staging_buffer; // only create if copy_from_cpu is called

We’ll want to use our CHECK_RESULT macro in image.cpp, so let’s move it out of sample.cpp and into common.hpp, right after the GLM include:

#define CHECK_RESULT(_result, _var)             \
{                                               \
  auto result = _result;                        \
  if (result.is_error()) {                      \
    printf("%s\n", result.get_error().c_str()); \
    return false;                               \
  }                                             \
  _var = std::move(result).take_value();        \
}

And here’s the function:

bool Image::copy_from_cpu(VkCommandBuffer cmd, const void* data, VkDeviceSize size)
{
  assert(m_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);

  if (!m_staging_buffer || (m_staging_buffer->get_size() < size)) {
    m_staging_buffer.reset();

    CHECK_RESULT(
      Buffer::create(
        m_allocator,
        size,
        Buffer::EUsage::STAGING
      ),
      m_staging_buffer
    );
  }

  if (!m_staging_buffer->copy_from_cpu(data, size))
    return false;

  VkBufferImageCopy region{
    .bufferOffset = 0,
    .bufferRowLength = m_extent.width,
    .bufferImageHeight = m_extent.height,
    .imageSubresource = {
      .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
      .mipLevel = 0,
      .baseArrayLayer = 0,
      .layerCount = 1,
    },
    .imageOffset = {},
    .imageExtent = VkExtent3D(m_extent.width, m_extent.height, 1),
  };
  vkCmdCopyBufferToImage(cmd, m_staging_buffer->get_handle(), m_handle, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region);

  return true;
}
  • The assert: The copy needs the image in TRANSFER_DST_OPTIMAL, and we leave it to the caller to transition it first. That way, the caller can upload several things in a row without bouncing the layout back and forth in between.
  • The staging buffer: Created if we don’t have one yet, or recreated if the one we have is too small. Then we write our pixels into it, exactly like we did with our vertices and indices.
  • VkBufferImageCopy: Describes how the bytes in the buffer map onto the texels of the image.
    • bufferOffset: Where in the buffer our pixels start.
    • bufferRowLength and bufferImageHeight: How the pixels are laid out in the buffer, in texels. Our rows are exactly as wide as the image, with nothing in between them, so these are just the image’s width and height. Setting them to 0 would mean the same thing: “tightly packed”. They become useful if, say, you only want to copy part of a bigger image that’s sitting in the buffer.
    • imageSubresource: Which part of the image to copy into: the colour aspect, of our one mip level and array layer.
    • imageOffset and imageExtent: The region of the image to fill: all of it, starting from the top left corner.
  • vkCmdCopyBufferToImage: Records the copy. Notice that we have to tell it which layout the image is in, and only a few are allowed here, TRANSFER_DST_OPTIMAL being the one we want.

The bytes per texel come from the image’s format, which is why it’s so important for the format to match our pixels.

The staging buffer has to stay alive until the GPU is done copying from it, and that only happens after we submit and wait for our command buffer. So we can’t free it at the end of copy_from_cpu. We just keep it until the image itself is destroyed, which is fine for our little 4KB texture, but worth knowing about with bigger ones. In the destructor, we free it first:

Image::~Image()
{
  m_staging_buffer.reset();

  if (m_device && m_view_handle)
    vkDestroyImageView(m_device, m_view_handle, nullptr);

  if (m_allocator && m_allocation && m_handle)
    vmaDestroyImage(m_allocator, m_handle, m_allocation);
}

Finally, the copy goes between our two transitions:

    const auto success = execute_single_shot_commands([&](VkCommandBuffer cmd) -> Result<>
    {
      if (!m_texture_image->transition_layout(cmd, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL))
        return "Failed to transition texture image to VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL";

      if (!m_texture_image->copy_from_cpu(cmd, pixels.data(), pixels.size()))
        return "Failed to copy pixels to texture image";

      if (!m_texture_image->transition_layout(cmd, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL))
        return "Failed to transition texture image to VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL";

      return Ok{};
    });

And that’s it, our image now has the pixels!

Checking our work with RenderDoc

Well… does it? To see it on screen, we still have to go through texture coordinates, shader changes and the whole descriptor business. That’s a lot of work to do before we even know whether the code so far does what it should. And if something does end up wrong at the end, it could be in any of those places.

Luckily, we don’t have to wait. A graphics debugger like RenderDoc can capture a frame of our app and let us look at everything that’s on the GPU: buffers, images, pipelines, the works. It’s free, it runs on Windows and Linux, and it’s well worth getting to know, as it’ll save you a lot of guesswork throughout your graphics programming career.

To check our texture:

  1. Open RenderDoc, and go to the Launch Application tab
  2. Set Executable Path to our build/App, and Working Directory to the sample’s folder
  3. Under Capture Options, tick Ref All Resources
  4. Hit Launch. Our app starts up as usual, with a little RenderDoc overlay in the corner
  5. Press F12 (or Print Screen) in our app’s window to capture a frame, then close the app
  6. Open the capture from RenderDoc’s capture list, and go to Window → Resource Inspector
  7. Find our image in the list. Since we haven’t given it a name, RenderDoc gives it a generic one with a number in it, but it’s the only 32×32 image we have. Open it, and you should see our violet and white checkerboard!

Why Ref All Resources? By default, RenderDoc only includes resources that the captured frame actually uses, to keep captures small. Our frame doesn’t use the texture yet, so without that option, it simply won’t be there.

NOTE: If you’re on Linux with Wayland, RenderDoc may fail to launch our app with Failed to create Vulkan surface. RenderDoc only supports X11 windows on Linux, and GLFW picks Wayland when it can. Starting RenderDoc with XDG_SESSION_TYPE=x11 qrenderdoc makes GLFW go with X11 (through XWayland) instead.

Texture coordinates

Now that we know the pixels made it, let’s get them onto our quad. The first question is: which part of the texture goes where?

That’s what texture coordinates (also called UVs) are for. They’re 2D coordinates into a texture, from (0, 0) at its top left corner to (1, 1) at its bottom right, whatever the size of the texture. We give each vertex a texture coordinate, saying which point of the texture it should be pinned to, and the rasterizer interpolates them across the triangles, exactly like it did with our colours. Each fragment then knows exactly which point of the texture it covers.

Let’s add one to our Vertex, and give each of our corners the matching corner of the texture:

struct Vertex
{
  glm::vec3 pos;
  glm::vec3 colour;
  glm::vec2 texcoord;
};

static const Vertex VERTICES[4] = {
  {glm::vec3(-0.5f, -0.5f, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)},
  {glm::vec3(0.5f, -0.5f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f) , glm::vec2(1.0f, 0.0f)},
  {glm::vec3(0.5f, 0.5f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)  , glm::vec2(1.0f, 1.0f)},
  {glm::vec3(-0.5f, 0.5f, 0.0f),  glm::vec3(1.0f, 0.0f, 1.0f), glm::vec2(0.0f, 1.0f)},
};

Our top left vertex gets (0, 0), the top left of the texture, and so on, going clockwise. Since Vulkan’s Y axis points down, just like a texture’s, the image comes out the right way up, with no flipping needed.

A Vertex is now 8 tightly packed floats, 32 bytes. Our buffer sizes and the binding’s stride all come from sizeof, so they update on their own. We just have to describe the new attribute to the pipeline:

      std::initializer_list<VkVertexInputAttributeDescription>{
        VkVertexInputAttributeDescription{.location = 0, .binding = 0, .format = VK_FORMAT_R32G32B32_SFLOAT, .offset = offsetof(Vertex, pos)},
        VkVertexInputAttributeDescription{.location = 1, .binding = 0, .format = VK_FORMAT_R32G32B32_SFLOAT, .offset = offsetof(Vertex, colour)},
        VkVertexInputAttributeDescription{.location = 2, .binding = 0, .format = VK_FORMAT_R32G32_SFLOAT, .offset = offsetof(Vertex, texcoord)},
      },

Two 32-bit floats, so VK_FORMAT_R32G32_SFLOAT, at location 2.

The vertex shader takes it in, and passes it on to the fragment shader, same as the colour:

#version 450

layout(location = 0) in vec3 in_pos;
layout(location = 1) in vec3 in_color;
layout(location = 2) in vec2 in_texcord;

layout(location = 0) out vec3 out_color;
layout(location = 1) out vec2 out_texcoord;

void main() {
    gl_Position = vec4(in_pos, 1.0);
    out_color = in_color;
    out_texcoord = in_texcord;
}

Before we bring the texture into it, let’s make sure our texture coordinates are right, by showing them as colours. In the fragment shader:

#version 450

layout(location = 0) in vec3 in_color;
layout(location = 1) in vec2 in_texcoord;

layout(location = 0) out vec4 finalColor;

void main() {
    finalColor = vec4(in_texcoord, 1.0, 1.0);
}

The U coordinate goes into red, V into green, and blue is always on. Remember to recompile both shaders with glslc and re-embed them into sample.hpp with tools/embed_spv.py, then run it:

Texture coordinates, visualized
Texture coordinates, visualized

Blue at the top left ((0, 0)), magenta at the top right ((1, 0)), white at the bottom right ((1, 1)) and cyan at the bottom left ((0, 1)), with smooth gradients in between. Visualizing values as colours like this is one of the simplest (and most useful) ways of debugging shaders!

Sampling the texture

Now for the real thing. Reading a texture in a shader is called sampling it, and here’s our fragment shader doing just that:

#version 450

layout(location = 0) in vec3 in_color;
layout(location = 1) in vec2 in_texcoord;

layout(binding = 0) uniform sampler2D texture_sampler;

layout(location = 0) out vec4 finalColor;

void main() {
    finalColor = texture(texture_sampler, in_texcoord);
}
  • uniform sampler2D texture_sampler: A 2D texture, along with the settings for how to read from it. uniform means it’s the same for every fragment in a draw, unlike our in values. And it doesn’t come from the vertex shader, it comes from outside the pipeline altogether, which is what that layout(binding = 0) is about, as we’ll see in a moment.
  • texture(texture_sampler, in_texcoord): Reads the texture at our texture coordinate, and returns its colour. Not necessarily the colour of a single texel, as we’ll see when we create our sampler.

Recompile and re-embed the fragment shader, and run it, and the validation layers will complain as soon as we create our pipeline. And they’re right: our shader now uses a texture, but our pipeline layout is still empty, so we’ve told the pipeline nothing about it. We haven’t given it any texture to use either. To do both, we need descriptors.

THEORY: Descriptors

Our shaders can only access outside resources, like textures and uniform buffers, through descriptors. A descriptor is a small object that describes a resource to the GPU: for our texture, it says “this image view, read using this sampler, which is in this layout”. Vulkan organizes them like this:

  • Descriptor: Points at a single resource (or an array of them). There are different types of descriptors for different kinds of resources. Ours is a VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, which bundles an image view with a sampler, matching the sampler2D in our shader.
  • Descriptor set: A group of descriptors, each at a numbered binding. Shaders refer to a descriptor using its set and binding numbers: layout(set = 0, binding = 0). We left out the set in our shader, which means set 0.
  • Descriptor set layout: The shape of a descriptor set: which bindings it has, the type and count of each, and which shader stages can access them. Like a struct definition, where descriptor sets are the instances.
  • Pipeline layout: Remember the empty pipeline layout from the coloured triangle post? It’s the list of descriptor set layouts a pipeline uses (plus push constants, which we’ll get to in another post). Set 0 in the shader is the first layout in this list, set 1 is the second, and so on. The pipeline is compiled against this, so the shader and the pipeline layout have to agree.
  • Descriptor pool: Descriptor sets are allocated from a pool, much like command buffers are allocated from a command pool. The pool has to be created with room for the number of sets, and the number of descriptors of each type, we’ll allocate from it.

Putting a texture in front of a shader then goes like this:

  1. Create a descriptor set layout describing our bindings, and a pipeline layout listing it. Create the pipeline with that pipeline layout
  2. Create a descriptor pool, and allocate a descriptor set from it, using our set layout
  3. Write our image view and sampler into the set, with vkUpdateDescriptorSets
  4. Bind the set before drawing, with vkCmdBindDescriptorSets

One rule to keep in mind: a descriptor set can’t be written to while a command buffer that uses it is still recording or executing. We only write ours once, during initialize, so that’s not a problem for us here, but it will matter once our data starts changing every frame.

Why the sets, then? Why not just one big list of bindings? It lets us group our resources by how often they change. A typical renderer might have one set for per-frame data (like the camera), one per material (its textures), and one per object. Changing materials then only means binding a different set 1, while set 0 stays put.

The ShaderDataTable class

That’s a lot of different objects! Rather than juggling them all in SampleVulkan, let’s wrap them up in a class. I’ll call it a ShaderDataTable: a table of all the data our shaders can access, where we look entries up by name.

Part 1: layouts, the pool and the sets

Here’s shader_data_table.hpp:

// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include "image.hpp"

class Pipeline;

class ShaderDataTable
{
public:
    struct EntryDescription
    {
        std::string name{};
        uint32_t set{};
        uint32_t binding{};
        VkDescriptorType type{};
        uint32_t count{};
        VkShaderStageFlags stages{};
    };

public:
    static Result<Box<ShaderDataTable>> create(VkDevice device, std::span<const EntryDescription> entries);

    ShaderDataTable(const ShaderDataTable&) = delete;
    ~ShaderDataTable();

    bool write_image_entry(const std::string& name, const Image* image, VkSampler sampler, uint32_t index = 0);
    bool write_buffer_entry(const std::string& name, const Buffer* buffer, VkDeviceSize offset = 0, VkDeviceSize size = 0, uint32_t index = 0);
    void flush_writes();

    void bind(VkCommandBuffer cmd);

    VkPipelineLayout get_pipeline_layout() const { return m_pipeline_layout; }

protected:
    ShaderDataTable(VkDevice device): m_device(device) {}

private:
    VkDevice m_device{};

    VkDescriptorPool m_pool{};
    VkPipelineLayout m_pipeline_layout{};
    std::vector<VkDescriptorSet> m_sets{};
    std::vector<VkDescriptorSetLayout> m_set_layouts{};
    std::map<std::string, std::pair<uint32_t, uint32_t>> m_entry_map{};

    std::vector<VkWriteDescriptorSet> m_queued_writes{};
    std::deque<VkDescriptorImageInfo> m_queued_write_image_infos{};
    std::deque<VkDescriptorBufferInfo> m_queued_write_buffer_infos{};
};

An EntryDescription describes one binding: a name to refer to it by, which set and binding it’s at, its descriptor type, how many descriptors it holds (more than 1 for arrays) and which shader stages use it. m_entry_map maps each name to its {set, binding} pair. We’ll look at the writing half of the class in part 2.

create starts off by working out how many sets we need, and grouping the bindings by set:

Result<Box<ShaderDataTable>> ShaderDataTable::create(VkDevice device, std::span<const EntryDescription> entries)
{
    Box<ShaderDataTable> table{new ShaderDataTable(device)};

    uint32_t set_count{};
    for(const auto& entry: entries) {
      set_count = std::max(entry.set + 1, set_count);
    }

    std::map<VkDescriptorType, uint32_t> descriptor_counts{};
    std::vector<std::vector<VkDescriptorSetLayoutBinding>> bindings{set_count};
    for(const auto& entry: entries) {
      bindings[entry.set].push_back({
        .binding = entry.binding,
        .descriptorType = entry.type,
        .descriptorCount = entry.count,
        .stageFlags = entry.stages,
      });

      descriptor_counts[entry.type] += entry.count;

      table->m_entry_map[entry.name] = {entry.set, entry.binding};
    }
  • set_count: The highest set number we’ve been given, plus one. If someone only uses set 2, sets 0 and 1 simply end up with no bindings, which is allowed.
  • bindings: One list of VkDescriptorSetLayoutBindings per set. Each is just our EntryDescription in Vulkan’s terms.
  • descriptor_counts: The total number of descriptors of each type, across all sets. We’ll need these to size our pool. std::map’s [] starts off a missing entry at 0, so we can just keep adding to it.

Next, a descriptor set layout for each set, and the pipeline layout listing them all:

    table->m_set_layouts.resize(set_count);
    for(uint32_t i = 0; i < set_count; i++) {
      VkDescriptorSetLayoutCreateInfo set_layout_create_info{
        .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
        .bindingCount = (uint32_t)bindings[i].size(),
        .pBindings = bindings[i].data(),
      };

      if (vkCreateDescriptorSetLayout(device, &set_layout_create_info, nullptr, &table->m_set_layouts[i]) != VK_SUCCESS)
        return "Failed to create the descriptor set layout";
    }

    VkPipelineLayoutCreateInfo layout_create_info{
      .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
      .setLayoutCount = (uint32_t)table->m_set_layouts.size(),
      .pSetLayouts = table->m_set_layouts.data(),
      .pushConstantRangeCount = 0, // we'll talk about push constants in another post
    };

    if (vkCreatePipelineLayout(device, &layout_create_info, nullptr, &table->m_pipeline_layout) != VK_SUCCESS)
      return "Failed to create the pipeline layout";

Then the pool, with room for exactly what we need:

    std::vector<VkDescriptorPoolSize> pool_sizes{};
    for(const auto& dc: descriptor_counts) {
      pool_sizes.push_back({.type = dc.first, .descriptorCount = dc.second});
    }

    VkDescriptorPoolCreateInfo pool_create_info{
      .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
      .maxSets = set_count,
      .poolSizeCount = (uint32_t)pool_sizes.size(),
      .pPoolSizes = pool_sizes.data(),
    };

    if (vkCreateDescriptorPool(device, &pool_create_info, nullptr, &table->m_pool) != VK_SUCCESS)
      return "Failed to create the descriptor pool";
  • pool_sizes: One VkDescriptorPoolSize per descriptor type, saying how many descriptors of that type the pool can hand out in total.
  • maxSets: How many sets can be allocated from the pool. Our table only ever allocates its own sets, once, so that’s set_count.

And finally, the sets themselves:

    table->m_sets.resize(set_count);
    VkDescriptorSetAllocateInfo alloc_info{
        .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
        .descriptorPool = table->m_pool,
        .descriptorSetCount = (uint32_t)table->m_set_layouts.size(),
        .pSetLayouts = table->m_set_layouts.data(),
    };

    if (vkAllocateDescriptorSets(device, &alloc_info, table->m_sets.data()) != VK_SUCCESS)
      return "Failed to allocate descriptor sets";

    return table;
}

One set per layout, all in a single call.

You might be wondering why we hold on to the set layouts, once the pipeline layout and the sets have been created. Can’t we destroy them right away? It’s tempting, but no: a descriptor set can’t be written to with vkUpdateDescriptorSets once the layout it was allocated with has been destroyed. So they live as long as the table does, and the destructor cleans everything up:

ShaderDataTable::~ShaderDataTable()
{
    if (!m_device)
        return;

    for (size_t i = 0; i < m_set_layouts.size(); i++)
      vkDestroyDescriptorSetLayout(m_device, m_set_layouts[i], nullptr);
    m_set_layouts.clear();

    if (m_pool) vkDestroyDescriptorPool(m_device, m_pool, nullptr);

    if (m_pipeline_layout) vkDestroyPipelineLayout(m_device, m_pipeline_layout, nullptr);
}

Destroying the pool also frees all the sets allocated from it, so we don’t free those one by one.

The pipeline layout’s new home

The pipeline layout now belongs to the ShaderDataTable, so Pipeline no longer creates its own. In pipeline.hpp, replace #include "common.hpp" with #include "shader_data_table.hpp", remove the m_layout member, and add a new parameter to create, in both pipeline.hpp and pipeline.cpp:

    static Result<Box<Pipeline>> create(VkDevice device, VkFormat color_attachment_format,
        std::span<const VkVertexInputBindingDescription> input_bindings,
        std::span<const VkVertexInputAttributeDescription> input_attributes,
        const ShaderDataTable* data_table,
        std::span<const uint32_t> vertex_shader_source, std::span<const uint32_t> fragment_shader_source);

In pipeline.cpp, remove the VkPipelineLayoutCreateInfo and the vkCreatePipelineLayout call from the start of create, and use the table’s layout instead:

    .layout = data_table->get_pipeline_layout(),

The destructor now only destroys the pipeline:

Pipeline::~Pipeline()
{
  if (!m_device)
    return;

  if (m_handle) vkDestroyPipeline(m_device, m_handle, nullptr);
}

Part 2: writing and binding

Our set exists now, but it’s empty. Its descriptors don’t point at anything yet. To fill them in, we write to them with vkUpdateDescriptorSets, which takes a list of VkWriteDescriptorSets. Rather than calling it once per descriptor, our table queues the writes up, and does them all at once in flush_writes.

First though, ShaderDataTable needs a few things from our image. In image.hpp:

  VkImageView get_view() const { return m_view_handle; }
  VkImageLayout get_layout() const { return m_layout; }
  VkFormat get_format() const { return m_format; }

Here’s write_image_entry:

bool ShaderDataTable::write_image_entry(const std::string& name, const Image* image, VkSampler sampler, uint32_t index)
{
    const auto entry = m_entry_map.find(name);
    if (entry == m_entry_map.end())
        return false;

    m_queued_write_image_infos.push_back(VkDescriptorImageInfo{
      sampler,
      image->get_view(),
      image->get_layout(),
    });

    m_queued_writes.push_back({
        .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
        .dstSet = m_sets[entry->second.first],
        .dstBinding = entry->second.second,
        .dstArrayElement = index,
        .descriptorCount = 1,
        .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
        .pImageInfo = &m_queued_write_image_infos.back(),
    });

    return true;
}
  • Looking up the entry: If there’s no entry with that name, we return false, so that a typo in a name doesn’t fail silently.
  • VkDescriptorImageInfo: What the descriptor will point at: our sampler, our image view, and the layout the image will be in when the shader reads it. Note that it takes the image’s layout at the time of the write, so we have to write the descriptor after our image has been transitioned to SHADER_READ_ONLY_OPTIMAL.
  • VkWriteDescriptorSet: Which set, binding and array element to write to, and the type of the descriptor. index is the array element, for bindings that hold more than one descriptor, 0 otherwise. Its pImageInfo points at the image info we just queued.

That pointer is why the infos live in a std::deque, and not a std::vector. The write only points at the info, and nothing gets read until vkUpdateDescriptorSets in flush_writes. So every info has to stay at the same address until then. A std::vector moves all of its elements to a new chunk of memory whenever it grows, which would leave all our earlier writes pointing at memory that’s no longer theirs! A std::deque never moves existing elements when we push_back, so our pointers stay valid.

write_buffer_entry is the same thing, for buffers:

bool ShaderDataTable::write_buffer_entry(const std::string& name, const Buffer* buffer, VkDeviceSize offset, VkDeviceSize size, uint32_t index)
{
    const auto entry = m_entry_map.find(name);
    if (entry == m_entry_map.end())
        return false;

    m_queued_write_buffer_infos.push_back(VkDescriptorBufferInfo{
        buffer->get_handle(),
        offset,
        (size == 0) ? buffer->get_size() : size,
    });

    m_queued_writes.push_back({
        .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
        .dstSet = m_sets[entry->second.first],
        .dstBinding = entry->second.second,
        .dstArrayElement = index,
        .descriptorCount = 1,
        .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // for now we assume all writes are uniform buffers
        .pBufferInfo = &m_queued_write_buffer_infos.back(),
    });

    return true;
}

We don’t use it in this post, but we’ll need it for uniform buffers soon enough. A size of 0 means “the whole buffer”.

flush_writes does all the queued writes in one go, and then clears the queues:

void ShaderDataTable::flush_writes()
{
    if (m_queued_writes.empty())
        return;

    vkUpdateDescriptorSets(m_device, m_queued_writes.size(), m_queued_writes.data(), 0, nullptr);

    m_queued_write_image_infos.clear();
    m_queued_write_buffer_infos.clear();

    m_queued_writes.clear();
}

The last two parameters of vkUpdateDescriptorSets are for copying descriptors from one set to another, which we don’t need. Once it returns, Vulkan is done with our infos, so it’s safe to clear them.

And bind binds all of our sets, for the draws that follow:

void ShaderDataTable::bind(VkCommandBuffer cmd)
{
    vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline_layout, 0, m_sets.size(), m_sets.data(), 0, nullptr);
}

The 0 after the pipeline layout is the first set number to bind to: our sets go into sets 0, 1, and so on, in order. The last two parameters are for dynamic offsets, which we don’t use.

The sampler

The last piece of the puzzle is the sampler, which says how to read from a texture. Texture coordinates rarely land exactly on the centre of a texel, so the sampler decides what colour to return when they don’t. It also decides what to do with texture coordinates outside of 0 to 1.

A sampler isn’t tied to any particular image, so one sampler can be used with as many textures as we like. We add it to SampleVulkan:

  VkSampler m_texture_sampler{};

And create it in initialize, right before our texture:

  {
    VkSamplerCreateInfo create_info{
      .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
      .magFilter = VK_FILTER_NEAREST,
      .minFilter = VK_FILTER_NEAREST,
      .addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT,
      .addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT,
      .addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT,
    };

    if (vkCreateSampler(m_device, &create_info, nullptr, &m_texture_sampler) != VK_SUCCESS) {
      printf("Failed to create the texture sampler\n");
      return false;
    }
  }
  • magFilter: The filter used when the texture is magnified, meaning each texel covers more than one pixel on screen. That’s our case: our 32×32 texture covers a 400×300 pixel quad (in an 800×600 window), so each texel covers about 12×9 pixels.
  • minFilter: The filter used when the texture is minified, meaning each texel covers less than one pixel, like a big texture on something far away.
  • addressModeU/V/W: What to do with texture coordinates outside of 0 to 1, for each axis. REPEAT tiles the texture. Others clamp to the edge, or mirror the texture.

Everything else is left at its default, which is fine for our single mip level texture. For one, the zero valued maxLod keeps sampling to our one and only mip level.

There are two filters to choose from:

  • VK_FILTER_NEAREST: Return the texel closest to the texture coordinate. Sharp, and blocky up close, like pixel art.
  • VK_FILTER_LINEAR: Blend the 4 closest texels, weighted by how close each one is. Smooth, and blurry up close.

I originally went with LINEAR, which is what you’d usually pick for photos and most game textures. On our tiny checkerboard though, the result is quite blurry. Every one of those 12×9 pixel texels blends into its neighbours, so each edge between a violet and a white square turns into a gradient about a texel wide. With NEAREST, every pixel takes the colour of exactly one texel, and our edges stay perfectly sharp. Try switching between the two, it’s a great way to see what a sampler actually does!

The sampler is destroyed in the destructor, right after the texture:

    vkDestroySampler(m_device, m_texture_sampler, nullptr);

Putting it all together

Let’s wire everything up in SampleVulkan. First, the table, next to the other new members in sample.hpp:

  Box<ShaderDataTable> m_shader_data_table{};

We create it in initialize, right before the pipeline (which needs its layout), with a single entry for our texture:

  CHECK_RESULT(
    ShaderDataTable::create(
      m_device,
      std::initializer_list<ShaderDataTable::EntryDescription>{
        {.name = "texture_sampler", .set = 0, .binding = 0, .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .count = 1, .stages = VK_SHADER_STAGE_FRAGMENT_BIT,},
      }
    ),
    m_shader_data_table
  );

A single combined image sampler at set 0, binding 0, used in the fragment shader. It matches the layout(binding = 0) uniform sampler2D texture_sampler in our shader, name and all (although the name is just for us, Vulkan only goes by the numbers).

The pipeline gets the table:

  CHECK_RESULT(
    Pipeline::create(
      m_device,
      m_swapchain_format.format,
      std::initializer_list<VkVertexInputBindingDescription>{
        {.binding = 0, .stride = sizeof(Vertex), .inputRate = VK_VERTEX_INPUT_RATE_VERTEX},
      },
      std::initializer_list<VkVertexInputAttributeDescription>{
        VkVertexInputAttributeDescription{.location = 0, .binding = 0, .format = VK_FORMAT_R32G32B32_SFLOAT, .offset = offsetof(Vertex, pos)},
        VkVertexInputAttributeDescription{.location = 1, .binding = 0, .format = VK_FORMAT_R32G32B32_SFLOAT, .offset = offsetof(Vertex, colour)},
        VkVertexInputAttributeDescription{.location = 2, .binding = 0, .format = VK_FORMAT_R32G32_SFLOAT, .offset = offsetof(Vertex, texcoord)},
      },
      m_shader_data_table.get(),
      SHADER_SPV_VERT,
      SHADER_SPV_FRAG
    ),
    m_graphics_pipeline
  );

At the very end of initialize, once our texture has its pixels and is in SHADER_READ_ONLY_OPTIMAL, we write it into the table:

  if (!m_shader_data_table->write_image_entry("texture_sampler", m_texture_image.get(), m_texture_sampler)) {
    printf("Failed to write texture image to shader data table\n");
    return false;
  }
  m_shader_data_table->flush_writes();

In draw_frame, we bind the table along with our buffers, before the draw call:

  m_graphics_pipeline->bind(cmd);

  m_vertex_buffer->bind(cmd);
  m_index_buffer->bind(cmd);

  m_shader_data_table->bind(cmd);

  vkCmdDrawIndexed(cmd, sizeof(INDICES)/sizeof(INDICES[0]), 1, 0, 0, 0);

And in the destructor, the pipeline goes first, as it was created using the table’s layout, followed by the table itself:

    m_graphics_pipeline.reset();
    m_shader_data_table.reset();

Run it, and…

Our checkerboard texture
Our checkerboard texture

There it is, our texture, on our quad!

You might notice that the squares are a bit wider than they are tall. That’s not the texture’s fault: our quad is a square in clip space, but our window is 4:3, so everything gets stretched horizontally. We’ll fix that once we get to projection matrices.

Loading images from files

Our checkerboard did its job: it proved that our whole texture path works, from the staging buffer all the way to the fragment shader. But real textures come from image files, so let’s finish off by loading one.

Image files like PNGs and JPGs are compressed, so they have to be decoded into plain pixels before we can upload them. Writing a PNG decoder is a project of its own, so we’ll use stb_image, by Sean Barrett. It’s a single header library: the whole thing is one file, which we just drop into our project. No CMake changes, nothing to build separately. It loads PNG, JPG, BMP, TGA and a few more formats, and it’s public domain (or MIT, if you prefer), so we’re free to use it however we like.

Download stb_image.h from the link above, and save it next to our other source files as stb_image.hpp.

A single header library contains both the declarations and the implementation, but the implementation is only compiled in where we ask for it. We do that in exactly one .cpp file, by defining STB_IMAGE_IMPLEMENTATION before including the header. Any other file that needs stb_image would just include it, without the define. Image loading belongs with our images, so at the top of image.cpp:

#include "image.hpp"

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.hpp"

We add a new static function to Image, in image.hpp:

  static bool load_rgba_from_file(const std::string& path, std::vector<uint8_t>& pixels, VkExtent2D& extent);

It’s static, as it doesn’t need an Image to work with: it only loads pixels into CPU memory, and what we do with them afterwards is up to us. Here it is, at the end of image.cpp:

bool Image::load_rgba_from_file(const std::string& path, std::vector<uint8_t>& pixels, VkExtent2D& extent)
{
    int w, h, n;
    const auto pixel_data = stbi_load(path.c_str(), &w, &h, &n, STBI_rgb_alpha);
    if (!pixel_data)
        return false;

    extent.width = (uint32_t)w;
    extent.height = (uint32_t)h;

    pixels.resize(w * h * 4);
    memcpy(pixels.data(), pixel_data, pixels.size());

    stbi_image_free(pixel_data);

    return true;
}
  • stbi_load: Loads and decodes the file, and returns a pointer to its pixels, or nullptr if it fails (stbi_failure_reason() can tell you why). It gives us the width and height in w and h, and the number of channels in the file in n. The pixels come out exactly the way our checkerboard was laid out: row after row, starting from the top left, with no padding in between.
  • STBI_rgb_alpha: Asks for 4 channels, R, G, B and A, whatever the file has. The texture we’ll load is a PNG with no alpha channel, so it only has 3. stb_image adds a fully opaque alpha for us, so the pixels match our R8G8B8A8_SRGB format. Why not just use a 3 channel format? Because GPUs aren’t required to support sampling from 3 channel 8-bit formats like R8G8B8_SRGB, and many don’t, so 4 channels it is.
  • memcpy and stbi_image_free: stb_image allocates the pixels itself, and they have to be freed with stbi_image_free. We copy them into the caller’s std::vector, which cleans up after itself, and free the original right away. That way, the caller never has to know about stb_image at all.

In initialize, the checkerboard gives way to our new function. The pixels and the extent now come from the file:

  {
    std::vector<uint8_t> pixels{};
    VkExtent2D extent{};

    if (!Image::load_rgba_from_file("resources/Ground037_1K-PNG_Color.png", pixels, extent)) {
      printf("Failed to load texture data from the disk\n");
      return false;
    }

    CHECK_RESULT(
      Image::create(
        m_device, 
        m_allocator,
        VK_FORMAT_R8G8B8A8_SRGB,
        extent,
        VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT // We want to sample this image from fragment shader and 
                                                                          // copy data from staging buffer into this image.
      ),
    m_texture_image);

The rest of the block, transitions and copy included, stays exactly the same. pixels is still a std::vector<uint8_t>, so pixels.data() and pixels.size() work just like before. That’s the nice thing about having built the upload path around plain pixels: it doesn’t care where they came from. get_checkerboard_pattern_pixels is still in sample.cpp too, so you can always switch back to it.

The path is relative to the working directory, so run the app from the sample’s folder (like we’ve been doing all along), or it won’t find the file.

Here’s the texture we’re loading, which goes into a new resources folder:

Ground037, from ambientCG
Ground037, from ambientCG

It’s Ground037 from ambientCG, a great source of free textures, all released under the CC0 license (public domain). The only change I made was to downscale it from 1024×1024 to 256×256 using GIMP, to keep the file size down.

Last but not least, the sampler. NEAREST was the right call for our checkerboard, but this is a photo, and here we want smooth over sharp. Our 256×256 texture still gets magnified a little, each texel covering about 1.5×1.2 pixels, and NEAREST would make that look blocky. So it’s back to LINEAR:

    VkSamplerCreateInfo create_info{
      .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
      .magFilter = VK_FILTER_LINEAR,
      .minFilter = VK_FILTER_LINEAR,
      .addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT,
      .addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT,
      .addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT,
    };

Run it one last time, and…

End Result
End Result

A real texture, loaded from a file, on our quad!

Loading shaders from files

While we’re loading things from disk, there’s one more thing that deserves the same treatment: our shaders. Ever since the coloured triangle post, we’ve been embedding them into sample.hpp as arrays of numbers. That kept things simple at the start, but you’ve probably noticed how tedious it gets: every little shader change means compiling it, running tools/embed_spv.py, pasting the result into sample.hpp and rebuilding the whole app. On top of that, those arrays make up a good chunk of our source code, while being completely unreadable.

So let’s load the SPIR-V straight from files instead. We still compile our shaders with glslc, but now the output goes into our resources folder, next to our texture:

glslc shaders/default.vert -o resources/default.vert.spv
glslc shaders/default.frag -o resources/default.frag.spv

And that’s it! No more embedding. Go ahead and delete SHADER_SPV_VERT and SHADER_SPV_FRAG from sample.hpp.

To read the files, we’ll use a std::ifstream, so add #include <fstream> to the top of sample.cpp. Then, right after get_checkerboard_pattern_pixels:

static Result<std::vector<uint32_t>> load_shader_from_file(const std::string& path)
{
  std::ifstream f(path, std::ios::in | std::ios::binary | std::ios::ate);
  if (!f.is_open())
    return "Failed to open shader file \""+ path + "\".";

  std::vector<uint32_t> data;
  data.resize(f.tellg() >> 2);
  f.seekg(SEEK_SET);
  f.read((char*)data.data(), data.size() << 2);

  return std::move(data);
}
  • Opening the file: std::ios::binary, as SPIR-V is a binary format, and we don’t want anything messing with its bytes (like line ending conversions on Windows). std::ios::ate opens the file with the read position “at the end”, which is a handy trick for getting its size: tellg then tells us how many bytes there are.
  • Why uint32_t? SPIR-V is a stream of 32-bit words, and VkShaderModuleCreateInfo takes it as a const uint32_t*, which has to be 4-byte aligned. Reading into a std::vector<uint32_t> guarantees that. A std::vector<char> wouldn’t, and casting its data to a uint32_t* could get us into trouble. The >> 2 turns the size in bytes into a number of words, and the << 2 turns it back again, same as we already do in Pipeline::create.
  • Reading: seekg jumps back to the start of the file, and read reads all of it straight into our vector.
  • The Result: If the file can’t be opened, we return an error that includes the path, so we know exactly which file is missing. Otherwise, we move the vector into the Result, rather than copying it.

In initialize, we load both shaders right before creating our pipeline:

  std::vector<uint32_t> vertex_shader_data, fragment_shader_data{};
  CHECK_RESULT(load_shader_from_file("resources/default.vert.spv"), vertex_shader_data);
  CHECK_RESULT(load_shader_from_file("resources/default.frag.spv"), fragment_shader_data);

And pass them along instead of the embedded arrays:

      m_shader_data_table.get(),
      vertex_shader_data,
      fragment_shader_data
    ),
    m_graphics_pipeline
  );

Notice that Pipeline doesn’t change at all. It has taken its shaders as std::span<const uint32_t>s since the VMA, GLM and refactoring post, and as we said back then, a std::vector loaded from a file works just as well as our embedded arrays did. That decision is paying off now!

Same as with our texture, these paths are relative to the working directory, so remember to run the app from the sample’s folder. If you don’t, you’ll get a Failed to open shader file "resources/default.vert.spv"., telling you exactly what went wrong.

Run it, and you should see the exact same textured quad as before. The difference is in the workflow: change a shader, recompile it with glslc, and just run the app again. No embedding, and no rebuilding!

The compiled .spv files are in the resources folder of the GitHub repo too, so you can run the sample without compiling the shaders yourself.

Wrapping up

And that’s it! Build it, run it, and you should see the textured quad, with no validation errors.

Let’s recap what we did:

  1. Wrote an Image class on top of VMA, with an image view, and moved transition_image_layout into it
  2. Generated a checkerboard of R8G8B8A8_SRGB pixels
  3. Uploaded them through a staging buffer with vkCmdCopyBufferToImage, with layout transitions before and after the copy
  4. Checked our texture with RenderDoc, before writing any shader code for it
  5. Added texture coordinates to our vertices, and checked them by visualizing them as colours
  6. Sampled the texture in our fragment shader
  7. Learned about descriptors, descriptor sets, set layouts, pools and pipeline layouts, and wrapped them all up in the ShaderDataTable class
  8. Created a sampler, and saw the difference between nearest and linear filtering
  9. Loaded a real texture from a PNG file with stb_image
  10. Replaced our embedded shaders with SPIR-V files loaded at runtime

Go ahead and play around with it! Load your own images, switch back to the checkerboard and change its colours or the size of its squares, set some texture coordinates to 2.0 and watch REPEAT tile the texture, or try out the other address modes.

Next up: Rotating Cube

Time to leave the flat world behind! We’ll turn our quad into a cube, and set it spinning. That means transformations: model, view and projection matrices with GLM (which also fixes our stretched aspect ratio). We’ll get those matrices to our shaders through uniform buffers, putting write_buffer_entry to use at last. And with faces now able to hide each other, we’ll need a depth buffer, so the faces at the back don’t get drawn over the ones at the front.

References

  1. RenderDoc, and its documentation
  2. Vulkan Guide: Synchronization examples
  3. Vulkan Memory Allocator: Recommended usage patterns
  4. stb_image
  5. ambientCG: Ground037
  6. VkGuide
  7. The Vulkan specification (version 1.4.364 at the time of writing)

Full Source Code

The complete sample is now just under 2200 lines in total, spread over a few more files than last time (and with the embedded shader code gone, it’s all actual code now!). That’s not counting stb_image.hpp, which is the unmodified stb_image.h from stb. The resources/ folder can be found in the GitHub repo along with everything else.

Show CMakeLists.txt
cmake_minimum_required(VERSION 3.28)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

project(I_A_S_ME_VulkanSeries)

include(FetchContent)

set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE)

FetchContent_Declare(glfw
    GIT_REPOSITORY https://github.com/glfw/glfw.git
    GIT_TAG 3.5.1
    GIT_SHALLOW TRUE
)

FetchContent_Declare(VulkanMemoryAllocator
    GIT_REPOSITORY https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator.git
    GIT_TAG v3.5.0
    GIT_SHALLOW TRUE
)

FetchContent_Declare(glm
    GIT_REPOSITORY https://github.com/g-truc/glm.git
    GIT_TAG 1.0.3
    GIT_SHALLOW TRUE
)

FetchContent_MakeAvailable(glfw VulkanMemoryAllocator glm)

add_executable(App
    vma.cpp
    main.cpp
    image.cpp
    buffer.cpp
    sample.cpp
    pipeline.cpp
    shader_data_table.cpp
)

target_link_libraries(App PRIVATE 
    glfw
    vulkan
    glm::glm
    GPUOpen::VulkanMemoryAllocator
)
Show common.hpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include <map>
#include <span>
#include <deque>
#include <cstdio>
#include <memory>
#include <string>
#include <cstddef>
#include <variant>
#include <cassert>
#include <type_traits>

#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>

#include <vk_mem_alloc.h>

#include <glm/glm.hpp>

#define CHECK_RESULT(_result, _var)             \
{                                               \
  auto result = _result;                        \
  if (result.is_error()) {                      \
    printf("%s\n", result.get_error().c_str()); \
    return false;                               \
  }                                             \
  _var = std::move(result).take_value();        \
}

struct Ok {};

// A very simple Result type to hold either
// an error message or the value. To be used
// mostly as return types in failable functions. 
template<typename T = Ok>
class [[nodiscard]] Result
{
    static_assert(!std::is_same_v<std::decay_t<T>, std::string>, "std::string values are not allowed");
    static_assert(!std::is_same_v<T, void>, "void values are not allowed. Use Result<> or Result<Ok> instead.");

public:
    Result(std::nullptr_t) = delete;

    constexpr Result(const char* error): m_variant(std::in_place_index<1>, error) {}
    constexpr Result(T&& value): m_variant(std::in_place_index<0>, std::move(value)) {}
    constexpr Result(const std::string& error): m_variant(std::in_place_index<1>, error) {}

    constexpr bool is_ok() const { return m_variant.index() == 0; }
    constexpr bool is_error() const { return m_variant.index() == 1; }

    T get_value() && = delete;
    T& get_value() & { assert(is_ok()); return std::get<0>(m_variant); }
    const T& get_value() const& { assert(is_ok()); return std::get<0>(m_variant); }

    T take_value() && { assert(is_ok()); return std::get<0>(std::move(m_variant)); }
    
    const std::string& get_error() const& { assert(is_error()); return std::get<1>(m_variant); }
    std::string get_error() && { assert(is_error()); return std::get<1>(std::move(m_variant)); }

private:
    std::variant<T, std::string> m_variant;
};

// Alias std::unique_ptr to Box. Easier to type.
// (Inspired by Rust of course, just like Result above).
template<typename T>
using Box = std::unique_ptr<T>;
Show buffer.hpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include "common.hpp"

class Buffer
{
public:
    enum class EUsage
    {
        VERTEX,
        INDEX,
        STAGING,
    };

public:
    static Result<Box<Buffer>> create(VmaAllocator allocator, VkDeviceSize size, EUsage usage);

    Buffer(const Buffer&) = delete;
    ~Buffer();

    void bind(VkCommandBuffer cmd);

    VkDeviceSize get_size() const { return m_size; }

    VkBuffer get_handle() const { return m_handle; }

    bool copy_from_cpu(const void* data, VkDeviceSize size);

private:
    Buffer(VmaAllocator allocator): m_allocator(allocator) {}

private:
    EUsage m_usage{};
    VmaAllocator m_allocator{};
    
    VkBuffer m_handle{};
    VkDeviceSize m_size{};
    VmaAllocation m_allocation{};
};
Show buffer.cpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#include "buffer.hpp"

Result<Box<Buffer>> Buffer::create(VmaAllocator allocator, VkDeviceSize size, EUsage usage)
{
  Box<Buffer> buffer{new Buffer(allocator)};

  buffer->m_size = size;
  buffer->m_usage = usage;

  VkBufferUsageFlags _usage{};
  VmaAllocationCreateFlags _mem_flags{};

  switch (usage) {
    case EUsage::VERTEX:
      // vertex buffer + transfer dst (for copying data in from staging buffer)
      _usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
      break;

    case EUsage::INDEX:
      // index buffer + transfer dst (for copying data in from staging buffer)
      _usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
      break;

    case EUsage::STAGING:
      // allows transferring data out from this buffer (for copying)
      _usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;

      // allow writing to this buffer from CPU memory
      _mem_flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT;
      break;
  }

  VkBufferCreateInfo create_info{
    .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
    .size = size,
    .usage = _usage,
    .sharingMode = VK_SHARING_MODE_EXCLUSIVE, // we only need to use our buffers from a single queue family at a time
  };

  VmaAllocationCreateInfo alloc_create_info{
    .flags = _mem_flags,
    .usage = VMA_MEMORY_USAGE_AUTO, // when _mem_flags doesn't contain CPU access flags (like we set in above switch STAGING case), this picks fast GPU VRAM
  };

  if (vmaCreateBuffer(allocator, &create_info, &alloc_create_info, &buffer->m_handle, &buffer->m_allocation, nullptr) != VK_SUCCESS) {
    return "Failed to create the buffer";
  }

  return buffer;
}

Buffer::~Buffer()
{
  if (m_allocator && m_handle && m_allocation) 
    vmaDestroyBuffer(m_allocator, m_handle, m_allocation);
}

void Buffer::bind(VkCommandBuffer cmd)
{
  switch (m_usage) {
    case EUsage::VERTEX:
    {
      VkDeviceSize offset = 0;
      vkCmdBindVertexBuffers(cmd, 0, 1, &m_handle, &offset);
    }
    break;

    case EUsage::INDEX:
      vkCmdBindIndexBuffer(cmd, m_handle, 0, VK_INDEX_TYPE_UINT32);
    break;
    
    case EUsage::STAGING:
      assert(false); // we shouldn't call bind on a staging buffer
    break;
  }
}

bool Buffer::copy_from_cpu(const void* data, VkDeviceSize size)
{
  assert(m_usage == EUsage::STAGING);

  return vmaCopyMemoryToAllocation(m_allocator, data, m_allocation, 0, size) == VK_SUCCESS;
}
Show image.hpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include "buffer.hpp"

class Image
{
public:
  static bool load_rgba_from_file(const std::string& path, std::vector<uint8_t>& pixels, VkExtent2D& extent);

  static bool transition_image_layout(VkCommandBuffer cmd, VkImage image, VkImageLayout old_layout, VkImageLayout new_layout,
        uint32_t base_mip_level = 0, uint32_t level_count = 1, uint32_t base_array_layer = 0,
        uint32_t layer_count = 1);

public:
  static Result<Box<Image>> create(VkDevice device, VmaAllocator allocator, VkFormat format, VkExtent2D extent, VkImageUsageFlags usage);

  Image(const Image&) = delete;
  ~Image();

  bool transition_layout(VkCommandBuffer cmd, VkImageLayout new_layout);

  // make sure the image is in VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL layout before
  // calling this function
  bool copy_from_cpu(VkCommandBuffer cmd, const void* data, VkDeviceSize size);

  VkImageView get_view() const { return m_view_handle; }
  VkImageLayout get_layout() const { return m_layout; }
  VkFormat get_format() const { return m_format; }

private:
  Image(VkDevice device, VmaAllocator allocator): m_device(device), m_allocator(allocator) {}

private:
  VkDevice m_device{};
  VmaAllocator m_allocator{};

  VkImage m_handle{};
  VkImageView m_view_handle{};
  VkFormat m_format{};
  VkExtent2D m_extent{};
  VmaAllocation m_allocation{};
  VkImageLayout m_layout{VK_IMAGE_LAYOUT_UNDEFINED};

  Box<Buffer> m_staging_buffer; // only create if copy_from_cpu is called
};
Show image.cpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#include "image.hpp"

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.hpp"

Result<Box<Image>> Image::create(VkDevice device, VmaAllocator allocator, VkFormat format, VkExtent2D extent, VkImageUsageFlags usage)
{
  Box<Image> image(new Image(device, allocator));

  image->m_format = format;
  image->m_extent = extent;

  VkImageCreateInfo create_info{
    .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
    .imageType = VK_IMAGE_TYPE_2D, // for now we'll only need 2D images
    .format = format,
    .extent = VkExtent3D(extent.width, extent.height, 1),
    .mipLevels = 1, // we won't be bothering with mip mapping for now
    .arrayLayers = 1,
    .samples = VK_SAMPLE_COUNT_1_BIT, // we won't be bothering with multisampling for now either
    .tiling = VK_IMAGE_TILING_OPTIMAL, // we don't have any specific tiling we need so let vulkan pick the optimal one
    .usage = usage,
    .sharingMode = VK_SHARING_MODE_EXCLUSIVE, // we only need to use our images from a single queue family at a time
    .initialLayout = image->m_layout,
  };

  VmaAllocationCreateInfo alloc_create_info{
    .usage = VMA_MEMORY_USAGE_AUTO,
  };
  if (vmaCreateImage(allocator, &create_info, &alloc_create_info, &image->m_handle, &image->m_allocation, nullptr) != VK_SUCCESS)
    return "Failed to create the image";

  VkImageViewCreateInfo view_create_info{
    .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
    .image = image->m_handle,
    .viewType = VK_IMAGE_VIEW_TYPE_2D,
    .format = image->m_format,
    .subresourceRange = {
      .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
      .baseMipLevel = 0,
      .levelCount = 1,
      .baseArrayLayer = 0,
      .layerCount = 1,
    },
  };
  if (vkCreateImageView(device, &view_create_info, nullptr, &image->m_view_handle) != VK_SUCCESS)
    return "Failed to create the image view";

  return image;
}

Image::~Image()
{
  m_staging_buffer.reset();

  if (m_device && m_view_handle)
    vkDestroyImageView(m_device, m_view_handle, nullptr);

  if (m_allocator && m_allocation && m_handle)
    vmaDestroyImage(m_allocator, m_handle, m_allocation);
}

bool Image::transition_layout(VkCommandBuffer cmd, VkImageLayout new_layout)
{
  if (transition_image_layout(cmd, m_handle, m_layout, new_layout)) {
    m_layout = new_layout;
    return true;
  }

  return false;
}

bool Image::copy_from_cpu(VkCommandBuffer cmd, const void* data, VkDeviceSize size)
{
  assert(m_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);

  if (!m_staging_buffer || (m_staging_buffer->get_size() < size)) {
    m_staging_buffer.reset();

    CHECK_RESULT(
      Buffer::create(
        m_allocator,
        size,
        Buffer::EUsage::STAGING
      ),
      m_staging_buffer
    );
  }

  if (!m_staging_buffer->copy_from_cpu(data, size))
    return false;

  VkBufferImageCopy region{
    .bufferOffset = 0,
    .bufferRowLength = m_extent.width,
    .bufferImageHeight = m_extent.height,
    .imageSubresource = {
      .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
      .mipLevel = 0,
      .baseArrayLayer = 0,
      .layerCount = 1,
    },
    .imageOffset = {},
    .imageExtent = VkExtent3D(m_extent.width, m_extent.height, 1),
  };
  vkCmdCopyBufferToImage(cmd, m_staging_buffer->get_handle(), m_handle, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region);

  return true;
}

bool Image::transition_image_layout(VkCommandBuffer cmd, VkImage image, VkImageLayout old_layout,
                                           VkImageLayout new_layout, uint32_t base_mip_level, uint32_t level_count,
                                           uint32_t base_array_layer, uint32_t layer_count)
{
  VkPipelineStageFlags2 src_stage{}, dst_stage{};
  VkAccessFlags2 src_access{}, dst_access{};
  VkImageAspectFlags aspect{VK_IMAGE_ASPECT_COLOR_BIT};

#define _is_layout_pair(o, n) ((old_layout == o) && (new_layout == n))

  if (_is_layout_pair(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL))
  {
    src_stage = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT;
    src_access = VK_ACCESS_2_NONE;

    dst_stage = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT;
    dst_access = VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT;
  }
  else if (_is_layout_pair(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL))
  {
    // Wait for any depth writes from a previous use of this image (e.g. the previous frame)
    src_stage = VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT;
    src_access = VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;

    dst_stage = VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT;
    dst_access = VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;

    aspect = VK_IMAGE_ASPECT_DEPTH_BIT;
  }
  else if (_is_layout_pair(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR))
  {
    src_stage = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT;
    src_access = VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT;

    dst_stage = VK_PIPELINE_STAGE_2_NONE;
    dst_access = VK_ACCESS_2_NONE;
  }
  else if (_is_layout_pair(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL)) {
    src_stage = VK_PIPELINE_STAGE_2_NONE;
    src_access = VK_ACCESS_2_NONE;

    dst_stage = VK_PIPELINE_STAGE_2_COPY_BIT;
    dst_access = VK_ACCESS_2_TRANSFER_WRITE_BIT;
  }
  else if (_is_layout_pair(VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)) {
    src_stage = VK_PIPELINE_STAGE_2_COPY_BIT;
    src_access = VK_ACCESS_2_TRANSFER_WRITE_BIT;

    dst_stage = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT;
    dst_access = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT;
  }
  else
  {
    printf("Unknown layout transition\n");
    return false;
  }

#undef _is_layout_pair

  VkImageMemoryBarrier2 barrier{
      .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,

      .srcStageMask = src_stage,
      .srcAccessMask = src_access,

      .dstStageMask = dst_stage,
      .dstAccessMask = dst_access,

      .oldLayout = old_layout,
      .newLayout = new_layout,

      .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
      .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,

      .image = image,

      .subresourceRange =
          {
              .aspectMask = aspect,
              .baseMipLevel = base_mip_level,
              .levelCount = level_count,
              .baseArrayLayer = base_array_layer,
              .layerCount = layer_count,
          },
  };

  VkDependencyInfo dep_info{
      .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
      .imageMemoryBarrierCount = 1,
      .pImageMemoryBarriers = &barrier,
  };

  vkCmdPipelineBarrier2(cmd, &dep_info);

  return true;
}

bool Image::load_rgba_from_file(const std::string& path, std::vector<uint8_t>& pixels, VkExtent2D& extent)
{
    int w, h, n;
    const auto pixel_data = stbi_load(path.c_str(), &w, &h, &n, STBI_rgb_alpha);
    if (!pixel_data)
        return false;

    extent.width = (uint32_t)w;
    extent.height = (uint32_t)h;

    pixels.resize(w * h * 4);
    memcpy(pixels.data(), pixel_data, pixels.size());

    stbi_image_free(pixel_data);

    return true;
}
Show shader_data_table.hpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include "image.hpp"

class Pipeline;

class ShaderDataTable
{
public:
    struct EntryDescription
    {
        std::string name{};
        uint32_t set{};
        uint32_t binding{};
        VkDescriptorType type{};
        uint32_t count{};
        VkShaderStageFlags stages{};
    };

public:
    static Result<Box<ShaderDataTable>> create(VkDevice device, std::span<const EntryDescription> entries);

    ShaderDataTable(const ShaderDataTable&) = delete;
    ~ShaderDataTable();

    bool write_image_entry(const std::string& name, const Image* image, VkSampler sampler, uint32_t index = 0);
    bool write_buffer_entry(const std::string& name, const Buffer* buffer, VkDeviceSize offset = 0, VkDeviceSize size = 0, uint32_t index = 0);
    void flush_writes();

    void bind(VkCommandBuffer cmd);

    VkPipelineLayout get_pipeline_layout() const { return m_pipeline_layout; }

protected:
    ShaderDataTable(VkDevice device): m_device(device) {}

private:
    VkDevice m_device{};

    VkDescriptorPool m_pool{};
    VkPipelineLayout m_pipeline_layout{};
    std::vector<VkDescriptorSet> m_sets{};
    std::vector<VkDescriptorSetLayout> m_set_layouts{};
    std::map<std::string, std::pair<uint32_t, uint32_t>> m_entry_map{};

    std::vector<VkWriteDescriptorSet> m_queued_writes{};
    std::deque<VkDescriptorImageInfo> m_queued_write_image_infos{};
    std::deque<VkDescriptorBufferInfo> m_queued_write_buffer_infos{};
};
Show shader_data_table.cpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#include "shader_data_table.hpp"

Result<Box<ShaderDataTable>> ShaderDataTable::create(VkDevice device, std::span<const EntryDescription> entries)
{
    Box<ShaderDataTable> table{new ShaderDataTable(device)};

    uint32_t set_count{};
    for(const auto& entry: entries) {
      set_count = std::max(entry.set + 1, set_count);    
    }

    std::map<VkDescriptorType, uint32_t> descriptor_counts{};
    std::vector<std::vector<VkDescriptorSetLayoutBinding>> bindings{set_count};
    for(const auto& entry: entries) {
      bindings[entry.set].push_back({
        .binding = entry.binding,
        .descriptorType = entry.type,
        .descriptorCount = entry.count,
        .stageFlags = entry.stages,
      });

      descriptor_counts[entry.type] += entry.count;

      table->m_entry_map[entry.name] = {entry.set, entry.binding};
    }

    table->m_set_layouts.resize(set_count);
    for(uint32_t i = 0; i < set_count; i++) {
      VkDescriptorSetLayoutCreateInfo set_layout_create_info{
        .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
        .bindingCount = (uint32_t)bindings[i].size(),
        .pBindings = bindings[i].data(),
      };

      if (vkCreateDescriptorSetLayout(device, &set_layout_create_info, nullptr, &table->m_set_layouts[i]) != VK_SUCCESS)
        return "Failed to create the descriptor set layout";
    }

    VkPipelineLayoutCreateInfo layout_create_info{
      .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
      .setLayoutCount = (uint32_t)table->m_set_layouts.size(),
      .pSetLayouts = table->m_set_layouts.data(),
      .pushConstantRangeCount = 0, // we'll talk about push constants in another post
    };

    if (vkCreatePipelineLayout(device, &layout_create_info, nullptr, &table->m_pipeline_layout) != VK_SUCCESS)
      return "Failed to create the pipeline layout";

    std::vector<VkDescriptorPoolSize> pool_sizes{};
    for(const auto& dc: descriptor_counts) {
      pool_sizes.push_back({.type = dc.first, .descriptorCount = dc.second});
    }

    VkDescriptorPoolCreateInfo pool_create_info{
      .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
      .maxSets = set_count,
      .poolSizeCount = (uint32_t)pool_sizes.size(),
      .pPoolSizes = pool_sizes.data(),
    };

    if (vkCreateDescriptorPool(device, &pool_create_info, nullptr, &table->m_pool) != VK_SUCCESS)
      return "Failed to create the descriptor pool";

    table->m_sets.resize(set_count);
    VkDescriptorSetAllocateInfo alloc_info{
        .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
        .descriptorPool = table->m_pool,
        .descriptorSetCount = (uint32_t)table->m_set_layouts.size(),
        .pSetLayouts = table->m_set_layouts.data(),
    };

    if (vkAllocateDescriptorSets(device, &alloc_info, table->m_sets.data()) != VK_SUCCESS)
      return "Failed to allocate descriptor sets";

    return table;
}

ShaderDataTable::~ShaderDataTable()
{
    if (!m_device)
        return;

    for (size_t i = 0; i < m_set_layouts.size(); i++)
      vkDestroyDescriptorSetLayout(m_device, m_set_layouts[i], nullptr);
    m_set_layouts.clear();

    if (m_pool) vkDestroyDescriptorPool(m_device, m_pool, nullptr);

    if (m_pipeline_layout) vkDestroyPipelineLayout(m_device, m_pipeline_layout, nullptr);
}

bool ShaderDataTable::write_image_entry(const std::string& name, const Image* image, VkSampler sampler, uint32_t index)
{
    const auto entry = m_entry_map.find(name);
    if (entry == m_entry_map.end())
        return false;

    m_queued_write_image_infos.push_back(VkDescriptorImageInfo{
      sampler,
      image->get_view(),
      image->get_layout(),  
    });

    m_queued_writes.push_back({
        .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
        .dstSet = m_sets[entry->second.first],
        .dstBinding = entry->second.second,
        .dstArrayElement = index,
        .descriptorCount = 1,
        .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
        .pImageInfo = &m_queued_write_image_infos.back(),
    });

    return true;
}

bool ShaderDataTable::write_buffer_entry(const std::string& name, const Buffer* buffer, VkDeviceSize offset, VkDeviceSize size, uint32_t index)
{
    const auto entry = m_entry_map.find(name);
    if (entry == m_entry_map.end())
        return false;

    m_queued_write_buffer_infos.push_back(VkDescriptorBufferInfo{
        buffer->get_handle(),
        offset,
        (size == 0) ? buffer->get_size() : size,
    });

    m_queued_writes.push_back({
        .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
        .dstSet = m_sets[entry->second.first],
        .dstBinding = entry->second.second,
        .dstArrayElement = index,
        .descriptorCount = 1,
        .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // for now we assume all writes are uniform buffers
        .pBufferInfo = &m_queued_write_buffer_infos.back(),
    });

    return true;
}

void ShaderDataTable::flush_writes()
{
    if (m_queued_writes.empty())
        return;

    vkUpdateDescriptorSets(m_device, m_queued_writes.size(), m_queued_writes.data(), 0, nullptr);

    m_queued_write_image_infos.clear();
    m_queued_write_buffer_infos.clear();

    m_queued_writes.clear();
}

void ShaderDataTable::bind(VkCommandBuffer cmd)
{
    vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline_layout, 0, m_sets.size(), m_sets.data(), 0, nullptr);
}
Show pipeline.hpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include "shader_data_table.hpp"

class Pipeline
{
public:
    static Result<Box<Pipeline>> create(VkDevice device, VkFormat color_attachment_format, 
        std::span<const VkVertexInputBindingDescription> input_bindings,
        std::span<const VkVertexInputAttributeDescription> input_attributes,
        const ShaderDataTable* data_table,
        std::span<const uint32_t> vertex_shader_source, std::span<const uint32_t> fragment_shader_source);

    Pipeline(const Pipeline&) = delete;
    ~Pipeline();

    void bind(VkCommandBuffer cmd);

protected:
    Pipeline(VkDevice device): m_device(device) {}

private:
    VkDevice m_device{};

    VkPipeline m_handle{};
};
Show pipeline.cpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#include "pipeline.hpp"

Result<Box<Pipeline>> Pipeline::create(VkDevice device, VkFormat color_attachment_format,
        std::span<const VkVertexInputBindingDescription> input_bindings,
        std::span<const VkVertexInputAttributeDescription> input_attributes,
        const ShaderDataTable* data_table,
        std::span<const uint32_t> vertex_shader_source, std::span<const uint32_t> fragment_shader_source)
{
  Box<Pipeline> pipeline{new Pipeline(device)};

  VkShaderModule shader_modules[2];

  VkShaderModuleCreateInfo shader_module_create_infos[2] = {
    {
      .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
      .codeSize = vertex_shader_source.size() << 2,
      .pCode = vertex_shader_source.data(),
    },
    {
      .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
      .codeSize = fragment_shader_source.size() << 2,
      .pCode = fragment_shader_source.data(),
    },
  };

  if (vkCreateShaderModule(device, &shader_module_create_infos[0], nullptr, &shader_modules[0]) != VK_SUCCESS)
    return "Failed to create the shader module for vertex shader";

  if (vkCreateShaderModule(device, &shader_module_create_infos[1], nullptr, &shader_modules[1]) != VK_SUCCESS) {
    vkDestroyShaderModule(device, shader_modules[0], nullptr);
    return "Failed to create the shader module for fragment shader";
  }

  VkPipelineShaderStageCreateInfo shader_stage_create_infos[2] = {
    {
      .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
      .stage = VK_SHADER_STAGE_VERTEX_BIT,
      .module = shader_modules[0],
      .pName = "main",
    },
    {
      .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
      .stage = VK_SHADER_STAGE_FRAGMENT_BIT,
      .module = shader_modules[1],
      .pName = "main",
    },
  };

  VkPipelineRenderingCreateInfo rendering_create_info {
    .sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO,
    .colorAttachmentCount = 1,
    .pColorAttachmentFormats = &color_attachment_format,
    .depthAttachmentFormat = VK_FORMAT_UNDEFINED,
    .stencilAttachmentFormat = VK_FORMAT_UNDEFINED,
  };

  VkPipelineVertexInputStateCreateInfo vertex_input_state_create_info{
    .sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
    .vertexBindingDescriptionCount = (uint32_t)input_bindings.size(),
    .pVertexBindingDescriptions = input_bindings.data(),
    .vertexAttributeDescriptionCount = (uint32_t)input_attributes.size(),
    .pVertexAttributeDescriptions = input_attributes.data(),
  };

  VkPipelineInputAssemblyStateCreateInfo ia_state_create_info{
    .sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
    .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
  };

  VkPipelineViewportStateCreateInfo viewport_state_create_info{
    .sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
    .viewportCount = 1,
    .scissorCount = 1,
  };

  VkPipelineRasterizationStateCreateInfo rs_create_info{
    .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
    .polygonMode = VK_POLYGON_MODE_FILL,
    .cullMode = VK_CULL_MODE_NONE,
    .lineWidth = 1.0,
  };

  VkPipelineMultisampleStateCreateInfo multisample_state_create_info{
    .sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
    .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT,
  };

  VkPipelineColorBlendAttachmentState color_blend_attachment_state{
    .blendEnable = VK_FALSE,
    .colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
                  VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT,
  };

  VkPipelineColorBlendStateCreateInfo color_blend_state_create_info{
    .sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
    .attachmentCount = 1,
    .pAttachments = &color_blend_attachment_state,
  };

  VkDynamicState dynamic_states[2] = {
    VK_DYNAMIC_STATE_VIEWPORT,
    VK_DYNAMIC_STATE_SCISSOR,
  };

  VkPipelineDynamicStateCreateInfo dynamic_state_create_info{
    .sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,
    .dynamicStateCount = (sizeof(dynamic_states)/sizeof(dynamic_states[0])),
    .pDynamicStates = dynamic_states,
  };

  VkGraphicsPipelineCreateInfo create_info{
    .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
    .pNext = &rendering_create_info,

    .stageCount = (sizeof(shader_stage_create_infos)/sizeof(shader_stage_create_infos[0])),
    .pStages = shader_stage_create_infos,

    .pVertexInputState = &vertex_input_state_create_info,
    .pInputAssemblyState = &ia_state_create_info,
    .pViewportState = &viewport_state_create_info,
    .pRasterizationState = &rs_create_info,
    .pMultisampleState = &multisample_state_create_info,
    .pColorBlendState = &color_blend_state_create_info,
    .pDynamicState = &dynamic_state_create_info,

    .layout = data_table->get_pipeline_layout(),
  };

  if (vkCreateGraphicsPipelines(device, nullptr, 1, &create_info, nullptr, &pipeline->m_handle) != VK_SUCCESS) {
    vkDestroyShaderModule(device, shader_modules[0], nullptr);
    vkDestroyShaderModule(device, shader_modules[1], nullptr);

    return "Failed to create the graphics pipeline";
  }

  vkDestroyShaderModule(device, shader_modules[0], nullptr);
  vkDestroyShaderModule(device, shader_modules[1], nullptr);

  return pipeline;
}

void Pipeline::bind(VkCommandBuffer cmd)
{
  // for now we'll only be using graphics pipeline so we can just hardcode VK_PIPELINE_BIND_POINT_GRAPHICS here
  vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, m_handle);
}

Pipeline::~Pipeline()
{
  if (!m_device)
    return;

  if (m_handle) vkDestroyPipeline(m_device, m_handle, nullptr);
}
Show sample.hpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include "image.hpp"
#include "buffer.hpp"
#include "pipeline.hpp"

#include <vector>
#include <string>
#include <cassert>
#include <stdint.h>
#include <functional>

class SampleVulkan
{
  static constexpr uint32_t NUM_CONCURRENT_FRAMES = 3;
  static constexpr const char *VALIDATION_LAYER_NAME = "VK_LAYER_KHRONOS_validation";
  static constexpr const char *SWAPCHAIN_DEVICE_EXTENSION_NAME = "VK_KHR_swapchain";
  static constexpr const char *PORTABILITY_SUBSET_DEVICE_EXTENSION_NAME = "VK_KHR_portability_subset";

  struct FrameResourceSet
  {
    VkFence fen_in_flight{};
    VkSemaphore sm_image_available{};
    VkCommandBuffer cmd_buffer{};
  };

public:
  SampleVulkan() = default;
  SampleVulkan(const SampleVulkan &) = delete;
  SampleVulkan &operator=(const SampleVulkan &) = delete;

  ~SampleVulkan();

  bool initialize(std::function<bool(VkInstance, uint32_t &, uint32_t &, VkSurfaceKHR &)> surface_creation_callback);

  bool render();

  void resize(uint32_t fb_width, uint32_t fb_height);

private:
  bool create_instance();
  bool select_physical_device();
  bool create_device_and_swapchain();
  bool create_frame_resources();

  void draw_frame(VkCommandBuffer cmd, VkImageView color_attachment);

  bool execute_single_shot_commands(std::function<Result<>(VkCommandBuffer)> commands);

  bool recreate_swapchain();

private:
  VkInstance m_instance{};
  VkDebugUtilsMessengerEXT m_debug_messenger{};

  VkSurfaceKHR m_surface{};
  std::string m_physical_device_name{};
  VkPhysicalDevice m_physical_device{};
  uint32_t m_graphics_queue_family_index{};
  uint32_t m_present_queue_family_index{};
  uint32_t m_swapchain_image_count{};
  std::vector<VkSemaphore> m_render_done_semaphores;
  VkSurfaceFormatKHR m_swapchain_format{};
  VkPresentModeKHR m_swapchain_present_mode{};
  VkExtent2D m_swapchain_extent{1, 1};
  VkExtent2D m_pending_swapchain_extent{1, 1};
  bool m_swapchain_is_out_of_date{};
  VkSurfaceTransformFlagBitsKHR m_swapchain_pre_transform{};

  VkDevice m_device{};
  VkQueue m_graphics_queue{};
  VkQueue m_present_queue{};
  VkSwapchainKHR m_swapchain{};
  std::vector<VkImage> m_swapchain_images{};
  std::vector<VkImageView> m_swapchain_image_views{};

  uint32_t m_current_frame_index{};
  VkCommandPool m_frame_resource_command_pool{};
  FrameResourceSet m_frames[NUM_CONCURRENT_FRAMES];

  Box<Pipeline> m_graphics_pipeline{};

  VmaAllocator m_allocator{};

  Box<Buffer> m_staging_buffer{};
  Box<Buffer> m_vertex_buffer{};
  Box<Buffer> m_index_buffer{};

  VkFence m_single_shot_command_fence{};
  VkCommandPool m_single_shot_command_pool{};
  VkCommandBuffer m_single_shot_command_buffer{};

  Box<Image> m_texture_image{};
  VkSampler m_texture_sampler{};
  
  Box<ShaderDataTable> m_shader_data_table{};
};
Show sample.cpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#include "sample.hpp"

#include <set>
#include <stdio.h>
#include <string.h>
#include <utility>
#include <fstream>
#include <algorithm>

template<typename ElementT, typename FuncT, typename... Args> std::vector<ElementT> vkEnumCall(FuncT f, Args... args)
{
  uint32_t _count{};
  f(args..., &_count, nullptr);

  std::vector<ElementT> result(_count);
  f(args..., &_count, result.data());

  return result;
}

struct Vertex
{
  glm::vec3 pos;
  glm::vec3 colour;
  glm::vec2 texcoord;
};

static const Vertex VERTICES[4] = {
  {glm::vec3(-0.5f, -0.5f, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)},
  {glm::vec3(0.5f, -0.5f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f) , glm::vec2(1.0f, 0.0f)},
  {glm::vec3(0.5f, 0.5f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)  , glm::vec2(1.0f, 1.0f)},
  {glm::vec3(-0.5f, 0.5f, 0.0f),  glm::vec3(1.0f, 0.0f, 1.0f), glm::vec2(0.0f, 1.0f)},
};

static const uint32_t INDICES[6] = {
  0, 1, 2,
  2, 3, 0
};

// Create checkerboard pattern pixels (violet and white)
static std::vector<uint8_t> get_checkerboard_pattern_pixels(uint32_t width, uint32_t height, uint32_t checker_size = 4)
{
  std::vector<uint8_t> rgba_data(width * height * 4);

  for (uint32_t y = 0; y < height; ++y)
  {
    for (uint32_t x = 0; x < width; ++x)
    {
      const bool is_violet = ((x / checker_size) % 2) == ((y / checker_size) % 2);
      uint32_t index = (y * width + x) * 4;
      if (is_violet)
      {
        rgba_data[index + 0] = 255;
        rgba_data[index + 1] = 0;
        rgba_data[index + 2] = 255;
        rgba_data[index + 3] = 255;
      }
      else
      {
        rgba_data[index + 0] = 255;
        rgba_data[index + 1] = 255;
        rgba_data[index + 2] = 255;
        rgba_data[index + 3] = 255;
      }
    }
  }

  return rgba_data;
}

static Result<std::vector<uint32_t>> load_shader_from_file(const std::string& path)
{
  std::ifstream f(path, std::ios::in | std::ios::binary | std::ios::ate);
  if (!f.is_open())
    return "Failed to open shader file \""+ path + "\".";

  std::vector<uint32_t> data;
  data.resize(f.tellg() >> 2);
  f.seekg(SEEK_SET);
  f.read((char*)data.data(), data.size() << 2);

  return std::move(data);
}

SampleVulkan::~SampleVulkan()
{
  if (m_device)
  {
    vkDeviceWaitIdle(m_device);

    m_texture_image.reset();
    
    vkDestroySampler(m_device, m_texture_sampler, nullptr);

    vkDestroyFence(m_device, m_single_shot_command_fence, nullptr);

    vkDestroyCommandPool(m_device, m_single_shot_command_pool, nullptr);

    m_vertex_buffer.reset();
    m_index_buffer.reset();
    m_staging_buffer.reset();

    m_graphics_pipeline.reset();
    m_shader_data_table.reset();

    for (uint32_t i = 0; i < NUM_CONCURRENT_FRAMES; i++)
    {
      vkDestroyFence(m_device, m_frames[i].fen_in_flight, nullptr);
      vkDestroySemaphore(m_device, m_frames[i].sm_image_available, nullptr);
    }

    for (size_t i = 0; i < m_render_done_semaphores.size(); i++)
      vkDestroySemaphore(m_device, m_render_done_semaphores[i], nullptr);
    m_render_done_semaphores.clear();

    vkDestroyCommandPool(m_device, m_frame_resource_command_pool, nullptr);

    for (const auto &view : m_swapchain_image_views)
      vkDestroyImageView(m_device, view, nullptr);
    vkDestroySwapchainKHR(m_device, m_swapchain, nullptr);

    vmaDestroyAllocator(m_allocator);

    vkDestroyDevice(m_device, nullptr);
  }

  if (m_instance)
  {
    if (m_surface)
      vkDestroySurfaceKHR(m_instance, m_surface, nullptr);

    {
      const auto debug_messenger_destroy_func =
          (PFN_vkDestroyDebugUtilsMessengerEXT) vkGetInstanceProcAddr(m_instance, "vkDestroyDebugUtilsMessengerEXT");
      if (debug_messenger_destroy_func && m_debug_messenger)
        debug_messenger_destroy_func(m_instance, m_debug_messenger, nullptr);
    }

    vkDestroyInstance(m_instance, nullptr);
  }
}

bool SampleVulkan::initialize(
    std::function<bool(VkInstance, uint32_t &, uint32_t &, VkSurfaceKHR &)> surface_creation_callback)
{
  if (!create_instance())
    return false;

  if (!surface_creation_callback(m_instance, m_pending_swapchain_extent.width, m_pending_swapchain_extent.height,
                                 m_surface))
  {
    printf("Failed to create Vulkan surface\n");
    return false;
  }

  if (!select_physical_device())
    return false;

  if (!create_device_and_swapchain())
    return false;

  VmaAllocatorCreateInfo vma_create_info{
    .physicalDevice = m_physical_device,
    .device = m_device,
    .instance = m_instance,
    .vulkanApiVersion = VK_API_VERSION_1_3,
  };
  if (vmaCreateAllocator(&vma_create_info, &m_allocator) != VK_SUCCESS) {
    printf("Failed to create the VMA allocator\n");
    return false;
  }

  if (!create_frame_resources())
    return false;

  {
    VkCommandPoolCreateInfo pool_create_info{
      .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
      .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
      .queueFamilyIndex = m_graphics_queue_family_index,
    };
    if (vkCreateCommandPool(m_device, &pool_create_info, nullptr, &m_single_shot_command_pool) != VK_SUCCESS) {
      printf("Failed to create the single shot command pool\n");
      return false;
    }

    VkFenceCreateInfo fence_create_info{
      .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
    };
    if (vkCreateFence(m_device, &fence_create_info, nullptr, &m_single_shot_command_fence) != VK_SUCCESS) {
      printf("Failed to create the single shot fence\n");
      return false;
    }

    VkCommandBufferAllocateInfo alloc_info{
      .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
      .commandPool = m_single_shot_command_pool,
      .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
      .commandBufferCount = 1,
    };
    if (vkAllocateCommandBuffers(m_device, &alloc_info, &m_single_shot_command_buffer) != VK_SUCCESS) {
      printf("Failed to allocate the single shot command buffer\n");
      return false;
    }
  }

  CHECK_RESULT(
    ShaderDataTable::create(
      m_device,
      std::initializer_list<ShaderDataTable::EntryDescription>{
        {.name = "texture_sampler", .set = 0, .binding = 0, .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .count = 1, .stages = VK_SHADER_STAGE_FRAGMENT_BIT,},
      }
    ),
    m_shader_data_table
  );

  std::vector<uint32_t> vertex_shader_data, fragment_shader_data{};
  CHECK_RESULT(load_shader_from_file("resources/default.vert.spv"), vertex_shader_data);
  CHECK_RESULT(load_shader_from_file("resources/default.frag.spv"), fragment_shader_data);

  CHECK_RESULT(
    Pipeline::create(
      m_device,
      m_swapchain_format.format,
      std::initializer_list<VkVertexInputBindingDescription>{
        {.binding = 0, .stride = sizeof(Vertex), .inputRate = VK_VERTEX_INPUT_RATE_VERTEX},
      },
      std::initializer_list<VkVertexInputAttributeDescription>{
        VkVertexInputAttributeDescription{.location = 0, .binding = 0, .format = VK_FORMAT_R32G32B32_SFLOAT, .offset = offsetof(Vertex, pos)},
        VkVertexInputAttributeDescription{.location = 1, .binding = 0, .format = VK_FORMAT_R32G32B32_SFLOAT, .offset = offsetof(Vertex, colour)},
        VkVertexInputAttributeDescription{.location = 2, .binding = 0, .format = VK_FORMAT_R32G32_SFLOAT, .offset = offsetof(Vertex, texcoord)},
      },
      m_shader_data_table.get(),
      vertex_shader_data,
      fragment_shader_data
    ),
    m_graphics_pipeline
  );

  CHECK_RESULT(
    Buffer::create(
      m_allocator,
      std::max(sizeof(VERTICES), sizeof(INDICES)), // maximum size we'll need for our staging operations 
      Buffer::EUsage::STAGING
    ),
    m_staging_buffer
  );

  CHECK_RESULT(
    Buffer::create(
      m_allocator,
      sizeof(VERTICES), 
      Buffer::EUsage::VERTEX
    ),
    m_vertex_buffer
  );

  CHECK_RESULT(
    Buffer::create(
      m_allocator,
      sizeof(INDICES), 
      Buffer::EUsage::INDEX
    ),
    m_index_buffer
  );

  { // copy VERTICES to vertex buffer
    if(!m_staging_buffer->copy_from_cpu(VERTICES, sizeof(VERTICES))) {
      printf("Failed to copy VERTICES to staging buffer\n");
      return false;
    }

    const auto success = execute_single_shot_commands([&](VkCommandBuffer cmd) -> Result<>
    {
      VkBufferCopy copy_region{
        .srcOffset = 0,
        .dstOffset = 0,
        .size = m_vertex_buffer->get_size(),
      };

      vkCmdCopyBuffer(cmd, m_staging_buffer->get_handle(), m_vertex_buffer->get_handle(), 1, &copy_region);

      VkMemoryBarrier barrier{
        .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER,
        .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
        .dstAccessMask = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT,
      };
      vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,
                          0, 1, &barrier, 0, nullptr, 0, nullptr);

      return Ok{};
    });
    if(!success) {
      printf("Failed to copy staging buffer to vertex buffer\n");
      return false;
    }
  }

  { // copy INDICES to index buffer
    if(!m_staging_buffer->copy_from_cpu(INDICES, sizeof(INDICES))) {
      printf("Failed to copy INDICES to staging buffer\n");
      return false;
    }

    const auto success = execute_single_shot_commands([&](VkCommandBuffer cmd) -> Result<>
    {
      VkBufferCopy copy_region{
        .srcOffset = 0,
        .dstOffset = 0,
        .size = m_index_buffer->get_size(),
      };
      
      vkCmdCopyBuffer(cmd, m_staging_buffer->get_handle(), m_index_buffer->get_handle(), 1, &copy_region);

      VkMemoryBarrier barrier{
        .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER,
        .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
        .dstAccessMask = VK_ACCESS_INDEX_READ_BIT,
      };
      vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,
                          0, 1, &barrier, 0, nullptr, 0, nullptr);

      return Ok{};
    });
    if (!success) {
      printf("Failed to copy staging buffer to index buffer\n");
      return false;
    }
  }

  {
    VkSamplerCreateInfo create_info{
      .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
      .magFilter = VK_FILTER_LINEAR,
      .minFilter = VK_FILTER_LINEAR,
      .addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT,
      .addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT,
      .addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT,
    };

    if (vkCreateSampler(m_device, &create_info, nullptr, &m_texture_sampler) != VK_SUCCESS) {
      printf("Failed to create the texture sampler\n");
      return false;
    }
  }

  {
    std::vector<uint8_t> pixels{};
    VkExtent2D extent{};

    if (!Image::load_rgba_from_file("resources/Ground037_1K-PNG_Color.png", pixels, extent)) {
      printf("Failed to load texture data from the disk\n");
      return false;
    }

    CHECK_RESULT(
      Image::create(
        m_device, 
        m_allocator,
        VK_FORMAT_R8G8B8A8_SRGB,
        extent,
        VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT // We want to sample this image from fragment shader and 
                                                                          // copy data from staging buffer into this image.
      ),
    m_texture_image);

    const auto success = execute_single_shot_commands([&](VkCommandBuffer cmd) -> Result<>
    {
      if (!m_texture_image->transition_layout(cmd, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL))
        return "Failed to transition texture image to VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL";

      if (!m_texture_image->copy_from_cpu(cmd, pixels.data(), pixels.size()))
        return "Failed to copy pixels to texture image";

      if (!m_texture_image->transition_layout(cmd, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL))
        return "Failed to transition texture image to VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL";

      return Ok{};
    });
    if (!success) {
      printf("Failed to copy pixels to the image\n");
      return false;
    }
  }

  if (!m_shader_data_table->write_image_entry("texture_sampler", m_texture_image.get(), m_texture_sampler)) {
    printf("Failed to write texture image to shader data table\n");
    return false;
  }
  m_shader_data_table->flush_writes();

  return true;
}

bool SampleVulkan::render()
{
  const auto &current_frame = m_frames[m_current_frame_index];

  vkWaitForFences(m_device, 1, &current_frame.fen_in_flight, VK_TRUE, UINT64_MAX);

  uint32_t image_index{};
  switch (vkAcquireNextImageKHR(m_device, m_swapchain, UINT64_MAX, current_frame.sm_image_available, VK_NULL_HANDLE,
                                &image_index))
  {
  case VK_ERROR_OUT_OF_DATE_KHR:
    if (!recreate_swapchain())
      return false;
    return true;

  case VK_SUCCESS:
  case VK_SUBOPTIMAL_KHR:
    break;

  default:
    printf("Failed to acquire swapchain image\n");
    return false;
  }

  VkCommandBufferBeginInfo cmd_begin_info{
      .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
  };
  vkResetCommandBuffer(current_frame.cmd_buffer, 0);
  if (vkBeginCommandBuffer(current_frame.cmd_buffer, &cmd_begin_info) != VK_SUCCESS)
  {
    printf("Failed to start recording command buffer\n");
    return false;
  }

  if (!Image::transition_image_layout(current_frame.cmd_buffer, m_swapchain_images[image_index], VK_IMAGE_LAYOUT_UNDEFINED,
                               VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL))
  {
    printf("Failed to transition swapchain image\n");
    return false;
  }

  draw_frame(current_frame.cmd_buffer, m_swapchain_image_views[image_index]);

  if (!Image::transition_image_layout(current_frame.cmd_buffer, m_swapchain_images[image_index],
                               VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR))
  {
    printf("Failed to transition swapchain image\n");
    return false;
  }

  if (vkEndCommandBuffer(current_frame.cmd_buffer) != VK_SUCCESS)
  {
    printf("Failed to finish recording command buffer\n");
    return false;
  }

  VkPipelineStageFlags submit_pipeline_wait_stage{VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT};
  VkSubmitInfo submit_info{
      .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
      .waitSemaphoreCount = 1,
      .pWaitSemaphores = &current_frame.sm_image_available,
      .pWaitDstStageMask = &submit_pipeline_wait_stage,
      .commandBufferCount = 1,
      .pCommandBuffers = &current_frame.cmd_buffer,
      .signalSemaphoreCount = 1,
      .pSignalSemaphores = &m_render_done_semaphores[image_index],
  };

  vkResetFences(m_device, 1, &current_frame.fen_in_flight);
  if (vkQueueSubmit(m_graphics_queue, 1, &submit_info, current_frame.fen_in_flight) != VK_SUCCESS)
  {
    printf("Failed to submit frame command buffer\n");
    return false;
  }

  VkPresentInfoKHR present_info{
      .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
      .waitSemaphoreCount = 1,
      .pWaitSemaphores = &m_render_done_semaphores[image_index],
      .swapchainCount = 1,
      .pSwapchains = &m_swapchain,
      .pImageIndices = &image_index,
  };

  switch (vkQueuePresentKHR(m_present_queue, &present_info))
  {
  case VK_ERROR_OUT_OF_DATE_KHR:
  case VK_SUBOPTIMAL_KHR:
    if (!recreate_swapchain())
      return false;
    break;

  case VK_SUCCESS:
    break;

  default:
    printf("Failed to present swapchain\n");
    return false;
  }

  if (m_swapchain_is_out_of_date && !recreate_swapchain())
    return false;

  m_current_frame_index = (m_current_frame_index + 1) % NUM_CONCURRENT_FRAMES;

  return true;
}

void SampleVulkan::draw_frame(VkCommandBuffer cmd, VkImageView color_attachment)
{
  VkRenderingAttachmentInfo color_attachment_info{
      .sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
      .imageView = color_attachment,
      .imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
      .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
      .storeOp = VK_ATTACHMENT_STORE_OP_STORE,
      .clearValue =
          {
              .color =
                  {
                      0.1f,
                      0.1f,
                      0.1f,
                      1.0f,
                  },
          },
  };

  VkRenderingInfo rendering_info{
      .sType = VK_STRUCTURE_TYPE_RENDERING_INFO,
      .renderArea =
          {
              {},
              m_swapchain_extent,
          },
      .layerCount = 1,
      .viewMask = 0,
      .colorAttachmentCount = 1,
      .pColorAttachments = &color_attachment_info,
  };

  vkCmdBeginRendering(cmd, &rendering_info);

  VkViewport viewport = {
    .width = (float)m_swapchain_extent.width,
    .height = (float)m_swapchain_extent.height,
    .minDepth = 0.0f,
    .maxDepth = 1.0f,
  };
  vkCmdSetViewport(cmd, 0, 1, &viewport);

  VkRect2D scissor{
    .extent = m_swapchain_extent,
  };
  vkCmdSetScissor(cmd, 0, 1, &scissor);

  m_graphics_pipeline->bind(cmd);

  m_vertex_buffer->bind(cmd);
  m_index_buffer->bind(cmd);

  m_shader_data_table->bind(cmd);

  vkCmdDrawIndexed(cmd, sizeof(INDICES)/sizeof(INDICES[0]), 1, 0, 0, 0);

  vkCmdEndRendering(cmd);
}

bool SampleVulkan::execute_single_shot_commands(std::function<Result<>(VkCommandBuffer)> commands)
{
  if (vkResetCommandBuffer(m_single_shot_command_buffer, 0) != VK_SUCCESS)
    return false;

  VkCommandBufferBeginInfo begin_info{
    .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
  };
  if (vkBeginCommandBuffer(m_single_shot_command_buffer, &begin_info) != VK_SUCCESS)
    return false;

  const auto result = commands(m_single_shot_command_buffer);
  if (result.is_error()) {
    printf("%s\n", result.get_error().c_str());
    return false;
  }

  if (vkEndCommandBuffer(m_single_shot_command_buffer) != VK_SUCCESS)
    return false;

  VkSubmitInfo submit_info{
    .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
    .commandBufferCount = 1,
    .pCommandBuffers = &m_single_shot_command_buffer,
  };
  if (vkQueueSubmit(m_graphics_queue, 1, &submit_info, m_single_shot_command_fence) != VK_SUCCESS)
    return false;

  if (vkWaitForFences(m_device, 1, &m_single_shot_command_fence, true, UINT64_MAX) != VK_SUCCESS)
    return false;

  if (vkResetFences(m_device, 1, &m_single_shot_command_fence) != VK_SUCCESS)
    return false;

  return true;
}

bool SampleVulkan::create_instance()
{
  // This is a sample, not production code, so we always enable validation layers,
  // unless they're unavailable
  const auto instance_layer_props = vkEnumCall<VkLayerProperties>(vkEnumerateInstanceLayerProperties);
  const bool enable_validation_layers =
      std::any_of(instance_layer_props.begin(), instance_layer_props.end(),
                  [](VkLayerProperties p) { return strcmp(p.layerName, VALIDATION_LAYER_NAME) == 0; });

  VkDebugUtilsMessengerCreateInfoEXT debug_messenger_create_info{
      .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
      .messageSeverity =
          VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT,
      .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
                     VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,
      .pfnUserCallback = [](VkDebugUtilsMessageSeverityFlagBitsEXT severity, VkDebugUtilsMessageTypeFlagsEXT type,
                            const VkDebugUtilsMessengerCallbackDataEXT *callback_data, void *user_data) -> VkBool32 {
        printf("[VK_VALIDATION_LAYER]: %s\n", callback_data->pMessage);
        return VK_FALSE;
      },
  };

  std::vector<const char *> extensions;
  { // GLFW Extensions
    uint32_t glfw_ext_count{};
    const auto glfw_ext = glfwGetRequiredInstanceExtensions(&glfw_ext_count);
    extensions.insert(extensions.end(), glfw_ext, glfw_ext + glfw_ext_count);
  }
  if (enable_validation_layers)
    extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);

  // macOS support: MoltenVK is a "portability" implementation (it doesn't support all
  // of Vulkan), so the loader only exposes it to us if we explicitly opt in.
  const auto instance_ext_props = vkEnumCall<VkExtensionProperties>(vkEnumerateInstanceExtensionProperties, nullptr);
  const bool enable_portability =
      std::any_of(instance_ext_props.begin(), instance_ext_props.end(), [](VkExtensionProperties p) {
        return strcmp(p.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0;
      });
  if (enable_portability)
    extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);

  VkApplicationInfo app_info{
      .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
      .pApplicationName = "i-a-s.me Vulkan 1.3 Sample",
      .applicationVersion = VK_MAKE_VERSION(1, 0, 0),
      .pEngineName = "i-a-s.me Vulkan 1.3 Sample",
      .engineVersion = VK_MAKE_VERSION(1, 0, 0),
      .apiVersion = VK_API_VERSION_1_3,
  };
  VkInstanceCreateInfo create_info{
      .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
      .pNext = enable_validation_layers ? &debug_messenger_create_info : nullptr,
      .flags = enable_portability ? (VkInstanceCreateFlags) VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR : 0u,
      .pApplicationInfo = &app_info,
      .enabledLayerCount = enable_validation_layers ? 1u : 0u,
      .ppEnabledLayerNames = enable_validation_layers ? &VALIDATION_LAYER_NAME : nullptr,
      .enabledExtensionCount = (uint32_t) extensions.size(),
      .ppEnabledExtensionNames = extensions.data(),
  };

  if (vkCreateInstance(&create_info, nullptr, &m_instance) != VK_SUCCESS)
  {
    printf("Failed to create Vulkan instance\n");
    return false;
  }

  const auto debug_messenger_create_func =
      (PFN_vkCreateDebugUtilsMessengerEXT) vkGetInstanceProcAddr(m_instance, "vkCreateDebugUtilsMessengerEXT");
  if (enable_validation_layers && debug_messenger_create_func)
  {
    if (debug_messenger_create_func(m_instance, &debug_messenger_create_info, nullptr, &m_debug_messenger) !=
        VK_SUCCESS)
    {
      printf("Failed to create Vulkan debug messenger\n");
      return false;
    }
  }

  return true;
}

bool SampleVulkan::select_physical_device()
{
  const auto find_queue_families = [&](VkPhysicalDevice p) -> std::pair<uint32_t, uint32_t> {
    uint32_t graphics_family_index{UINT32_MAX}, present_family_index{UINT32_MAX};

    const auto queue_families = vkEnumCall<VkQueueFamilyProperties>(vkGetPhysicalDeviceQueueFamilyProperties, p);
    for (uint32_t i = 0; i < (uint32_t) queue_families.size(); i++)
    {
      const auto &f = queue_families[i];

      if (f.queueFlags & VK_QUEUE_GRAPHICS_BIT)
        graphics_family_index = i;

      VkBool32 has_present_support{};
      if ((vkGetPhysicalDeviceSurfaceSupportKHR(p, i, m_surface, &has_present_support) == VK_SUCCESS) &&
          has_present_support)
        present_family_index = i;

      if ((graphics_family_index != UINT32_MAX) && (present_family_index != UINT32_MAX))
        break;
    }

    return {graphics_family_index, present_family_index};
  };

  m_physical_device = VK_NULL_HANDLE;

  const auto physical_devices = vkEnumCall<VkPhysicalDevice>(vkEnumeratePhysicalDevices, m_instance);

  for (const auto &p : physical_devices)
  {
    VkPhysicalDeviceProperties2 props{
        .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2,
    };
    vkGetPhysicalDeviceProperties2(p, &props);

    if (props.properties.apiVersion < VK_API_VERSION_1_3)
      continue; // If this physical device does not support at least Vulkan 1.3, we cannot use it. We use Vulkan 1.3
                // core features in this sample.

    const auto queue_family_indices = find_queue_families(p);

    if ((queue_family_indices.first == UINT32_MAX) || (queue_family_indices.second == UINT32_MAX))
      continue; // This physical device isn't what we want, if it lacks either graphics or present queue families

    // We could (and should) do more suitability checks in a real application,
    // but for this sample, this is just ok.

    m_physical_device = p;
    m_graphics_queue_family_index = queue_family_indices.first;
    m_present_queue_family_index = queue_family_indices.second;

    m_physical_device_name = props.properties.deviceName;

    if (props.properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU)
      break; // If we find a discrete GPU, then prefer it
  }

  if (m_physical_device == VK_NULL_HANDLE)
  {
    printf("Failed to find a good physical device\n");
    return false;
  }

  printf("Using physical device \"%s\"\n", m_physical_device_name.c_str());

  return true;
}

void SampleVulkan::resize(uint32_t fb_width, uint32_t fb_height)
{
  m_pending_swapchain_extent = {fb_width, fb_height};
  m_swapchain_is_out_of_date = true;
}

bool SampleVulkan::create_device_and_swapchain()
{
  const float priority = 1.0f;
  std::vector<VkDeviceQueueCreateInfo> queue_create_infos;
  // passing through std::set effectively dedups family indices.
  // not really necessary to use std::set here as we only have to consider
  // 2 families (graphics and present), so we could have just checked (family_index_1 == family_index_2),
  // but this std::set approach generalizes to higher orders (imagine doing if/else checks for combinations of 3 or 4)
  for (const auto index : std::set<uint32_t>{m_graphics_queue_family_index, m_present_queue_family_index})
    queue_create_infos.push_back(VkDeviceQueueCreateInfo{
        .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
        .queueFamilyIndex = index,
        .queueCount = 1,
        .pQueuePriorities = &priority,
    });

  std::vector<const char *> device_extensions{SWAPCHAIN_DEVICE_EXTENSION_NAME};
  // macOS support: if the device is a portability implementation (i.e. MoltenVK),
  // it exposes VK_KHR_portability_subset, and the spec requires us to enable it.
  const auto device_ext_props =
      vkEnumCall<VkExtensionProperties>(vkEnumerateDeviceExtensionProperties, m_physical_device, nullptr);
  if (std::any_of(device_ext_props.begin(), device_ext_props.end(), [](VkExtensionProperties p) {
        return strcmp(p.extensionName, PORTABILITY_SUBSET_DEVICE_EXTENSION_NAME) == 0;
      }))
    device_extensions.push_back(PORTABILITY_SUBSET_DEVICE_EXTENSION_NAME);

  VkPhysicalDeviceFeatures enabled_features{};
  VkPhysicalDeviceVulkan13Features vk_13_features{
      .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES,
      .synchronization2 = VK_TRUE,
      .dynamicRendering = VK_TRUE,
  };

  VkDeviceCreateInfo device_create_info{
      .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
      .pNext = &vk_13_features,
      .queueCreateInfoCount = (uint32_t) queue_create_infos.size(),
      .pQueueCreateInfos = queue_create_infos.data(),
      .enabledLayerCount = 0,
      .ppEnabledLayerNames = nullptr,
      .enabledExtensionCount = (uint32_t) device_extensions.size(),
      .ppEnabledExtensionNames = device_extensions.data(),
      .pEnabledFeatures = &enabled_features,
  };

  if (vkCreateDevice(m_physical_device, &device_create_info, nullptr, &m_device) != VK_SUCCESS)
  {
    printf("Failed to create Vulkan device\n");
    return false;
  }

  vkGetDeviceQueue(m_device, m_graphics_queue_family_index, 0, &m_graphics_queue);
  vkGetDeviceQueue(m_device, m_present_queue_family_index, 0, &m_present_queue);

  const auto surface_formats =
      vkEnumCall<VkSurfaceFormatKHR>(vkGetPhysicalDeviceSurfaceFormatsKHR, m_physical_device, m_surface);
  const auto surface_present_modes =
      vkEnumCall<VkPresentModeKHR>(vkGetPhysicalDeviceSurfacePresentModesKHR, m_physical_device, m_surface);
  assert(surface_formats.size());
  assert(surface_present_modes.size());
  m_swapchain_format = surface_formats[0];
  m_swapchain_present_mode = (std::find(surface_present_modes.begin(), surface_present_modes.end(),
                                        VK_PRESENT_MODE_MAILBOX_KHR) != surface_present_modes.end())
                                 ? VK_PRESENT_MODE_MAILBOX_KHR
                                 : VK_PRESENT_MODE_FIFO_KHR;

  return recreate_swapchain();
}

bool SampleVulkan::create_frame_resources()
{
  VkCommandPoolCreateInfo commmand_pool_create_info{
      .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
      .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
      .queueFamilyIndex = m_graphics_queue_family_index,
  };
  if (vkCreateCommandPool(m_device, &commmand_pool_create_info, nullptr, &m_frame_resource_command_pool) != VK_SUCCESS)
  {
    printf("Failed to create command pool\n");
    return false;
  }

  VkCommandBufferAllocateInfo command_buffer_alloc_info{
      .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
      .commandPool = m_frame_resource_command_pool,
      .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
      .commandBufferCount = 1,
  };
  for (uint32_t i = 0; i < NUM_CONCURRENT_FRAMES; i++)
  {
    if (vkAllocateCommandBuffers(m_device, &command_buffer_alloc_info, &m_frames[i].cmd_buffer) != VK_SUCCESS)
    {
      printf("Failed to allocate frame command buffer\n");
      return false;
    }

    VkSemaphoreCreateInfo semaphore_create_info{
        .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
    };
    if (vkCreateSemaphore(m_device, &semaphore_create_info, nullptr, &m_frames[i].sm_image_available) != VK_SUCCESS)
    {
      printf("Failed to create a semaphore\n");
      return false;
    }

    VkFenceCreateInfo fence_create_info{
        .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
        .flags = VK_FENCE_CREATE_SIGNALED_BIT,
    };
    if (vkCreateFence(m_device, &fence_create_info, nullptr, &m_frames[i].fen_in_flight) != VK_SUCCESS)
    {
      printf("Failed to create a fence\n");
      return false;
    }
  }

  return true;
}

bool SampleVulkan::recreate_swapchain()
{
  vkDeviceWaitIdle(m_device);

  VkSurfaceCapabilitiesKHR surface_caps{};
  if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR(m_physical_device, m_surface, &surface_caps) != VK_SUCCESS)
  {
    printf("Failed to query physical device surface caps\n");
    return false;
  }

  // A minimized window has a 0x0 surface, and a 0x0 swapchain is not allowed. So we
  // keep the current swapchain, and try again later (once the window is restored).
  if ((surface_caps.maxImageExtent.width == 0) || (surface_caps.maxImageExtent.height == 0))
  {
    m_swapchain_is_out_of_date = true;
    return true;
  }

  m_swapchain_image_count = std::min(surface_caps.minImageCount + 1,
                                     (surface_caps.maxImageCount == 0) ? UINT32_MAX : surface_caps.maxImageCount);

  m_swapchain_pre_transform = surface_caps.currentTransform;

  m_pending_swapchain_extent.width = std::clamp(m_pending_swapchain_extent.width, surface_caps.minImageExtent.width,
                                                surface_caps.maxImageExtent.width);
  m_pending_swapchain_extent.height = std::clamp(m_pending_swapchain_extent.height, surface_caps.minImageExtent.height,
                                                 surface_caps.maxImageExtent.height);
  m_swapchain_extent = m_pending_swapchain_extent;

  for (const auto &view : m_swapchain_image_views)
    vkDestroyImageView(m_device, view, nullptr);
  if (m_swapchain)
    vkDestroySwapchainKHR(m_device, m_swapchain, nullptr);
  m_swapchain_image_views.clear();
  m_swapchain = VK_NULL_HANDLE;

  VkSwapchainCreateInfoKHR swapchain_create_info{
      .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
      .surface = m_surface,
      .minImageCount = m_swapchain_image_count,
      .imageFormat = m_swapchain_format.format,
      .imageColorSpace = m_swapchain_format.colorSpace,
      .imageExtent = m_swapchain_extent,
      .imageArrayLayers = 1,
      .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
      .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
      .preTransform = m_swapchain_pre_transform,
      .compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
      .presentMode = m_swapchain_present_mode,
      .clipped = VK_TRUE,
  };

  uint32_t queue_family_indices[] = {m_graphics_queue_family_index, m_present_queue_family_index};
  if (m_graphics_queue_family_index != m_present_queue_family_index)
  {
    swapchain_create_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
    swapchain_create_info.queueFamilyIndexCount = 2;
    swapchain_create_info.pQueueFamilyIndices = queue_family_indices;
  }

  if (vkCreateSwapchainKHR(m_device, &swapchain_create_info, nullptr, &m_swapchain) != VK_SUCCESS)
  {
    printf("Failed to create swapchain\n");
    return false;
  }

  m_swapchain_images = vkEnumCall<VkImage>(vkGetSwapchainImagesKHR, m_device, m_swapchain);

  // Note that we use the *actual* number of images here, which can be
  // more than the minImageCount we asked for.
  for (auto semaphore : m_render_done_semaphores)
    vkDestroySemaphore(m_device, semaphore, nullptr);
  m_render_done_semaphores.assign(m_swapchain_images.size(), VK_NULL_HANDLE);

  VkSemaphoreCreateInfo semaphore_create_info{
      .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
  };
  for (auto &semaphore : m_render_done_semaphores)
  {
    if (vkCreateSemaphore(m_device, &semaphore_create_info, nullptr, &semaphore) != VK_SUCCESS)
    {
      printf("Failed to create a semaphore\n");
      return false;
    }
  }

  m_swapchain_image_views.reserve(m_swapchain_images.size());
  for (const auto &image : m_swapchain_images)
  {
    VkImageViewCreateInfo create_info{
        .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
        .image = image,
        .viewType = VK_IMAGE_VIEW_TYPE_2D,
        .format = m_swapchain_format.format,
        .components =
            {
                .r = VK_COMPONENT_SWIZZLE_IDENTITY,
                .g = VK_COMPONENT_SWIZZLE_IDENTITY,
                .b = VK_COMPONENT_SWIZZLE_IDENTITY,
                .a = VK_COMPONENT_SWIZZLE_IDENTITY,
            },
        .subresourceRange =
            {
                .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
                .baseMipLevel = 0,
                .levelCount = 1,
                .baseArrayLayer = 0,
                .layerCount = 1,
            },
    };

    VkImageView view{};
    if (vkCreateImageView(m_device, &create_info, nullptr, &view) != VK_SUCCESS)
    {
      printf("Failed to create a swapchain image view\n");
      return false;
    }

    m_swapchain_image_views.push_back(view);
  }

  m_swapchain_is_out_of_date = false;

  return true;
}
Show main.cpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#include "sample.hpp"

class SampleApp
{
  static constexpr uint32_t SCREEN_WIDTH = 800;
  static constexpr uint32_t SCREEN_HEIGHT = 600;

  public:
  int launch(int argc, char *argv[]);

  ~SampleApp();

  private:
  GLFWwindow *m_window{};
  Box<SampleVulkan> m_vulkan{};
};

int main(int argc, char *argv[])
{
  SampleApp app;
  return app.launch(argc, argv);
}

int SampleApp::launch(int argc, char *argv[])
{
  if (!glfwInit())
  {
    printf("Failed to initialize GLFW\n");
    return -1;
  }

  glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
  m_window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "i-a-s.me Vulkan Sample", nullptr, nullptr);
  if (!m_window)
  {
    printf("Failed to create GLFW window\n");
    return -1;
  }

  m_vulkan = Box<SampleVulkan>(new SampleVulkan());
  if (!m_vulkan->initialize([window = m_window](VkInstance instance, uint32_t &out_width, uint32_t &out_height,
                                                VkSurfaceKHR &out_surface) -> bool {
        if (glfwCreateWindowSurface(instance, window, nullptr, &out_surface) != VK_SUCCESS)
        {
          printf("Failed to create Vulkan surface\n");
          return false;
        }

        int32_t fb_width{}, fb_height{};
        glfwGetFramebufferSize(window, &fb_width, &fb_height);
        while ((fb_width == 0) || (fb_height == 0))
        {
          glfwWaitEvents();
          glfwGetFramebufferSize(window, &fb_width, &fb_height);
        }

        out_width = (uint32_t) fb_width;
        out_height = (uint32_t) fb_height;

        return true;
      }))
  {
    printf("Failed to initialize Vulkan\n");
    return -1;
  }

  glfwSetWindowUserPointer(m_window, m_vulkan.get());

  glfwSetFramebufferSizeCallback(m_window, [](GLFWwindow *window, int width, int height) {
    int32_t fb_width{}, fb_height{};
    glfwGetFramebufferSize(window, &fb_width, &fb_height);
    if ((fb_width == 0) || (fb_height == 0))
      return;
    static_cast<SampleVulkan *>(glfwGetWindowUserPointer(window))->resize(fb_width, fb_height);
  });

  while (!glfwWindowShouldClose(m_window))
  {
    if (glfwGetKey(m_window, GLFW_KEY_ESCAPE))
      glfwSetWindowShouldClose(m_window, true);

    glfwPollEvents();

    // Don't render while the window is minimized (its framebuffer is 0x0 then)
    int32_t fb_width{}, fb_height{};
    glfwGetFramebufferSize(m_window, &fb_width, &fb_height);
    if ((fb_width == 0) || (fb_height == 0))
    {
      glfwWaitEvents();
      continue;
    }

    if (!m_vulkan->render())
      break;
  }

  return 0;
}

SampleApp::~SampleApp()
{
  m_vulkan.reset();

  if (m_window)
    glfwDestroyWindow(m_window);

  glfwTerminate();
}
Show vma.cpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#define VMA_IMPLEMENTATION
#include <vk_mem_alloc.h>
Show shaders/default.vert
#version 450

layout(location = 0) in vec3 in_pos;
layout(location = 1) in vec3 in_color;
layout(location = 2) in vec2 in_texcord;

layout(location = 0) out vec3 out_color;
layout(location = 1) out vec2 out_texcoord;

void main() {
    gl_Position = vec4(in_pos, 1.0);
    out_color = in_color;
    out_texcoord = in_texcord;
}
Show shaders/default.frag
#version 450

layout(location = 0) in vec3 in_color;
layout(location = 1) in vec2 in_texcoord;

layout(binding = 0) uniform sampler2D texture_sampler;

layout(location = 0) out vec4 finalColor;

void main() {
    finalColor = texture(texture_sampler, in_texcoord);
}