Skip to content
systemcoding.dev
GPU

The Complete Guide to Vulkan for Graphics Programmers

Learn Vulkan 1.3 from instance to frame loop in C++: devices, queues, swapchains, dynamic rendering, pipelines, synchronization, memory and debugging.

34 min read
Summarize in AI
Flat illustration of a GPU die of compute units with one thread block lit, with the Vulkan, C++ and NVIDIA logos.

Vulkan is a graphics and compute API that asks the programmer to do what OpenGL drivers used to do in secret. You create the objects the driver would have created lazily, you record work into command buffers instead of issuing immediate calls, and you describe in writing which operations must finish before which others begin. The reward is predictability: the cost of every call is visible, work can be recorded on many threads, and the same code behaves much the same across vendors. The price is volume. A triangle takes around a thousand lines, and most of those lines are decisions that OpenGL made for you.

This guide is the map. It walks through every stage of a Vulkan 1.3 renderer in C++, from the first instance to a loop that presents frames, and it explains why each object exists before showing the code that creates it. It assumes you have drawn something with OpenGL, or at least understand the idea of a vertex shader and a fragment shader, and that you have a window from GLFW or SDL, as covered in the windowing guide. The code uses Vulkan 1.3 core features, which includes dynamic rendering and the second synchronization API, so there are no render pass objects or framebuffers to build. Each section stands on its own, and the later posts in this series go deeper on the individual steps.

What Vulkan is, and what it is not

Vulkan is a specification, published by the Khronos Group, of a C API and a set of behaviors. It is implemented by the graphics driver, which for Vulkan is intentionally thin. A Vulkan driver does little validation, little state tracking and little guessing. If you pass an invalid argument, the result is undefined behavior, not an error message, which is why the validation layers described below are part of normal development and not an optional extra.

It is also a cross-platform standard. The same API runs on Windows, Linux, Android and, through the MoltenVK translation layer, on Apple platforms. Programs link a small library called the loader, which finds the installed drivers, called ICDs for installable client drivers, and forwards calls to them.

It is not a framework. There is no scene graph, no math library, no window creation, no asset loading and no memory manager beyond raw allocation. The ecosystem fills those gaps: GLFW or SDL for windows, glm for math, VulkanMemoryAllocator for memory, and glslang or Slang for shader compilation.

Choose Vulkan when you need control of the GPU and are willing to pay for it in code: a renderer that must scale across cores, a project that targets Android and desktop with one API, or a compute workload that wants explicit scheduling. Choose OpenGL or a higher-level layer when the project is small, the team is one person on a deadline or the rendering needs are modest. Vulkan does not make a simple program faster, and it makes a simple program longer.

Versions and what 1.3 gives you

Vulkan 1.0 appeared in 2016. Versions 1.1 and 1.2 added subgroups, timeline semaphores and descriptor indexing, and 1.3 in 2022 promoted a set of extensions into core that remove the most tedious code from the beginner path. Two matter here. Dynamic rendering lets you begin rendering directly into image views with vkCmdBeginRendering, so you do not create VkRenderPass and VkFramebuffer objects. Synchronization2 replaces the old pipeline barrier and queue submission calls with versions that name stages and accesses in 64-bit fields and attach them to each barrier. Vulkan 1.4, released in late 2024, folds in more extensions and raises the set of features every conforming device must support, and everything in this guide runs on 1.4 as well.

The code below requests API version 1.3 and enables the two features explicitly. A device that cannot do so is rejected during device selection, which is correct behavior: on desktop GPUs from the last several years, 1.3 is widely available.

The object model in one page

Vulkan has many object types, and most beginners drown in them. The relationships are simple once you see them in order.

ObjectWhat it representsCreated from
VkInstanceThe connection between your program and the Vulkan loaderNothing
VkSurfaceKHRA window to present toInstance and window
VkPhysicalDeviceA GPU in the machine, read-onlyInstance (enumerated)
VkDeviceYour logical connection to one GPUPhysical device
VkQueueA line you submit work toDevice (retrieved)
VkSwapchainKHRThe images shown on the surfaceDevice and surface
VkImageViewA way to see an image as a render targetImage
VkShaderModuleA compiled shaderDevice
VkPipelineShaders plus fixed-function stateDevice
VkCommandPoolMemory pool for command buffersDevice
VkCommandBufferA recorded list of GPU commandsCommand pool
VkSemaphore, VkFenceSynchronization primitivesDevice

Read the table as a dependency order. You cannot create a device without a physical device, and you cannot create a physical device, because you only choose among those the instance lists. Destruction runs the other way, children before parents, and that is the rule behind every cleanup block in this guide.

Step 1: the instance and validation layers

The instance is the first object. It records which API version you want and which extensions you will use, and it is where you request layers. A layer is a library that sits between your program and the driver and inspects calls. The Khronos validation layer, VK_LAYER_KHRONOS_validation, checks every call against the specification and reports misuse as readable messages. Enable it in every debug build, and treat each message as a bug.

instance.cppcpp
#include <vulkan/vulkan.h>
#include <GLFW/glfw3.h>
#include <cstdint>
#include <cstring>
#include <stdexcept>
#include <vector>

static bool layer_available(const char* name) {
    uint32_t count = 0;
    vkEnumerateInstanceLayerProperties(&count, nullptr);
    std::vector<VkLayerProperties> layers(count);
    vkEnumerateInstanceLayerProperties(&count, layers.data());
    for (const auto& l : layers)
        if (std::strcmp(l.layerName, name) == 0) return true;
    return false;
}

VkInstance create_instance(bool enable_validation) {
    VkApplicationInfo app{};
    app.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
    app.pApplicationName = "guide";
    app.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
    app.pEngineName = "none";
    app.apiVersion = VK_API_VERSION_1_3;

    uint32_t glfw_count = 0;
    const char** glfw_exts = glfwGetRequiredInstanceExtensions(&glfw_count);
    std::vector<const char*> extensions(glfw_exts, glfw_exts + glfw_count);

    std::vector<const char*> layers;
    if (enable_validation) {
        if (!layer_available("VK_LAYER_KHRONOS_validation"))
            throw std::runtime_error("validation layer not installed");
        layers.push_back("VK_LAYER_KHRONOS_validation");
        extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
    }

    VkInstanceCreateFlags flags = 0;
#ifdef __APPLE__
    extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);
    flags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR;
#endif

    VkInstanceCreateInfo ci{};
    ci.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
    ci.flags = flags;
    ci.pApplicationInfo = &app;
    ci.enabledLayerCount = static_cast<uint32_t>(layers.size());
    ci.ppEnabledLayerNames = layers.data();
    ci.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
    ci.ppEnabledExtensionNames = extensions.data();

    VkInstance instance = VK_NULL_HANDLE;
    if (vkCreateInstance(&ci, nullptr, &instance) != VK_SUCCESS)
        throw std::runtime_error("vkCreateInstance failed");
    return instance;
}

Notice the shape of the call, which every Vulkan creation follows. You fill a Create info struct whose first field is an sType tag naming its own type, you point the struct at its arrays, and you pass it to a vkCreate function that writes the handle. The sType tags exist so extension structs can be chained through a pNext pointer, which is how new features are added without changing function signatures. Zero-initializing with {} and setting only what you need is the idiom.

The validation layer prints to the console by default on most platforms when it finds a problem. A typical message, here for a mismatch between the enabled extensions and a call, looks like this:

Text
Validation Error: [ VUID-vkCreateSwapchainKHR-surface-01270 ] Object 0: handle = 0x5584, type = VK_OBJECT_TYPE_SURFACE_KHR | vkCreateSwapchainKHR(): ...

The text between brackets is a VUID, a valid-usage ID, and it is the key into the specification: searching for it finds the exact rule you broke. The identifier and message wording vary by layer version.

Step 2: surface, physical device and queue families

With the instance, create the surface from the window, then choose a GPU. Machines can have several, such as an integrated GPU and a discrete one, and the program decides which to use.

device_select.cppcpp
#include <optional>

struct QueueFamilies {
    std::optional<uint32_t> graphics;
    std::optional<uint32_t> present;
    bool complete() const { return graphics && present; }
};

QueueFamilies find_families(VkPhysicalDevice dev, VkSurfaceKHR surface) {
    uint32_t count = 0;
    vkGetPhysicalDeviceQueueFamilyProperties(dev, &count, nullptr);
    std::vector<VkQueueFamilyProperties> props(count);
    vkGetPhysicalDeviceQueueFamilyProperties(dev, &count, props.data());

    QueueFamilies out;
    for (uint32_t i = 0; i < count; ++i) {
        if (props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) out.graphics = i;
        VkBool32 can_present = VK_FALSE;
        vkGetPhysicalDeviceSurfaceSupportKHR(dev, i, surface, &can_present);
        if (can_present) out.present = i;
        if (out.complete()) break;
    }
    return out;
}

static bool supports_extension(VkPhysicalDevice dev, const char* name) {
    uint32_t count = 0;
    vkEnumerateDeviceExtensionProperties(dev, nullptr, &count, nullptr);
    std::vector<VkExtensionProperties> exts(count);
    vkEnumerateDeviceExtensionProperties(dev, nullptr, &count, exts.data());
    for (const auto& e : exts)
        if (std::strcmp(e.extensionName, name) == 0) return true;
    return false;
}

VkPhysicalDevice pick_device(VkInstance instance, VkSurfaceKHR surface) {
    uint32_t count = 0;
    vkEnumeratePhysicalDevices(instance, &count, nullptr);
    if (count == 0) throw std::runtime_error("no Vulkan GPU");
    std::vector<VkPhysicalDevice> devices(count);
    vkEnumeratePhysicalDevices(instance, &count, devices.data());

    VkPhysicalDevice best = VK_NULL_HANDLE;
    for (auto dev : devices) {
        VkPhysicalDeviceProperties props;
        vkGetPhysicalDeviceProperties(dev, &props);
        if (props.apiVersion < VK_API_VERSION_1_3) continue;
        if (!find_families(dev, surface).complete()) continue;
        if (!supports_extension(dev, VK_KHR_SWAPCHAIN_EXTENSION_NAME)) continue;
        if (props.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) return dev;
        if (best == VK_NULL_HANDLE) best = dev;
    }
    if (best == VK_NULL_HANDLE) throw std::runtime_error("no suitable GPU");
    return best;
}

A queue family is a group of queues with the same capabilities, such as graphics, compute and transfer. Commands are submitted to queues, and which queue can do what is fixed by its family. A family that can run graphics work is not guaranteed to be able to present to your window, which is why presentation support is queried per family and per surface, and why the code tracks two indices that are usually, but not always, equal.

The selection prefers a discrete GPU and falls back to the first usable one. For output, a laptop with an integrated and a discrete GPU would print the chosen device's name, which comes from props.deviceName:

Text
GPU: NVIDIA GeForce RTX 3060 Laptop GPU

The text depends on your hardware. A production selector scores devices by memory size and features and lets the user override the choice.

Step 3: the logical device and its queues

The physical device is a read-only description. The logical device is what you actually use, and creating it is where you turn on the features you need and declare which queues you want.

logical_device.cppcpp
struct Device {
    VkDevice device = VK_NULL_HANDLE;
    VkQueue graphics = VK_NULL_HANDLE;
    VkQueue present = VK_NULL_HANDLE;
};

Device create_device(VkPhysicalDevice phys, const QueueFamilies& fam) {
    std::vector<uint32_t> unique = { *fam.graphics };
    if (*fam.present != *fam.graphics) unique.push_back(*fam.present);

    float priority = 1.0f;
    std::vector<VkDeviceQueueCreateInfo> queues;
    for (uint32_t family : unique) {
        VkDeviceQueueCreateInfo q{};
        q.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
        q.queueFamilyIndex = family;
        q.queueCount = 1;
        q.pQueuePriorities = &priority;
        queues.push_back(q);
    }

    VkPhysicalDeviceVulkan13Features f13{};
    f13.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES;
    f13.dynamicRendering = VK_TRUE;
    f13.synchronization2 = VK_TRUE;

    const char* exts[] = { VK_KHR_SWAPCHAIN_EXTENSION_NAME };

    VkDeviceCreateInfo ci{};
    ci.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
    ci.pNext = &f13;
    ci.queueCreateInfoCount = static_cast<uint32_t>(queues.size());
    ci.pQueueCreateInfos = queues.data();
    ci.enabledExtensionCount = 1;
    ci.ppEnabledExtensionNames = exts;

    Device d;
    if (vkCreateDevice(phys, &ci, nullptr, &d.device) != VK_SUCCESS)
        throw std::runtime_error("vkCreateDevice failed");
    vkGetDeviceQueue(d.device, *fam.graphics, 0, &d.graphics);
    vkGetDeviceQueue(d.device, *fam.present, 0, &d.present);
    return d;
}

The pNext chain in action: the 1.3 feature struct hangs off the device create info, and that is how you request dynamic rendering and synchronization2. Enabling a feature the physical device does not support makes vkCreateDevice fail. Using a feature you did not enable is a validation error.

The set of unique families matters because a queue family can be requested only once in the create info. If graphics and presentation share a family, which is the usual case on desktop hardware, the code requests one queue. The two queues the program holds afterward may then be the same handle.

Step 4: the swapchain

Vulkan has no default framebuffer. The images you draw to and present come from a swapchain, an object that owns a queue of images tied to a surface. You choose the format, the size, the number of images and how they are presented.

swapchain.cppcpp
struct Swapchain {
    VkSwapchainKHR handle = VK_NULL_HANDLE;
    VkFormat format{};
    VkExtent2D extent{};
    std::vector<VkImage> images;
    std::vector<VkImageView> views;
};

Swapchain create_swapchain(VkPhysicalDevice phys, VkDevice dev, VkSurfaceKHR surface,
                           GLFWwindow* window, const QueueFamilies& fam,
                           VkSwapchainKHR old = VK_NULL_HANDLE) {
    VkSurfaceCapabilitiesKHR caps;
    vkGetPhysicalDeviceSurfaceCapabilitiesKHR(phys, surface, &caps);

    uint32_t fcount = 0;
    vkGetPhysicalDeviceSurfaceFormatsKHR(phys, surface, &fcount, nullptr);
    std::vector<VkSurfaceFormatKHR> formats(fcount);
    vkGetPhysicalDeviceSurfaceFormatsKHR(phys, surface, &fcount, formats.data());

    VkSurfaceFormatKHR chosen = formats[0];
    for (const auto& f : formats)
        if (f.format == VK_FORMAT_B8G8R8A8_SRGB &&
            f.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) chosen = f;

    VkExtent2D extent = caps.currentExtent;
    if (extent.width == UINT32_MAX) {
        int w, h;
        glfwGetFramebufferSize(window, &w, &h);
        extent.width  = std::clamp<uint32_t>(w, caps.minImageExtent.width,  caps.maxImageExtent.width);
        extent.height = std::clamp<uint32_t>(h, caps.minImageExtent.height, caps.maxImageExtent.height);
    }

    uint32_t image_count = caps.minImageCount + 1;
    if (caps.maxImageCount > 0 && image_count > caps.maxImageCount)
        image_count = caps.maxImageCount;

    VkSwapchainCreateInfoKHR ci{};
    ci.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
    ci.surface = surface;
    ci.minImageCount = image_count;
    ci.imageFormat = chosen.format;
    ci.imageColorSpace = chosen.colorSpace;
    ci.imageExtent = extent;
    ci.imageArrayLayers = 1;
    ci.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
    ci.preTransform = caps.currentTransform;
    ci.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
    ci.presentMode = VK_PRESENT_MODE_FIFO_KHR;
    ci.clipped = VK_TRUE;
    ci.oldSwapchain = old;

    uint32_t indices[] = { *fam.graphics, *fam.present };
    if (indices[0] != indices[1]) {
        ci.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
        ci.queueFamilyIndexCount = 2;
        ci.pQueueFamilyIndices = indices;
    } else {
        ci.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
    }

    Swapchain sc;
    if (vkCreateSwapchainKHR(dev, &ci, nullptr, &sc.handle) != VK_SUCCESS)
        throw std::runtime_error("vkCreateSwapchainKHR failed");
    sc.format = chosen.format;
    sc.extent = extent;

    uint32_t n = 0;
    vkGetSwapchainImagesKHR(dev, sc.handle, &n, nullptr);
    sc.images.resize(n);
    vkGetSwapchainImagesKHR(dev, sc.handle, &n, sc.images.data());

    for (VkImage img : sc.images) {
        VkImageViewCreateInfo vi{};
        vi.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
        vi.image = img;
        vi.viewType = VK_IMAGE_VIEW_TYPE_2D;
        vi.format = sc.format;
        vi.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
        VkImageView view;
        vkCreateImageView(dev, &vi, nullptr, &view);
        sc.views.push_back(view);
    }
    return sc;
}

Three decisions are in this function. The format prefers an sRGB 8-bit format, so the hardware converts linear shader output to sRGB on write. The extent comes from the surface when the platform dictates it, and from the window's framebuffer size when the surface reports the special value UINT32_MAX that means "you choose". The present mode is FIFO, the one mode every conforming implementation must support: it waits for the display's vertical blank, behaves like vsync and never tears. The alternatives, MAILBOX for low-latency replacement of queued frames and IMMEDIATE for tearing, are optional and must be checked for availability.

Add #include <algorithm> for std::clamp. The oldSwapchain parameter is the hook for recreation on resize, discussed later.

An image view wraps each swapchain image so a render pass or dynamic rendering can use it, with a format, a type and a range of mip levels and layers. A swapchain image has one mip level and one layer, which the range encodes.

Step 5: shaders and the graphics pipeline

A pipeline bundles everything the GPU needs to draw: the shaders, the vertex input layout, the primitive type, the rasterizer settings, the blend state and the formats of the targets. It is immutable once built, and it is expensive to create, so a program builds its pipelines at load time.

Shaders arrive as SPIR-V. A GLSL vertex shader that draws a triangle from the vertex index, with no buffers:

triangle.vertglsl
#version 450

layout(location = 0) out vec3 vColor;

void main() {
    vec2 pos[3] = vec2[](vec2(0.0, -0.5), vec2(0.5, 0.5), vec2(-0.5, 0.5));
    vec3 col[3] = vec3[](vec3(1, 0, 0), vec3(0, 1, 0), vec3(0, 0, 1));
    gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);
    vColor = col[gl_VertexIndex];
}
triangle.fragglsl
#version 450

layout(location = 0) in vec3 vColor;
layout(location = 0) out vec4 outColor;

void main() {
    outColor = vec4(vColor, 1.0);
}

Compile them to SPIR-V with glslc triangle.vert -o triangle.vert.spv and the same for the fragment shader. With dynamic rendering, the pipeline learns about its render target through a struct chained into its create info, instead of through a render pass:

pipeline.cppcpp
VkPipeline create_pipeline(VkDevice dev, VkShaderModule vs, VkShaderModule fs,
                           VkFormat color_format, VkPipelineLayout layout) {
    VkPipelineShaderStageCreateInfo stages[2]{};
    stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
    stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
    stages[0].module = vs;
    stages[0].pName = "main";
    stages[1] = stages[0];
    stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
    stages[1].module = fs;

    VkPipelineVertexInputStateCreateInfo vertex_input{};
    vertex_input.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;

    VkPipelineInputAssemblyStateCreateInfo assembly{};
    assembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
    assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;

    VkPipelineViewportStateCreateInfo viewport{};
    viewport.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
    viewport.viewportCount = 1;
    viewport.scissorCount = 1;

    VkPipelineRasterizationStateCreateInfo raster{};
    raster.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
    raster.polygonMode = VK_POLYGON_MODE_FILL;
    raster.cullMode = VK_CULL_MODE_NONE;
    raster.frontFace = VK_FRONT_FACE_CLOCKWISE;
    raster.lineWidth = 1.0f;

    VkPipelineMultisampleStateCreateInfo msaa{};
    msaa.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
    msaa.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;

    VkPipelineColorBlendAttachmentState blend_att{};
    blend_att.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
                               VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
    VkPipelineColorBlendStateCreateInfo blend{};
    blend.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
    blend.attachmentCount = 1;
    blend.pAttachments = &blend_att;

    VkDynamicState dyn_states[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
    VkPipelineDynamicStateCreateInfo dynamic{};
    dynamic.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
    dynamic.dynamicStateCount = 2;
    dynamic.pDynamicStates = dyn_states;

    VkPipelineRenderingCreateInfo rendering{};
    rendering.sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO;
    rendering.colorAttachmentCount = 1;
    rendering.pColorAttachmentFormats = &color_format;

    VkGraphicsPipelineCreateInfo ci{};
    ci.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
    ci.pNext = &rendering;
    ci.stageCount = 2;
    ci.pStages = stages;
    ci.pVertexInputState = &vertex_input;
    ci.pInputAssemblyState = &assembly;
    ci.pViewportState = &viewport;
    ci.pRasterizationState = &raster;
    ci.pMultisampleState = &msaa;
    ci.pColorBlendState = &blend;
    ci.pDynamicState = &dynamic;
    ci.layout = layout;

    VkPipeline pipeline = VK_NULL_HANDLE;
    if (vkCreateGraphicsPipelines(dev, VK_NULL_HANDLE, 1, &ci, nullptr, &pipeline) != VK_SUCCESS)
        throw std::runtime_error("pipeline creation failed");
    return pipeline;
}

Making the viewport and scissor dynamic state means they are set when recording commands, so a window resize does not force a pipeline rebuild. The pipeline layout, created with vkCreatePipelineLayout and an empty set of descriptor layouts here, declares what resources the shaders may read, which is none for this triangle. A VkPipelineRenderingCreateInfo replaces the render pass: it states the format of the color attachment, and the pipeline is compatible with any rendering that uses that format.

Step 6: command pools and buffers

The CPU does not call draw functions that run now. It records commands into a command buffer, and then submits the buffer to a queue, which runs it later. Command buffers are allocated from a command pool, which belongs to one queue family.

commands.cppcpp
VkCommandPool create_pool(VkDevice dev, uint32_t family) {
    VkCommandPoolCreateInfo ci{};
    ci.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
    ci.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
    ci.queueFamilyIndex = family;
    VkCommandPool pool;
    vkCreateCommandPool(dev, &ci, nullptr, &pool);
    return pool;
}

VkCommandBuffer allocate_buffer(VkDevice dev, VkCommandPool pool) {
    VkCommandBufferAllocateInfo ai{};
    ai.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
    ai.commandPool = pool;
    ai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
    ai.commandBufferCount = 1;
    VkCommandBuffer cb;
    vkAllocateCommandBuffers(dev, &ai, &cb);
    return cb;
}

The reset flag allows a single buffer to be re-recorded every frame, which is the simple approach. Command pools are not thread safe, which is deliberate: a multithreaded renderer gives each thread its own pool, and that is how Vulkan achieves parallel recording without internal locks.

Step 7: recording a frame

Recording a frame has three parts: move the swapchain image into a layout where it can be rendered to, draw inside a rendering scope, and move the image into the layout that presentation requires. A layout is a promise about how an image will be used, and transitions between layouts are barriers.

record.cppcpp
void transition(VkCommandBuffer cb, VkImage image,
                VkImageLayout from, VkImageLayout to,
                VkPipelineStageFlags2 src_stage, VkAccessFlags2 src_access,
                VkPipelineStageFlags2 dst_stage, VkAccessFlags2 dst_access) {
    VkImageMemoryBarrier2 b{};
    b.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2;
    b.srcStageMask = src_stage;
    b.srcAccessMask = src_access;
    b.dstStageMask = dst_stage;
    b.dstAccessMask = dst_access;
    b.oldLayout = from;
    b.newLayout = to;
    b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
    b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
    b.image = image;
    b.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };

    VkDependencyInfo dep{};
    dep.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO;
    dep.imageMemoryBarrierCount = 1;
    dep.pImageMemoryBarriers = &b;
    vkCmdPipelineBarrier2(cb, &dep);
}

void record_frame(VkCommandBuffer cb, const Swapchain& sc, uint32_t image_index,
                  VkPipeline pipeline) {
    VkCommandBufferBeginInfo begin{};
    begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
    begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
    vkBeginCommandBuffer(cb, &begin);

    transition(cb, sc.images[image_index],
               VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
               VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT, 0,
               VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT,
               VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT);

    VkRenderingAttachmentInfo color{};
    color.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO;
    color.imageView = sc.views[image_index];
    color.imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
    color.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
    color.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
    color.clearValue.color = { { 0.05f, 0.06f, 0.09f, 1.0f } };

    VkRenderingInfo ri{};
    ri.sType = VK_STRUCTURE_TYPE_RENDERING_INFO;
    ri.renderArea = { { 0, 0 }, sc.extent };
    ri.layerCount = 1;
    ri.colorAttachmentCount = 1;
    ri.pColorAttachments = &color;

    vkCmdBeginRendering(cb, &ri);
    vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);

    VkViewport vp{ 0.0f, 0.0f, (float)sc.extent.width, (float)sc.extent.height, 0.0f, 1.0f };
    VkRect2D scissor{ { 0, 0 }, sc.extent };
    vkCmdSetViewport(cb, 0, 1, &vp);
    vkCmdSetScissor(cb, 0, 1, &scissor);
    vkCmdDraw(cb, 3, 1, 0, 0);
    vkCmdEndRendering(cb);

    transition(cb, sc.images[image_index],
               VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
               VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT,
               VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT,
               VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT, 0);

    vkEndCommandBuffer(cb);
}

The first transition goes from UNDEFINED, which tells the driver it may discard the old contents, to COLOR_ATTACHMENT_OPTIMAL. The last goes to PRESENT_SRC_KHR, the only layout from which an image may be presented. The stage and access masks say which work must finish before the transition and which work may start after it. The clear color is a fixed dark blue, and the vkCmdDraw call asks for 3 vertices and 1 instance, which the vertex shader turns into a triangle. This is where Synchronization2 earns its name: each barrier carries its own source and destination stages in one struct, so the intent reads in one place.

Step 8: synchronization

The GPU runs asynchronously. When you submit a command buffer, the call returns long before the work completes, and the program must prevent three hazards: drawing into an image that is still being presented, reusing a command buffer that the GPU is still reading, and presenting before drawing finishes. Vulkan provides two primitives for these jobs.

A semaphore synchronizes work between queue operations on the GPU. A fence lets the CPU wait for the GPU. The frame loop uses semaphores to order acquire, render and present, and a fence to know when it is safe to re-record a command buffer.

Because the CPU can record frame N+1 while the GPU is still running frame N, a renderer keeps a small number of frames in flight, usually two, each with its own command buffer, semaphore and fence:

frame_sync.cppcpp
constexpr int FRAMES_IN_FLIGHT = 2;

struct FrameSync {
    VkSemaphore image_available = VK_NULL_HANDLE;
    VkFence in_flight = VK_NULL_HANDLE;
    VkCommandBuffer cmd = VK_NULL_HANDLE;
};

FrameSync make_frame_sync(VkDevice dev, VkCommandPool pool) {
    FrameSync f;
    VkSemaphoreCreateInfo si{ VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
    VkFenceCreateInfo fi{ VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
    fi.flags = VK_FENCE_CREATE_SIGNALED_BIT;
    vkCreateSemaphore(dev, &si, nullptr, &f.image_available);
    vkCreateFence(dev, &fi, nullptr, &f.in_flight);
    f.cmd = allocate_buffer(dev, pool);
    return f;
}

The fence is created already signaled, so the first wait at the top of the loop returns immediately instead of waiting forever for a frame that never ran. The render_finished semaphore, which orders rendering before presentation, is created per swapchain image rather than per frame in flight, because the presentation engine may still hold a semaphore after the frame's fence signals, and reusing it too early is a validation error that newer layers report.

Step 9: the frame loop

Each iteration waits for the frame's fence, acquires an image, records, submits and presents. The structure is the same in every Vulkan program:

frame_loop.cppcpp
void draw_frame(VkDevice dev, VkQueue gfx, VkQueue present, Swapchain& sc,
                std::vector<VkSemaphore>& render_finished,
                FrameSync& frame, VkPipeline pipeline, bool& need_resize) {
    vkWaitForFences(dev, 1, &frame.in_flight, VK_TRUE, UINT64_MAX);

    uint32_t index = 0;
    VkResult r = vkAcquireNextImageKHR(dev, sc.handle, UINT64_MAX,
                                       frame.image_available, VK_NULL_HANDLE, &index);
    if (r == VK_ERROR_OUT_OF_DATE_KHR) { need_resize = true; return; }
    if (r != VK_SUCCESS && r != VK_SUBOPTIMAL_KHR)
        throw std::runtime_error("acquire failed");

    vkResetFences(dev, 1, &frame.in_flight);
    vkResetCommandBuffer(frame.cmd, 0);
    record_frame(frame.cmd, sc, index, pipeline);

    VkSemaphoreSubmitInfo wait{};
    wait.sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO;
    wait.semaphore = frame.image_available;
    wait.stageMask = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT;

    VkSemaphoreSubmitInfo signal{};
    signal.sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO;
    signal.semaphore = render_finished[index];
    signal.stageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT;

    VkCommandBufferSubmitInfo cmd{};
    cmd.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_SUBMIT_INFO;
    cmd.commandBuffer = frame.cmd;

    VkSubmitInfo2 submit{};
    submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO_2;
    submit.waitSemaphoreInfoCount = 1;
    submit.pWaitSemaphoreInfos = &wait;
    submit.commandBufferInfoCount = 1;
    submit.pCommandBufferInfos = &cmd;
    submit.signalSemaphoreInfoCount = 1;
    submit.pSignalSemaphoreInfos = &signal;
    vkQueueSubmit2(gfx, 1, &submit, frame.in_flight);

    VkPresentInfoKHR pi{};
    pi.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
    pi.waitSemaphoreCount = 1;
    pi.pWaitSemaphores = &render_finished[index];
    pi.swapchainCount = 1;
    pi.pSwapchains = &sc.handle;
    pi.pImageIndices = &index;
    r = vkQueuePresentKHR(present, &pi);
    if (r == VK_ERROR_OUT_OF_DATE_KHR || r == VK_SUBOPTIMAL_KHR) need_resize = true;
}

Walk the order. The fence wait ensures the previous use of this frame's command buffer has finished. vkAcquireNextImageKHR asks the presentation engine for an image and signals the image_available semaphore when it is ready to be written, and the submit waits on that semaphore at the color-attachment-output stage, so earlier pipeline stages that do not touch the image can start early. The submit signals the per-image render_finished semaphore and the fence when the work completes. The present waits on the semaphore. If acquire or present reports that the swapchain is out of date, the surface changed, and the program must recreate the swapchain. A window with this loop running shows the dark background and a triangle with red, green and blue corners.

Step 10: resize and recreation

A swapchain is tied to the size of the surface, and when the window changes size the swapchain becomes out of date. Recovery has a fixed shape: wait for the GPU to be idle, destroy the old image views, create a new swapchain passing the old one as oldSwapchain, destroy the old swapchain and rebuild whatever depended on the images. A minimized window reports a zero extent, so the program should pause until the size is non-zero, using glfwWaitEvents. Handling the framebuffer-size callback to set a flag, as the loop above does with need_resize, avoids relying on the driver to report the change. The resize post in this series covers the details, including how to avoid stalling the GPU.

Step 11: memory, buffers and images

The triangle needed no buffers, because its data lives in the shader. Real geometry needs vertex and index buffers, uniform data and textures, and in Vulkan, creating a buffer does not give it memory. You create the buffer object, query its memory requirements, allocate a VkDeviceMemory from a memory type that satisfies the requirements and the properties you want, and bind the two. The device reports its memory types and heaps, and the usual split is device-local memory, fast for the GPU and not mapped by the CPU, and host-visible memory the CPU can write.

The standard upload path stages data through host-visible memory:

  1. Create a staging buffer in host-visible, coherent memory and write the data into it through a mapped pointer.

  2. Create the destination buffer or image in device-local memory.

  3. Record a copy command, vkCmdCopyBuffer or vkCmdCopyBufferToImage, and submit it.

  4. Wait for completion, then free the staging buffer.

Doing this by hand for every resource is error prone, and there is a hard limit on the number of allocations a device allows, which is why almost every real project uses the VulkanMemoryAllocator library. It suballocates large blocks, picks memory types from usage flags and offers helpers for mapped staging buffers. Writing the raw allocation code once is a good exercise, and a production renderer should adopt the library afterward.

Step 12: descriptors and push constants

Shaders read resources, such as uniform buffers, textures and storage buffers, through descriptors. A descriptor is a small handle describing a resource, grouped into descriptor sets, which are bound as a unit. Three objects are involved. A descriptor set layout declares the bindings, their types and the shader stages that read them. A descriptor pool allocates sets. And vkUpdateDescriptorSets points a set at the actual buffers and images. The pipeline layout lists the set layouts a pipeline uses, which is how the pipeline knows the resource interface.

For small, frequently changing data, such as a transform matrix per draw, push constants are simpler. They are a few bytes, at least 128 on every conforming device, written directly into the command buffer with vkCmdPushConstants and read in the shader from a push_constant block. Use push constants for per-draw data, uniform buffers for per-frame data and descriptor sets with arrays or indexing for large collections of textures. A later post on pipelines and descriptors in this series covers the binding model in depth.

Step 13: debugging

Debugging Vulkan means using the tools that exist because the driver will not help. In order of how often you need them:

The validation layer catches API misuse as you run, and a clean run with it enabled is the baseline. Add the debug messenger from VK_EXT_debug_utils to route its messages into your logger, with severity filtering, instead of leaving them on the console. The same extension lets you name objects with vkSetDebugUtilsObjectNameEXT, so messages refer to "swapchain image 2" instead of a hex handle, and mark regions of a command buffer with vkCmdBeginDebugUtilsLabelEXT, so captures show a readable structure.

A frame capture tool such as RenderDoc records a frame and lets you inspect every draw, its pipeline state, bound resources and the output image after each step. When something draws wrong, a capture answers "what did the GPU actually receive?" more reliably than speculation.

The GPU vendor tools profile real hardware. They show occupancy, memory bandwidth and the cost of each pass, and they are where performance work starts. Never optimize a Vulkan renderer from reading code alone, since the answer depends on the hardware.

A debug build should also run with synchronization validation, enabled through the layer's settings, which flags missing barriers that a driver might tolerate on one GPU and break on another. Missing synchronization is the bug that appears only on a customer's machine.

Present modes and queue families beyond the basics

Two choices made quickly in the first renderer deserve a second look once it runs. The first is the present mode. FIFO is the only mode every implementation must offer, and it ties presentation to the display's refresh, so the loop runs at the refresh rate and the GPU idles in between. FIFO_RELAXED behaves the same until a frame arrives late, and then presents at once, which can tear but avoids halving the frame rate after a slow frame. MAILBOX keeps one waiting image and replaces it when a newer one arrives, giving low latency without tearing at the cost of rendering frames nobody sees. IMMEDIATE presents without waiting. To use anything other than FIFO, query vkGetPhysicalDeviceSurfacePresentModesKHR and pick from the list it returns, falling back to FIFO when your preference is missing.

The second is the queue layout. This guide submits graphics and presentation on one queue, which is the common case, and many GPUs also expose a dedicated compute family and a dedicated transfer family that run independently of graphics. A renderer that streams textures can upload on the transfer queue while the graphics queue draws, and a renderer with heavy particle or culling work can run it on the compute queue. Using them has a cost in complexity: resources touched by two queue families need an explicit queue family ownership transfer, a pair of barriers, unless the resource is created with concurrent sharing mode. The decision rule is to start with one queue, measure, and add queues only where a profile shows the graphics queue waiting for work that could overlap.

A final point about formats. The swapchain format in the guide is B8G8R8A8_SRGB, which is nearly universal on desktop. Mobile and HDR displays offer others, such as R8G8B8A8_SRGB or a 10-bit format with a different color space, and code that assumes the first is present should check the list. If you render with a floating-point intermediate target for lighting and tone-map into the swapchain at the end, the swapchain format matters only for the last pass, which keeps the rest of the renderer independent of what the display accepts.

Frames in flight, step by step

The synchronization in the loop is easier to trust once you trace it. With two frames in flight and three swapchain images, the loop runs like this over its first few iterations, where frame slot A and frame slot B alternate:

IterationFrame slotFence waitAcquires imageWhat the GPU is doing
1AReturns at once, created signaled0Rendering image 0
2BReturns at once, created signaled1Still on image 0, then image 1
3AWaits until iteration 1 finished2Rendering image 2
4BWaits until iteration 2 finished0Rendering image 0 again

The point of the table is that the CPU never gets more than two frames ahead. Iteration 3 cannot start recording into slot A until the GPU has finished iteration 1, because the command buffer in slot A is still being read. If the CPU were allowed to run ahead without limit, latency would grow, memory would pile up and eventually the process would run out of command buffers.

The image index returned by acquire is independent of the frame slot. The presentation engine hands back images in an order it chooses, which is why the render-finished semaphores are indexed by image and the image-available semaphores by slot. Mixing the two indices is the most common synchronization bug in a first renderer, and the validation layer reports it with a message about a semaphore being signaled while still pending.

Two frames in flight is a good default. One removes all overlap between CPU and GPU, so each waits on the other. Three adds latency, since the picture you present was recorded two frames earlier, for a benefit that matters only when frame times vary a lot.

Timeline semaphores

Binary semaphores, the kind used above, are either signaled or not, and each signal must be matched by exactly one wait. Vulkan 1.2 made timeline semaphores core: a timeline semaphore holds a 64-bit counter that only increases, and you wait for it to reach a value. One timeline semaphore can replace the fence and the semaphores of a frame, with a rule such as "frame N is complete when the counter reaches N":

timeline.cppcpp
VkSemaphoreTypeCreateInfo type{};
type.sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO;
type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE;
type.initialValue = 0;

VkSemaphoreCreateInfo ci{};
ci.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
ci.pNext = &type;

VkSemaphore timeline;
vkCreateSemaphore(device, &ci, nullptr, &timeline);

// the CPU waits until the GPU has reached frame_number - FRAMES_IN_FLIGHT
VkSemaphoreWaitInfo wait{};
wait.sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO;
wait.semaphoreCount = 1;
wait.pSemaphores = &timeline;
uint64_t target = frame_number - FRAMES_IN_FLIGHT;
wait.pValues = &target;
vkWaitSemaphores(device, &wait, UINT64_MAX);

Swapchain acquire and present still use binary semaphores, because the presentation engine does not accept timeline values, so a renderer that uses timelines for its own work keeps a small set of binary ones at that boundary. Timelines shine for work between queues, such as a compute pass that feeds graphics, where "wait for value 17" is far less error prone than a web of binary semaphores.

Uploading a vertex buffer, start to finish

A triangle from the shader is a demonstration, and real meshes come from memory. The code below creates a device-local vertex buffer filled through a staging buffer. It uses a helper that finds a memory type matching the requirements and the properties you ask for:

buffer.cppcpp
uint32_t find_memory_type(VkPhysicalDevice phys, uint32_t type_bits, VkMemoryPropertyFlags want) {
    VkPhysicalDeviceMemoryProperties mem;
    vkGetPhysicalDeviceMemoryProperties(phys, &mem);
    for (uint32_t i = 0; i < mem.memoryTypeCount; ++i) {
        bool allowed = (type_bits & (1u << i)) != 0;
        bool matches = (mem.memoryTypes[i].propertyFlags & want) == want;
        if (allowed && matches) return i;
    }
    throw std::runtime_error("no suitable memory type");
}

struct Buffer { VkBuffer buffer; VkDeviceMemory memory; };

Buffer create_buffer(VkPhysicalDevice phys, VkDevice dev, VkDeviceSize size,
                     VkBufferUsageFlags usage, VkMemoryPropertyFlags props) {
    VkBufferCreateInfo bi{};
    bi.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
    bi.size = size;
    bi.usage = usage;
    bi.sharingMode = VK_SHARING_MODE_EXCLUSIVE;

    Buffer b{};
    vkCreateBuffer(dev, &bi, nullptr, &b.buffer);

    VkMemoryRequirements req;
    vkGetBufferMemoryRequirements(dev, b.buffer, &req);

    VkMemoryAllocateInfo ai{};
    ai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
    ai.allocationSize = req.size;
    ai.memoryTypeIndex = find_memory_type(phys, req.memoryTypeBits, props);
    vkAllocateMemory(dev, &ai, nullptr, &b.memory);
    vkBindBufferMemory(dev, b.buffer, b.memory, 0);
    return b;
}

The requirements struct is the contract: req.size can be larger than the size you asked for because of alignment, and req.memoryTypeBits is a mask of the memory types the buffer may use. The helper intersects that mask with the properties you want, which is the whole of Vulkan's memory-type selection.

The upload then stages and copies:

upload.cppcpp
Buffer upload_vertices(VkPhysicalDevice phys, VkDevice dev, VkCommandPool pool, VkQueue queue,
                       const void* data, VkDeviceSize size) {
    Buffer staging = create_buffer(phys, dev, size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
        VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);

    void* mapped = nullptr;
    vkMapMemory(dev, staging.memory, 0, size, 0, &mapped);
    std::memcpy(mapped, data, static_cast<size_t>(size));
    vkUnmapMemory(dev, staging.memory);

    Buffer gpu = create_buffer(phys, dev, size,
        VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
        VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);

    VkCommandBuffer cb = allocate_buffer(dev, pool);
    VkCommandBufferBeginInfo begin{};
    begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
    begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
    vkBeginCommandBuffer(cb, &begin);
    VkBufferCopy region{ 0, 0, size };
    vkCmdCopyBuffer(cb, staging.buffer, gpu.buffer, 1, &region);
    vkEndCommandBuffer(cb);

    VkSubmitInfo submit{};
    submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
    submit.commandBufferCount = 1;
    submit.pCommandBuffers = &cb;
    vkQueueSubmit(queue, 1, &submit, VK_NULL_HANDLE);
    vkQueueWaitIdle(queue);

    vkFreeCommandBuffers(dev, pool, 1, &cb);
    vkDestroyBuffer(dev, staging.buffer, nullptr);
    vkFreeMemory(dev, staging.memory, nullptr);
    return gpu;
}

The vkQueueWaitIdle is the blunt way to wait for the copy, and it is acceptable at load time. A streaming renderer would use a fence or a transfer queue instead. Host-coherent memory spares you flush calls, because writes are visible to the device without vkFlushMappedMemoryRanges, and without the coherent flag you must flush the range yourself.

To draw from the buffer, bind it and describe its layout in the pipeline's vertex input state, with a binding of the vertex stride and an attribute for each field. A vertex of two floats of position and three of color has a stride of 20 bytes, so the binding description says stride = 20 and the attributes say offsets 0 and 8:

Text
binding 0: stride 20, per-vertex
  location 0: R32G32_SFLOAT       offset 0   (position)
  location 1: R32G32B32_SFLOAT    offset 8   (color)

At draw time, vkCmdBindVertexBuffers(cb, 0, 1, &gpu.buffer, &offset) followed by vkCmdDraw(cb, vertex_count, 1, 0, 0) replaces the shader-generated triangle.

Push constants in code

The push constant block has a fixed small size, and you declare its range in the pipeline layout. A model matrix of 64 bytes fits in the minimum of 128:

push_constants.cppcpp
struct Push { float model[16]; };

VkPushConstantRange range{};
range.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
range.offset = 0;
range.size = sizeof(Push);

VkPipelineLayoutCreateInfo li{};
li.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
li.pushConstantRangeCount = 1;
li.pPushConstantRanges = &range;
VkPipelineLayout layout;
vkCreatePipelineLayout(device, &li, nullptr, &layout);

// while recording, once per draw:
vkCmdPushConstants(cb, layout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(Push), &push);
push.vertglsl
layout(push_constant) uniform Push { mat4 model; } pc;

The stage flags in the shader's use, the layout's range and the command must agree, or the validation layer reports a mismatch. This is the cheapest way to vary a draw without descriptor updates.

Reading a validation message

A message from the validation layer has a regular structure, and learning to read it saves hours. Take this example, which a program triggers by drawing before binding a pipeline:

Text
Validation Error: [ VUID-vkCmdDraw-None-08606 ] | MessageID = 0x8c3e... | vkCmdDraw(): The VkPipeline state is not bound for this command buffer, but the draw requires a bound graphics pipeline.
The Vulkan spec states: A valid pipeline must be bound to the pipeline bind point used by this command

The exact ID and wording vary with the layer version, but the parts are constant. The severity and the VUID come first, and the VUID is searchable in the specification. The name of the failing call follows, which tells you where in your code to look. The sentence after it describes what is wrong in the layer's own words. Finally, "The Vulkan spec states" repeats the rule verbatim, so you can read the requirement without leaving the console. Fix the first error before the others, because one mistake often produces a cascade of later messages that disappear when it is resolved.

Common errors and what they mean

SymptomLikely cause
VK_ERROR_INCOMPATIBLE_DRIVER from vkCreateInstanceLoader found no usable driver, or on macOS the portability flag is missing
VK_ERROR_EXTENSION_NOT_PRESENTAn extension was requested that the instance or device lacks
Black window, no validation errorsLayout never transitioned, wrong viewport or a pipeline that culls everything
Validation: image layout mismatchA barrier names the wrong old layout, or one is missing
Validation: semaphore still in useA semaphore reused before the presentation engine released it
Crash in vkDestroyDeviceObjects still alive, or work still in flight when the device was destroyed
VK_ERROR_OUT_OF_DATE_KHR on resizeExpected, recreate the swapchain
Works on one GPU, fails on anotherMissing synchronization, or relying on an unqueried limit

Always call vkDeviceWaitIdle before destroying objects the GPU might still use.

Putting the pieces in order

The sequence of a complete program, with each item mapping to a section above, is: initialize the windowing library with no client API, create the instance with validation, create the surface, pick the physical device, create the logical device and queues, create the swapchain and views, create shader modules and the pipeline layout and pipeline, create the command pool and the per-frame command buffers, semaphores and fences, then loop on events and draw_frame, recreating the swapchain when it reports out of date, and on exit wait for idle and destroy everything in reverse order. A first version is about 600 lines in a single file, and it is worth getting working before splitting it up, because the order of calls is the lesson.

Resist the urge to build abstractions early. The Vulkan objects are the vocabulary, and a wrapper written before you understand them hides the structure you are trying to learn. Write the program flat, then extract what repeats.

When to choose something else

Vulkan is a poor fit for some work. If the aim is to learn graphics concepts, such as lighting, shadows and materials, OpenGL gets you to the interesting part in a tenth of the code, and the concepts transfer. If the target is Apple platforms only, Metal is the native API and avoids a translation layer. If the project needs Vulkan's portability but not its verbosity, the SDL3 GPU API and engines such as bgfx and wgpu provide a smaller explicit API above the native ones. And if the workload is compute and you want Vulkan's portability, check whether a compute-focused framework covers it before taking on the graphics surface.

Vulkan repays the effort for engines, for tools that must scale across many cores and for products that ship on several platforms with one renderer. If that is not your project, a simpler API is the better engineering choice, and nothing in this guide says otherwise.

Where the rest of the series goes

The steps above are the skeleton, and each has deeper material. The Vulkan setup posts cover the SDK, validation messenger, device selection details, the loader's JSON manifests and extension handling. The pipeline posts cover shaders, vertex input, descriptors and pipeline caches. The synchronization and memory posts cover barriers in depth, timeline semaphores, allocation strategy and aliasing. Read them in that order after building the loop in this guide, and keep the specification open in a tab, because the valid-usage statements in it are the actual contract.

The facts in this guide come from the Vulkan 1.3 specification and the Vulkan Guide, and the tooling from the LunarG Vulkan SDK documentation.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.