TExcelTAD
Home › Shaders & Graphics Programming › Vulkan 2: Pipelines, Commands, Sync, Memory

Vulkan 2: Pipelines, Commands, Sync, Memory

The previous lesson created a device and a swapchain. Now we draw. In Vulkan, drawing involves four ideas that OpenGL hid from you:

  1. Pipelines: all shader and fixed-function state, compiled ahead of time.
  2. Command buffers: GPU work is recorded first and submitted later.
  3. Synchronization: you tell the GPU what must finish before what.
  4. Memory: you allocate GPU memory and bind it to buffers and images.

As before, the snippets are shortened C++ (error checks and some fields omitted), with runnable models where the idea is pure logic.

Shader modules

Vulkan does not compile GLSL. You compile shaders ahead of time to SPIR-V (with glslc, glslangValidator, DXC or Slang, see the Toolkit) and load the bytes:

cpp
std::vector<char> code = readFile("shaders/triangle.frag.spv");
VkShaderModuleCreateInfo smci{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
smci.codeSize = code.size();
smci.pCode = reinterpret_cast<const uint32_t*>(code.data());
VkShaderModule fragModule;
vkCreateShaderModule(device, &smci, nullptr, &fragModule);

The GLSL you write for Vulkan is almost the GLSL of this course, plus explicit binding locations:

glsl
#version 450
layout(location = 0) in vec3 inColor;               // from the vertex shader's location 0
layout(location = 0) out vec4 outColor;             // color attachment 0
layout(set = 0, binding = 0) uniform Frame { float time; } frame;   // descriptor set 0, binding 0
layout(push_constant) uniform Push { vec4 tint; } push;

void main() {
    outColor = vec4(inColor * push.tint.rgb * (0.75 + 0.25 * sin(frame.time)), 1.0);
}

Pipeline layout and graphics pipeline

The pipeline layout declares what resources the shaders can see: descriptor set layouts (uniform buffers, textures, storage buffers) and push constant ranges (a few bytes set directly in the command buffer, ideal for per-draw data such as a model matrix).

The graphics pipeline bakes everything else: shader stages, vertex input layout, primitive topology, rasterizer state (culling, polygon mode), multisampling, depth/stencil tests, blending, and the attachment formats. Changing any of it means a different pipeline object, which is why engines build pipelines up front or cache them; creating one at draw time causes the infamous shader compilation stutter.

With dynamic rendering (core in Vulkan 1.3), the pipeline only needs the attachment formats, given in a VkPipelineRenderingCreateInfo chained into pNext. Older code instead creates a VkRenderPass object and VkFramebuffers and passes the render pass here; vulkan-tutorial.com teaches that path first, and both are valid.

cpp
VkPushConstantRange push{VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(float) * 4};
VkPipelineLayoutCreateInfo plci{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
plci.setLayoutCount = 1;
plci.pSetLayouts = &frameSetLayout;
plci.pushConstantRangeCount = 1;
plci.pPushConstantRanges = &push;
vkCreatePipelineLayout(device, &plci, nullptr, &pipelineLayout);

VkFormat colorFormat = VK_FORMAT_B8G8R8A8_SRGB;
VkPipelineRenderingCreateInfo rendering{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO};
rendering.colorAttachmentCount = 1;
rendering.pColorAttachmentFormats = &colorFormat;
rendering.depthAttachmentFormat = VK_FORMAT_D32_SFLOAT;

VkDynamicState dyn[] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};  // set per frame, survives resize
VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO};
dynamic.dynamicStateCount = 2;
dynamic.pDynamicStates = dyn;

VkGraphicsPipelineCreateInfo gp{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO};
gp.pNext = &rendering;                 // dynamic rendering: no VkRenderPass
gp.stageCount = 2;
gp.pStages = stages;                   // vertex + fragment VkPipelineShaderStageCreateInfo
gp.pVertexInputState = &vertexInput;
gp.pInputAssemblyState = &inputAssembly;   // VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST
gp.pViewportState = &viewportState;
gp.pRasterizationState = &raster;          // cull mode, front face, polygon mode
gp.pMultisampleState = &multisample;
gp.pDepthStencilState = &depthStencil;
gp.pColorBlendState = &colorBlend;
gp.pDynamicState = &dynamic;
gp.layout = pipelineLayout;
gp.renderPass = VK_NULL_HANDLE;
vkCreateGraphicsPipelines(device, pipelineCache, 1, &gp, nullptr, &pipeline);

A VkPipelineCache (saved to disk between runs) lets the driver skip recompiling pipelines it has seen before.

Command buffers

Work is recorded into command buffers allocated from a command pool (one pool per thread and per frame in flight is the usual setup), then submitted to a queue. Recording does nothing on the GPU.

cpp
vkResetCommandBuffer(cmd, 0);
VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(cmd, &begin);

transitionImage(cmd, swapImage, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);

VkRenderingAttachmentInfo color{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO};
color.imageView = swapImageView;
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.05f, 0.08f, 1.0f}};

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

vkCmdBeginRendering(cmd, &ri);
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
vkCmdSetViewport(cmd, 0, 1, &viewport);
vkCmdSetScissor(cmd, 0, 1, &scissor);
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &frameSet, 0, nullptr);
vkCmdPushConstants(cmd, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(tint), &tint);
vkCmdDraw(cmd, 3, 1, 0, 0);                         // 3 vertices, 1 instance
vkCmdEndRendering(cmd);

transitionImage(cmd, swapImage, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
vkEndCommandBuffer(cmd);

Synchronization

The GPU runs asynchronously and in parallel with itself, so you must describe the order. Vulkan has three tools:

Tool Orders Example
Pipeline barrier commands within a queue; also changes an image's layout "finish writing the shadow map before sampling it"
Semaphore GPU ↔ GPU, between queue operations "render after the swapchain image is acquired; present after rendering"
Fence GPU → CPU "the CPU may reuse frame 0's command buffer once the GPU signals this"

Images have layouts (optimal memory arrangements for a use): UNDEFINED, COLOR_ATTACHMENT_OPTIMAL, SHADER_READ_ONLY_OPTIMAL, TRANSFER_DST_OPTIMAL, PRESENT_SRC_KHR, and others. A barrier moves an image between them. With synchronization2 (core in 1.3), the transitionImage helper used above looks like this:

cpp
void transitionImage(VkCommandBuffer cmd, VkImage image, VkImageLayout from, VkImageLayout to) {
    VkImageMemoryBarrier2 b{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2};
    b.srcStageMask = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT;   // wait for this stage...
    b.srcAccessMask = VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT;          // ...and make these writes visible
    b.dstStageMask = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT;   // before this stage...
    b.dstAccessMask = VK_ACCESS_2_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT;
    b.oldLayout = from;
    b.newLayout = to;
    b.image = image;
    b.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};

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

(These masks fit the two transitions in this lesson's frame; a general helper picks stages and access masks per layout. Using ALL_COMMANDS everywhere is correct but slow.)

The frame loop and frames in flight

cpp
FrameData& f = frames[frameIndex];                            // per-frame: fence, semaphore, cmd buffer
vkWaitForFences(device, 1, &f.inFlight, VK_TRUE, UINT64_MAX);  // CPU waits until this slot is free

uint32_t imageIndex;
VkResult r = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, f.imageAvailable, VK_NULL_HANDLE, &imageIndex);
if (r == VK_ERROR_OUT_OF_DATE_KHR) { recreateSwapchain(); return; }
vkResetFences(device, 1, &f.inFlight);                        // reset only once we will submit

record(f.cmd, imageIndex);

VkSemaphoreSubmitInfo wait{VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO};
wait.semaphore = f.imageAvailable;
wait.stageMask = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT;   // only color output waits for the image
VkSemaphoreSubmitInfo signal{VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO};
signal.semaphore = renderFinished[imageIndex];                       // one per swapchain image
signal.stageMask = VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT;
VkCommandBufferSubmitInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_SUBMIT_INFO};
cbi.commandBuffer = f.cmd;

VkSubmitInfo2 submit{VK_STRUCTURE_TYPE_SUBMIT_INFO_2};
submit.waitSemaphoreInfoCount = 1;   submit.pWaitSemaphoreInfos = &wait;
submit.commandBufferInfoCount = 1;   submit.pCommandBufferInfos = &cbi;
submit.signalSemaphoreInfoCount = 1; submit.pSignalSemaphoreInfos = &signal;
vkQueueSubmit2(graphicsQueue, 1, &submit, f.inFlight);        // the fence signals when the GPU is done

VkPresentInfoKHR present{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR};
present.waitSemaphoreCount = 1;
present.pWaitSemaphores = &renderFinished[imageIndex];
present.swapchainCount = 1;
present.pSwapchains = &swapchain;
present.pImageIndices = &imageIndex;
vkQueuePresentKHR(graphicsQueue, &present);

frameIndex = (frameIndex + 1) % MAX_FRAMES_IN_FLIGHT;

The "render finished" semaphore is indexed by swapchain image, not by frame slot: presentation may still hold it when the same frame slot comes around again, and recent validation layers warn about reusing it too early.

Why frames in flight? With one set of per-frame resources, the CPU must wait for the GPU to finish frame N before recording frame N+1, so the two never work at the same time. With two sets, the CPU records the next frame while the GPU draws the current one. This model simulates the fence waits with 4 ms of CPU work and 10 ms of GPU work per frame:

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <vector>

void simulate(int framesInFlight, int frames, double cpuWork, double gpuWork) {
    std::vector<double> fenceDone(framesInFlight, 0.0);   // when each slot's last submit finished on the GPU
    double cpuTime = 0, gpuFree = 0, gpuEnd = 0;
    std::printf("frames in flight = %d\n", framesInFlight);
    for (int f = 0; f < frames; f++) {
        int slot = f % framesInFlight;
        double waitUntil = std::max(cpuTime, fenceDone[slot]);   // vkWaitForFences
        double waited = waitUntil - cpuTime;
        double cpuEnd = waitUntil + cpuWork;                      // record + submit
        double gpuStart = std::max(cpuEnd, gpuFree);
        gpuEnd = gpuStart + gpuWork;
        gpuFree = gpuEnd;
        fenceDone[slot] = gpuEnd;
        cpuTime = cpuEnd;
        std::printf("  frame %d: slot %d, CPU waited %4.1f ms, GPU %5.1f-%5.1f ms\n", f, slot, waited, gpuStart, gpuEnd);
    }
    std::printf("  %d frames done at %.1f ms (%.1f ms per frame)\n", frames, gpuEnd, gpuEnd / frames);
}

int main() {
    simulate(1, 4, 4.0, 10.0);
    simulate(2, 4, 4.0, 10.0);
}
frames in flight = 1
  frame 0: slot 0, CPU waited  0.0 ms, GPU   4.0- 14.0 ms
  frame 1: slot 0, CPU waited 10.0 ms, GPU  18.0- 28.0 ms
  frame 2: slot 0, CPU waited 10.0 ms, GPU  32.0- 42.0 ms
  frame 3: slot 0, CPU waited 10.0 ms, GPU  46.0- 56.0 ms
  4 frames done at 56.0 ms (14.0 ms per frame)
frames in flight = 2
  frame 0: slot 0, CPU waited  0.0 ms, GPU   4.0- 14.0 ms
  frame 1: slot 1, CPU waited  0.0 ms, GPU  14.0- 24.0 ms
  frame 2: slot 0, CPU waited  6.0 ms, GPU  24.0- 34.0 ms
  frame 3: slot 1, CPU waited  6.0 ms, GPU  34.0- 44.0 ms
  4 frames done at 44.0 ms (11.0 ms per frame)

With one frame in flight the GPU idles 4 ms every frame waiting for the CPU (14 ms per frame); with two, the GPU runs back to back and the frame time approaches the GPU's 10 ms. Two is the usual choice: more frames in flight add input latency and memory, for little gain.

Everything that changes per frame (uniform buffers, descriptor sets, command buffers) must exist once per frame in flight, or the CPU overwrites data the GPU is still reading.

Memory

A GPU exposes memory heaps (device-local VRAM, system RAM) and memory types with property flags: DEVICE_LOCAL (fast for the GPU), HOST_VISIBLE (the CPU can map it), HOST_COHERENT (no manual flushes). The raw sequence is: create a buffer, query vkGetBufferMemoryRequirements, pick a memory type, vkAllocateMemory, vkBindBufferMemory. Drivers limit the number of allocations (maxMemoryAllocationCount, often 4096), so real engines sub-allocate from large blocks. That is exactly what VMA does:

cpp
#define VMA_IMPLEMENTATION          // in exactly one .cpp file
#include "vk_mem_alloc.h"

VmaAllocatorCreateInfo aci{};
aci.vulkanApiVersion = VK_API_VERSION_1_3;
aci.physicalDevice = gpu;
aci.device = device;
aci.instance = instance;
VmaAllocator allocator;
vmaCreateAllocator(&aci, &allocator);

// A vertex buffer the GPU reads, which the CPU writes once (sequentially) through a mapped pointer
VkBufferCreateInfo bci{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
bci.size = sizeof(vertices);
bci.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;

VmaAllocationCreateInfo aci2{};
aci2.usage = VMA_MEMORY_USAGE_AUTO;
aci2.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT;

VkBuffer vbo;
VmaAllocation vboAlloc;
VmaAllocationInfo info;
vmaCreateBuffer(allocator, &bci, &aci2, &vbo, &vboAlloc, &info);
std::memcpy(info.pMappedData, vertices, sizeof(vertices));
// ...
vmaDestroyBuffer(allocator, vbo, vboAlloc);

For large static data (meshes, textures), the classic pattern is a staging buffer: copy into a host-visible buffer, then vkCmdCopyBuffer / vkCmdCopyBufferToImage into device-local memory, with a barrier before the first use.

Where to go next

Test yourself

What does a VkFence synchronize?

  1. Two queue submissions on the GPU
  2. The GPU with the CPU: the CPU waits until submitted work is finished
  3. Two draw calls in one command buffer
  4. Swapchain presentation with vsync

With dynamic rendering (Vulkan 1.3), what replaces the VkRenderPass in pipeline creation?

  1. Nothing is needed
  2. A VkPipelineRenderingCreateInfo with the attachment formats, chained into pNext
  3. A VkFramebuffer
  4. A descriptor set

Why use two frames in flight instead of one?

  1. To render at double resolution
  2. So the CPU records the next frame while the GPU draws the current one
  3. Because the swapchain needs two images
  4. To avoid creating pipelines