Adding User Interaction and Productivity Tools
local graph
Chapter 4 — Adding User Interaction and Productivity Tools
Section titled “Chapter 4 — Adding User Interaction and Productivity Tools”In this chapter, we will learn how to implement basic helpers to drastically simplify the debugging of graphical applications. The demos are implemented in Vulkan using all the material from the previous three chapters. In Chapter 3, we demonstrated how to wrap various instances of raw Vulkan code to create and maintain basic Vulkan state and objects. In this chapter, we will show how to start implementing Vulkan rendering code in a way that is easily extensible and adaptable for different applications. Beginning with 2D user-interface rendering is the best way to learn this, as it makes things easier and allows us to focus on the rendering code without being overwhelmed by complex 3D graphics algorithms.
We will cover the following recipes:
- Rendering ImGui user interfaces
- Integrating Tracy into C++ applications
- Using Tracy GPU profiling
- Adding a frames-per-second counter
- Using cube map textures in Vulkan
- Working with a 3D camera and basic user interaction
- Adding camera animations and motion
- Implementing an immediate-mode 3D drawing canvas
- Rendering on-screen graphs with ImGui and ImPlot
- Putting it all together into a Vulkan application
Technical requirements
Section titled “Technical requirements”To run code from this chapter on your Linux or Windows PC, you will need a GPU with recent drivers that support Vulkan 1.3. The source code used in this chapter can be downloaded from https://github.com/PacktPublishing/3D-Graphics-Rendering-Cookbook-Second-Edition/.
Rendering ImGui user interfaces
Section titled “Rendering ImGui user interfaces”ImGui is a popular bloat-free graphical user interface library for C++ and is essential to the interactive debugging of graphics apps. ImGui integration comes as a part of the LightweightVK library. In this recipe, we go step by step through the code and show how to create an example app with ImGui rendering.
Getting ready
Section titled “Getting ready”It is recommended to revisit the Using Vulkan descriptor indexing recipe from Chapter 3, and also recall the Vulkan basics described in the other recipes of that chapter.
This recipe covers the source code of lightweight/lvk/HelpersImGui.cpp. The demo code for this recipe is in Chapter04/01_ImGui.
How to do it…
Section titled “How to do it…”Let us start with a minimalistic ImGui demo application and take a look at how to use the ImGui Vulkan wrapper provided by LightweightVK:
-
First, we create an
lvk::ImGuiRendererobject. It takes in a pointer to ourlvk::IContext, the name of the default font, and the default font size in pixels.ImGuiRendererwill take care of all the low-level ImGui initialization and code:unique_ptr<lvk::ImGuiRenderer> imgui =std::make_unique<lvk::ImGuiRenderer>(*ctx, "data/OpenSans-Light.ttf", 30.0f); -
Let us create some GLFW callbacks that pass mouse movements and button presses into ImGui. GLFW mouse button IDs should be converted into ImGui ones:
glfwSetCursorPosCallback(window,{ImGui::GetIO().MousePos = ImVec2(x, y);});glfwSetMouseButtonCallback(window,{double xpos, ypos;glfwGetCursorPos(window, &xpos, &ypos);const ImGuiMouseButton_ imguiButton =(button==GLFW_MOUSE_BUTTON_LEFT) ?ImGuiMouseButton_Left : (button == GLFW_MOUSE_BUTTON_RIGHT ?ImGuiMouseButton_Right :ImGuiMouseButton_Middle);ImGuiIO& io = ImGui::GetIO();io.MousePos = ImVec2((float)xpos, (float)ypos);io.MouseDown[imguiButton] = action == GLFW_PRESS;}); -
Inside our typical rendering loop, we can invoke ImGui rendering commands as follows. The
ImGuiRenderer::beginFrame()method takes in anlvk::Framebufferobject so it can set up a rendering pipeline properly:ICommandBuffer& buf = ctx->acquireCommandBuffer();const lvk::Framebuffer framebuffer = {.color = {{ .texture = ctx->getCurrentSwapchainTexture() }}};buf.cmdBeginRendering({ .color = { {.loadOp = lvk::LoadOp_Clear,.clearColor = {1.0f, 1.0f, 1.0f, 1.0f} } } },framebuffer);imgui->beginFrame(framebuffer); -
Let’s draw an ImGui window with a texture. A texture index is passed into ImGui as an
ImTextureIDvalue so it can be used with the bindless rendering scheme we discussed in the previous chapter in the Using Vulkan descriptor sets recipe:ImGui::Begin("Texture Viewer", nullptr,ImGuiWindowFlags_AlwaysAutoResize);ImGui::Image(texture.index(), ImVec2(512, 512));ImGui::ShowDemoWindow();ImGui::End(); -
The
ImGuiRenderer::endFrame()method is a command buffer with actual Vulkan commands to render the user interface. Then we can callcmdEndRendering()and submit our command buffer:imgui->endFrame(buf);buf.cmdEndRendering();ctx->submit(buf, ctx->getCurrentSwapchainTexture());
This demo application should render a simple ImGui interface like that shown in the following screenshot:

Figure 4.1: ImGui rendering
Now let’s take a look at the underlying low-level implementation inside LightweightVK that renders ImGui data.
How it works…
Section titled “How it works…”The lvk::ImGuiRenderer helper class is declared in lvk\HelpersImGui.h. Here is its declaration.
- The constructor accepts a reference to
lvk::IContext, the name of the default.ttffont file, and the default font size in pixels. TheupdateFont()method can be invoked at a later point to override the previously used font. This method gets called from the constructor to set the default font:class ImGuiRenderer {public:explicit ImGuiRenderer(lvk::IContext& ctx,const char* defaultFontTTF = nullptr,float fontSizePixels = 24.0f);~ImGuiRenderer();void updateFont(const char* defaultFontTTF, float fontSizePixels); - The
beginFrame()andendFrame()methods are necessary to prepare ImGui for rendering and generate Vulkan commands from the ImGui draw data. ThesetDisplayScale()method can be used to override ImGui’sDisplayFramebufferScalefactor:void beginFrame(const lvk::Framebuffer& desc);void endFrame(lvk::ICommandBuffer& cmdBuffer);void setDisplayScale(float displayScale); - The private section of the
lvk::ImGuiRendererclass contains a method to create a new rendering pipeline and a bunch of data necessary for rendering. There’s a single set of vertex and fragment shaders, a rendering pipeline, and a texture created from the.ttffont file we provided at construction time:private:Holder<RenderPipelineHandle> createNewPipelineState(const lvk::Framebuffer& desc);private:lvk::IContext& ctx_;Holder<ShaderModuleHandle> vert_;Holder<ShaderModuleHandle> frag_;Holder<RenderPipelineHandle> pipeline_;Holder<TextureHandle> fontTexture_;Holder<SamplerHandle> samplerClamp_;float displayScale_ = 1.0f;uint32_t frameIndex_ = 0; - To ensure stall-free operation, LightweightVK uses multiple buffers to pass ImGui vertex and index data into Vulkan (
vbandibin the following code, for the vertex and index buffers respectively):struct DrawableData {Holder<BufferHandle> vb_;Holder<BufferHandle> ib_;uint32_t numAllocatedIndices_ = 0;uint32_t numAllocatedVerteices_ = 0;};static constexpr uint32_t kNumSwapchainImages = 3;DrawableData drawables_[kNumSwapchainImages] = {};};
Now we can dive into the implementation, which resides in lvk/HelpersImGui.cpp.
he vertex shader uses programmable-vertex pulling, which we briefly touched on in the previous chapter in the Dealing with buffers in Vulkan recipe. Let’s take a closer look at it.
- ImGui provides 2D screen coordinates for each vertex, 2D texture coordinates, and an RGBA color. We declare a
Vertexstructure to hold per-vertex data and store all vertices inside thevertices[]array residing insideVertexBuffer. Thebuffer_referenceGLSL layout qualifier declares a type and not an instance of a buffer, so that a reference to that buffer can be passed into the shader at a later point:layout (location = 0) out vec4 out_color;layout (location = 1) out vec2 out_uv;layout (location = 2) out flat uint out_textureId;struct Vertex {float x, y;float u, v;uint rgba;};layout(std430, buffer_reference) readonly buffer VertexBuffer {Vertex vertices[];}; - A reference to
VertexBuffercontaining our per-vertex data is passed via Vulkan push constants. Besides that, we pass a texture ID and some 2D viewport parameters represented as left, right, top, and bottom planes insidevec4 LRTB:layout(push_constant) uniform PushConstants {vec4 LRTB;VertexBuffer vb;uint textureId;} pc;void main() {float L = pc.LRTB.x;float R = pc.LRTB.y;float T = pc.LRTB.z;float B = pc.LRTB.w;
Once we have the viewport parameters, we can construct an orthographic projection matrix the following way, which is similar to how glm::ortho() creates a projection matrix:
mat4 proj = mat4( 2.0 / (R-L), 0.0, 0.0, 0.0, 0.0, 2.0 / (T-B), 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, (R+L) / (L-R), (T+B) / (B-T), 0.0, 1.0);- The current vertex is extracted from the
VertexBuffer::verticesarray using thegl_VertexIndexbuilt-in GLSL variable. The RGBA vertex colorv.rgbais packed into a 32-bit unsigned integer and can be unpacked intovec4using theunpackUnorm4x8()GLSL built-in function:Vertex v = pc.vb.vertices[gl_VertexIndex];out_color = unpackUnorm4x8(v.rgba); - The texture coordinates and texture ID are passed into the fragment shader unchanged. The projection matrix is multiplied by the vertex position expanded into
vec4by adding0as theZcomponent:out_uv = vec2(v.u, v.v);out_textureId = pc.textureId;gl_Position = proj * vec4(v.x, v.y, 0, 1);}
A corresponding GLSL fragment shader is much simpler and looks as follows:
- The input locations should match the corresponding output locations from the vertex shader:
layout (location = 0) in vec4 in_color;layout (location = 1) in vec2 in_uv;layout (location = 2) in flat uint in_textureId;layout (location = 0) out vec4 out_color;
- LightweightVK supports some basic sRGB framebuffer rendering. This shader constant is used to enable some rudimentary tone mapping. The texture ID is used to access a required bindless texture. The sampler is always a default sampler at index
0. Theconstant_idGLSL modifier is used to specify specialization constants for Vulkan:layout (constant_id = 0) const bool kNonLinearColorSpace = false;void main() {vec4 c = in_color * texture(sampler2D(kTextures2D[in_textureId], kSamplers[0]), in_uv); - Here we can render our UI in linear color space into an sRGB framebuffer:
out_color = kNonLinearColorSpace ?vec4(pow(c.rgb, vec3(2.2)), c.a) : c;}
Now let’s take a look at the C++ code in the lvk::ImGuiRender implementation. There’s a private ImGuiRenderer::createNewPipelineState() helper function there, which is responsible for creating a new rendering pipeline for ImGui rendering. As the entire relevant Vulkan state can be dynamic in Vulkan 1.3, a single immutable pipeline is sufficient.
- A framebuffer description is required to create a pipeline because we need information about color and depth attachment formats:
Holder<RenderPipelineHandle>ImGuiRenderer::createNewPipelineState(const lvk::Framebuffer& desc){const uint32_t nonLinearColorSpace =ctx_.getSwapChainColorSpace() == ColorSpace_SRGB_NONLINEAR ? 1:0;return ctx_.createRenderPipeline({.smVert = vert_,.smFrag = frag_,
- The sRGB mode is enabled based on the swapchain color space and passed into the shaders as Vulkan specialization constants:
.specInfo = {.entries = {{.constantId = 0,.size = sizeof(nonLinearColorSpace)}},.data = &nonLinearColorSpace,.dataSize = sizeof(nonLinearColorSpace) },
- All ImGui elements require alpha blending to be enabled. If a depth buffer is present, it is retained unchanged but the rendering pipeline should know about it:
.color = {{.format = ctx_.getFormat(desc.color[0].texture),.blendEnabled = true,.srcRGBBlendFactor = lvk::BlendFactor_SrcAlpha,.dstRGBBlendFactor = lvk::BlendFactor_OneMinusSrcAlpha,}},.depthFormat = desc.depthStencil.texture ?ctx_.getFormat(desc.depthStencil.texture) : lvk::Format_Invalid,.cullMode = lvk::CullMode_None},nullptr);}
Another helper function ImGuiRenderer::updateFont() is called from the constructor. Here’s how it is implemented.
- First, it sets up ImGui font configuration parameters using the provided font size:
void ImGuiRenderer::updateFont(const char* defaultFontTTF, float fontSizePixels){ImGuiIO& io = ImGui::GetIO();ImFontConfig cfg = ImFontConfig();cfg.FontDataOwnedByAtlas = false;cfg.RasterizerMultiply = 1.5f;cfg.SizePixels = ceilf(fontSizePixels);cfg.PixelSnapH = true;cfg.OversampleH = 4;cfg.OversampleV = 4;ImFont* font = nullptr;
- Then it loads the default font from a
.ttffile:if (defaultFontTTF) {font = io.Fonts->AddFontFromFileTTF(defaultFontTTF, cfg.SizePixels, &cfg);}io.Fonts->Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight; - Last but not least, the rasterized TrueType font data is retrieved from ImGui and stored as a LightweightVK texture. This font texture is used later for rendering via its index ID:
unsigned char* pixels;int width, height;io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);fontTexture_ = ctx_.createTexture({.type = lvk::TextureType_2D,.format = lvk::Format_RGBA_UN8,.dimensions = {(uint32_t)width, (uint32_t)height},.usage = lvk::TextureUsageBits_Sampled,.data = pixels }, nullptr);io.Fonts->TexID = fontTexture_.index();io.FontDefault = font;}
All the preparations are completed and we can now look at the constructor and destructor of ImGuiRenderer. Both member functions are very short.
- The constructor initializes both ImGui and ImPlot contexts in case LightweightVK was compiled with optional ImPlot support. At the moment, LightweightVK supports only a single ImGui context:
ImGuiRenderer::ImGuiRenderer(lvk::IContext& device,const char* defaultFontTTF,float fontSizePixels): ctx_(device){ImGui::CreateContext();#if defined(LVK_WITH_IMPLOT)ImPlot::CreateContext();#endif // LVK_WITH_IMPLOT
- Here we set the
ImGuiBackendFlags_RendererHasVtxOffsetflag telling ImGui that our renderer has support for vertex offsets. It enables the output of large meshes while still using 16-bit indices, making UI rendering more efficient:ImGuiIO& io = ImGui::GetIO();io.BackendRendererName = "imgui-lvk";io.BackendFlags |=ImGuiBackendFlags_RendererHasVtxOffset; - All the work to create the default font and shaders is delegated as we have just discussed:
updateFont(defaultFontTTF, fontSizePixels);vert_ = ctx_.createShaderModule({codeVS, Stage_Vert,"Shader Module: imgui (vert)"});frag_ = ctx_.createShaderModule({codeFS, Stage_Frag,"Shader Module: imgui (frag)"});samplerClamp_ = ctx_.createSampler({.wrapU = lvk::SamplerWrap_Clamp,.wrapV = lvk::SamplerWrap_Clamp,.wrapW = lvk::SamplerWrap_Clamp,});}
- The destructor is trivial and cleans up both ImGui and the optional ImPlot:
ImGuiRenderer::~ImGuiRenderer() {ImGuiIO& io = ImGui::GetIO();io.Fonts->TexID = nullptr;#if defined(LVK_WITH_IMPLOT)ImPlot::DestroyContext();#endif // LVK_WITH_IMPLOTImGui::DestroyContext();}
There’s one more simple function that we want to see before going on to the rendering: ImGuiRenderer::beginFrame(). It starts a new ImGui frame using the provided framebuffer. A graphics pipeline is lazily created here based on the actual framebuffer parameters because we did not have any framebuffer provided to us in the constructor:
void ImGuiRenderer::beginFrame( const lvk::Framebuffer& desc){ const lvk::Dimensions dim = ctx_.getDimensions(desc.color[0].texture); ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2(dim.width / displayScale_, dim.height / displayScale_); io.DisplayFramebufferScale = ImVec2(displayScale_, displayScale_); io.IniFilename = nullptr; if (pipeline_.empty()) { pipeline_ = createNewPipelineState(desc); } ImGui::NewFrame();}Now we are ready to tackle the UI rendering in the ImGuiRenderer::endFrame() function. This function runs every frame and populates a Vulkan command buffer. It is a bit more complicated, so let’s go over it step by step to see how it works. Error checking is omitted in the following code snippets for the sake of brevity.
- First, we should finalize ImGui frame rendering and retrieve the frame draw data:
void ImGuiRenderer::endFrame(lvk::ICommandBuffer& cmdBuffer) {ImGui::EndFrame();ImGui::Render();ImDrawData* dd = ImGui::GetDrawData();const float fb_width =dd->DisplaySize.x * dd->FramebufferScale.x;const float fb_height =dd->DisplaySize.y * dd->FramebufferScale.y;
- Let’s prepare the render state. We disable the depth test and depth buffer writes. A viewport is constructed based on the ImGui framebuffer size, which we set up earlier in
beginFrame()to be equal to our LightweightVK framebuffer size:cmdBuffer.cmdBindDepthState({});cmdBuffer.cmdBindViewport({.x = 0.0f,.y = 0.0f,.width = fb_width,.height = fb_height,}); - The parameters of the orthographic projection matrix are prepared here. They will be passed to shaders later via Vulkan push constants inside the rendering loop together with other parameters. Clipping parameters are prepared here as well to be used inside the rendering loop:
const float L = dd->DisplayPos.x;const float R = dd->DisplayPos.x + dd->DisplaySize.x;const float T = dd->DisplayPos.y;const float B = dd->DisplayPos.y + dd->DisplaySize.y;const ImVec2 clipOff = dd->DisplayPos;const ImVec2 clipScale = dd->FramebufferScale;
- We have a set of separate LVK buffers per each frame. These buffers store ImGui vertex and index data for the entire frame:
DrawableData& drawableData = drawables_[frameIndex_];frameIndex_ = (frameIndex_ + 1) % LVK_ARRAY_NUM_ELEMENTS(drawables_);
- If there are buffers already existing from the previous frames and these buffers’ sizes are insufficient to fit in the new vertex or index data, the buffers are re-created with the new size. The index buffer is created via
BufferUsageBits_Index:if (drawableData.numAllocatedIndices_ < dd->TotalIdxCount){drawableData.ib_ = ctx_.createBuffer({.usage = lvk::BufferUsageBits_Index,.storage = lvk::StorageType_HostVisible,.size = dd->TotalIdxCount * sizeof(ImDrawIdx),.debugName = "ImGui: drawableData.ib_",});drawableData.numAllocatedIndices_ = dd->TotalIdxCount;} - The buffer to store vertices is actually a
BufferUsageBits_Storagestorage buffer, because our GLSL shaders use programmable-vertex pulling to load the vertices:if (drawableData.numAllocatedVerteices_ < dd->TotalVtxCount){drawableData.vb_ = ctx_.createBuffer({.usage = lvk::BufferUsageBits_Storage,.storage = lvk::StorageType_HostVisible,.size = dd->TotalVtxCount * sizeof(ImDrawVert),.debugName = "ImGui: drawableData.vb_",});drawableData.numAllocatedVerteices_ = dd->TotalVtxCount;} - Let’s upload some data to the vertex and index buffers. The entire ImGui frame data is uploaded here. Offsets are carefully preserved so we know where every ImGui draw command data is stored:
ImDrawVert* vtx = (ImDrawVert*)ctx_.getMappedPtr(drawableData.vb_);uint16_t* idx = (uint16_t*)ctx_.getMappedPtr(drawableData.ib_);for (int n = 0; n < dd->CmdListsCount; n++) {const ImDrawList* cmdList = dd->CmdLists[n];memcpy(vtx, cmdList->VtxBuffer.Data,cmdList->VtxBuffer.Size * sizeof(ImDrawVert));memcpy(idx, cmdList->IdxBuffer.Data,cmdList->IdxBuffer.Size * sizeof(ImDrawIdx));vtx += cmdList->VtxBuffer.Size;idx += cmdList->IdxBuffer.Size;}
- The host-visible memory needs to be flushed. This will allow LightweightVK to issue a corresponding Vulkan
vkFlushMappedMemoryRanges()command if the memory is not host-coherent:ctx_.flushMappedMemory(drawableData.vb_, 0,dd->TotalVtxCount * sizeof(ImDrawVert));ctx_.flushMappedMemory(drawableData.ib_, 0,dd->TotalIdxCount * sizeof(ImDrawIdx)); - Let’s bind our index buffer and the rendering pipeline to a command buffer, and enter the rendering loop that iterates over all ImGui rendering commands:
uint32_t idxOffset = 0;uint32_t vtxOffset = 0;cmdBuffer.cmdBindIndexBuffer(drawableData.ib_, lvk::IndexFormat_UI16);cmdBuffer.cmdBindRenderPipeline(pipeline_);for (int n = 0; n < dd->CmdListsCount; n++) {const ImDrawList* cmdList = dd->CmdLists[n];for (int cmd_i = 0; cmd_i < cmdList->CmdBuffer.Size; cmd_i++) {const ImDrawCmd& cmd = cmdList->CmdBuffer[cmd_i];
- Viewport clipping is done right here on the CPU side. If the ImGui draw command is completely clipped, we should skip it:
ImVec2 clipMin((cmd.ClipRect.x - clipOff.x) * clipScale.x,(cmd.ClipRect.y - clipOff.y) * clipScale.y);ImVec2 clipMax((cmd.ClipRect.z - clipOff.x) * clipScale.x,(cmd.ClipRect.w - clipOff.y) * clipScale.y);if (clipMin.x < 0.0f) clipMin.x = 0.0f;if (clipMin.y < 0.0f) clipMin.y = 0.0f;if (clipMax.x > fb_width ) clipMax.x = fb_width;if (clipMax.y > fb_height) clipMax.y = fb_height;if (clipMax.x <= clipMin.x ||clipMax.y <= clipMin.y) continue;
- All the data necessary for rendering is passed into GLSL shaders via Vulkan push constants. It consists of the orthographic projection data, which is the left, right, top, and bottom planes, a reference to the vertex buffer, and a texture ID for bindless rendering:
struct VulkanImguiBindData {float LRTB[4];uint64_t vb = 0;uint32_t textureId = 0;uint32_t samplerId = 0;} bindData = {.LRTB = {L, R, T, B},.vb = ctx_.gpuAddress(drawableData.vb_),.textureId = static_cast<uint32_t>(cmd.TextureId),.samplerId = samplerClamp_.index(),};cmdBuffer.cmdPushConstants(bindData);
- Set up the scissor test so it can do precise clipping of ImGui elements:
cmdBuffer.cmdBindScissorRect({uint32_t(clipMin.x),uint32_t(clipMin.y),uint32_t(clipMax.x - clipMin.x),uint32_t(clipMax.y - clipMin.y)});
- The actual rendering is done via
cmdDrawIndexed(). Here we use both the index offset and vertex offset parameters to access the correct data in our large per-frame vertex and index buffers:cmdBuffer.cmdDrawIndexed(cmd.ElemCount, 1u,idxOffset + cmd.IdxOffset,int32_t(vtxOffset + cmd.VtxOffset));}idxOffset += cmdList->IdxBuffer.Size;vtxOffset += cmdList->VtxBuffer.Size;}}
Now we have done all the ImGui rendering and can render the entire ImGui user interface using Vulkan. Let’s jump to the next recipes and learn other productivity and debugging tools, such as profiling, 3D camera controls, frames-per-second counters, and a drawing canvas.
Integrating Tracy into C++ applications
Section titled “Integrating Tracy into C++ applications”In the previous chapter, Working with Vulkan Objects, we learned how to write small graphics applications with Vulkan and LightweightVK. In real-world applications, it is often necessary to be able to quickly get performance profiling information at runtime. In this recipe, we will show how to make use of the Tracy profiler in your 3D applications.
Getting ready
Section titled “Getting ready”The complete source code of the demo application for this recipe is located in Chapter04/02_TracyProfiler.
Make sure to download a precompiled Tracy client app for your platform from https://github.com/wolfpld/tracy. In our book, we use Tracy version 0.11.1.
How to do it…
Section titled “How to do it…”The Tracy profiler itself is integrated into the LightweightVK library. Our demo application, as well as many parts of the LightweightVK rendering code, is augmented with calls to profiling functions. Those calls are wrapped into a set of macros so as not to call Tracy directly. This allows turning the profiler on and off, and even switching to other profilers when necessary. Let’s take a look at the demo application and then explore the underlying low-level implementation:
- First, let’s take a look at the root LightweightVK CMake configuration file
deps/src/lightweightvk/CMakeLists.txtto see how the Tracy library is added to the project. At the beginning, we should see an option enabled by default:option(LVK_WITH_TRACY "Enable Tracy profiler" ON) - A few lines later in the same file, the CMake option is converted into a
TRACY_ENABLEC++ compiler macro definition and the Tracy library is added to the project. Note that this is thethird-party/deps/src/folder of the LightweightVK Git repository, which itself resides inside thedeps/src/folder of the book repository:if(LVK_WITH_TRACY)add_definitions("-DTRACY_ENABLE=1")add_subdirectory(third-party/deps/src/tracy)lvk_set_folder(TracyClient "third-party")endif() - Let’s continue scrolling the same file,
deps/src/lightweightvk/CMakeLitsts.txt, for a few pages further. Based on the previously enabledLVK_WITH_TRACYCMake option, we export theLVK_WITH_TRACYC++ macro definition to all users of LightweightVK. The Tracy library is linked with theLVKLibrarytarget so that every app using LightweightVK has access to Tracy functions as well:if(LVK_WITH_TRACY)target_compile_definitions(LVKLibrary PUBLIC "LVK_WITH_TRACY=1")target_link_libraries(LVKLibrary PUBLIC TracyClient)endif() - Now let’s look into
lightweightvk/lvk/LVK.hand check out some macro definitions. TheLVK_WITH_TRACYmacro is used to enable or disable Tracy usage. Some predefined RGB colors are declared as macros to be used to mark important point-of-interest operations:#if defined(LVK_WITH_TRACY)#include "tracy/Tracy.hpp"#define LVK_PROFILER_COLOR_WAIT 0xff0000#define LVK_PROFILER_COLOR_SUBMIT 0x0000ff#define LVK_PROFILER_COLOR_PRESENT 0x00ff00#define LVK_PROFILER_COLOR_CREATE 0xff6600#define LVK_PROFILER_COLOR_DESTROY 0xffa500#define LVK_PROFILER_COLOR_BARRIER 0xffffff - Other macros are mapped directly to Tracy functions so that we can work with Tracy zones in a non-intrusive way:
#define LVK_PROFILER_FUNCTION() ZoneScoped#define LVK_PROFILER_FUNCTION_COLOR(color) ZoneScopedC(color)#define LVK_PROFILER_ZONE(name, color) { \ZoneScopedC(color); \ZoneName(name, strlen(name))#define LVK_PROFILER_ZONE_END() }
- The
LVK_PROFILER_THREADmacro can be used to set the name of a C++ thread. TheLVK_PROFILER_FRAMEmacro is used to mark the start of the next frame during rendering. It is used by LightweightVK inlvk::VulkanSwapchain::present()and can be helpful if you want to implement your own swapchain management code, for example, on Android using OpenXR:#define LVK_PROFILER_THREAD(name) tracy::SetThreadName(name)#define LVK_PROFILER_FRAME(name) FrameMarkNamed(name) - Once Tracy is disabled, all macros are defined to no-ops and zones are defined as empty C++ scopes:
#else#define LVK_PROFILER_FUNCTION()#define LVK_PROFILER_FUNCTION_COLOR(color)#define LVK_PROFILER_ZONE(name, color) {#define LVK_PROFILER_ZONE_END() }#define LVK_PROFILER_THREAD(name)#define LVK_PROFILER_FRAME(name)#endif // LVK_WITH_TRACY
Macros LVK_PROFILER_FUNCTION and LVK_PROFILER_FUNCTION_COLOR are spread all over the LightweightVK code to give good profiling coverage. Let’s take a look at how to use them in our own apps.
How it works…
Section titled “How it works…”The demo application is located in Chapter04/02_TracyProfiler/src.main.cpp. Tracy is initialized automatically together with LightweightVK. All we have to do now is put corresponding macros in our code. Let’s take a look at how it works.
In our initialization part where we create lvk::IContext, we use LVK_PROFILER_ZONE and LVK_PROFILER_ZONE_END to mark an interesting fragment of our initialization code:
GLFWwindow* window = nullptr;unique_ptr<lvk::IContext> ctx;{ LVK_PROFILER_ZONE("Initialization", LVK_PROFILER_COLOR_CREATE); int width = -95; int height = -90; window = lvk::initWindow("Simple example", width, height); ctx = lvk::createVulkanContextWithSwapchain(window, width, height, {}); LVK_PROFILER_ZONE_END();}Inside the rendering loop, we can mark different point-of-interest code blocks the same way. The hex value is an RGB color that will be used by Tracy in the profiling window to highlight this profiling zone. Some predefined colors were mentioned earlier in this recipe:
lvk::ICommandBuffer& buf = ctx->acquireCommandBuffer();LVK_PROFILER_ZONE("Fill command buffer", 0xffffff);// …LVK_PROFILER_ZONE_END();If we need to mark the entire function and want to have an automatic name assigned to it, we should use the LVK_PROFILER_FUNCTION macro as in the following snippet. This macro does not require closing:
lvk::Result lvk::compileShader(VkDevice device, VkShaderStageFlagBits stage, const char* code, VkShaderModule* outShaderModule, const glslang_resource_t* glslLangResource){ LVK_PROFILER_FUNCTION(); //… return Result();}Let’s take a look at the profiler output while running this demo app. To retrieve the profiling data, you have to run a Tracy client and connect it to your graphics app. We use Tracy version 0.10, which can be downloaded from GitHub at https://github.com/wolfpld/tracy/releases/tag/v0.10. Here is a screenshot from a connected Tracy client showing a flame graph of our app.

Figure 4.2: Tracy user interface
This approach allows for fully transparent enabling and disabling of the Tracy profiler at build time. Adding other profilers, such as EasyProfiler and Optick, which provide similar APIs, is mostly trivial and can be easily implemented yourself as an exercise.
Using Tracy GPU profiling
Section titled “Using Tracy GPU profiling”Tracy includes a feature that uses Vulkan timestamps to obtain timing information for commands executed on the GPU. If the Vulkan extension VK_EXT_calibrated_timestamps is supported, the GPU timing data is synchronized to the same reference frame as the CPU timing. Let’s take a quick look at how to add Tracy GPU profiling to Vulkan within the VulkanContext.
Getting ready
Section titled “Getting ready”The corresponding C++ source code can be found in lvk/vulkan/VulkanClasses.cpp.
How to do it…
Section titled “How to do it…”Tracy GPU profiling can be integrated into existing Vulkan code as follows.
- First, include the
TracyVulkan.hppheader and define a helper macro to use within our rendering functions.#if defined(LVK_WITH_TRACY_GPU)#include "tracy/TracyVulkan.hpp"#define LVK_PROFILER_GPU_ZONE(name, ctx, cmdBuffer, color) \TracyVkZoneC(ctx->pimpl_->tracyVkCtx_, cmdBuffer, name, color);#else#define LVK_PROFILER_GPU_ZONE(name, ctx, cmdBuffer, color)#endif // LVK_WITH_TRACY_GPU - Add the necessary member fields for Tracy GPU to the
VulkanContextImplstructure.struct VulkanContextImpl final {// ...#if defined(LVK_WITH_TRACY_GPU)TracyVkCtx tracyVkCtx_ = nullptr;VkCommandPool tracyCommandPool_ = VK_NULL_HANDLE;VkCommandBuffer tracyCommandBuffer_ = VK_NULL_HANDLE;#endif // LVK_WITH_TRACY_GPU}; - Add the following initialization code to the
VulkanContext::initContext()function. This code checks the available Vulkan time domains and enables different Tracy GPU profiling features based on their availability. Notice how the C++ lambda is called directly in place, allowing thehasHostQueryvariable to be declared asconst.#if defined(LVK_WITH_TRACY_GPU)std::vector<VkTimeDomainEXT> timeDomains;if (hasCalibratedTimestamps_) {uint32_t numTimeDomains = 0;vkGetPhysicalDeviceCalibrateableTimeDomainsEXT(vkPhysicalDevice_, &numTimeDomains, nullptr));timeDomains.resize(numTimeDomains);vkGetPhysicalDeviceCalibrateableTimeDomainsEXT(vkPhysicalDevice_, &numTimeDomains, timeDomains.data()));}const bool hasHostQuery = vkFeatures12_.hostQueryReset &&[&timeDomains]() -> bool {for (VkTimeDomainEXT domain : timeDomains)if (domain == VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT ||domain == VK_TIME_DOMAIN_QUERY_PERFORMANCE_COUNTER_EXT)return true;return false;}(); - If host querying is supported, a dedicated command pool and command buffer are not required. Otherwise, we need to create them.
if (hasHostQuery) {pimpl_->tracyVkCtx_ = TracyVkContextHostCalibrated(vkPhysicalDevice_, vkDevice_, vkResetQueryPool,vkGetPhysicalDeviceCalibrateableTimeDomainsEXT,vkGetCalibratedTimestampsEXT);} else {const VkCommandPoolCreateInfo ciCommandPool = {.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT |VK_COMMAND_POOL_CREATE_TRANSIENT_BIT,.queueFamilyIndex = deviceQueues_.graphicsQueueFamilyIndex,};vkCreateCommandPool(vkDevice_,&ciCommandPool, nullptr, &pimpl_->tracyCommandPool_);lvk::setDebugObjectName(vkDevice_, VK_OBJECT_TYPE_COMMAND_POOL,(uint64_t)pimpl_->tracyCommandPool_,"Command Pool: VulkanContextImpl::tracyCommandPool_");const VkCommandBufferAllocateInfo aiCommandBuffer = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,.commandPool = pimpl_->tracyCommandPool_,.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,.commandBufferCount = 1,};vkAllocateCommandBuffers(vkDevice_, &aiCommandBuffer, &pimpl_->tracyCommandBuffer_);
- If calibrated timestamps are supported, Tracy uses a specialized code path for this scenario.
if (hasCalibratedTimestamps_) {pimpl_->tracyVkCtx_ = TracyVkContextCalibrated(vkPhysicalDevice_,vkDevice_,deviceQueues_.graphicsQueue,pimpl_->tracyCommandBuffer_,vkGetPhysicalDeviceCalibrateableTimeDomainsEXT,vkGetCalibratedTimestampsEXT);} else {pimpl_->tracyVkCtx_ = TracyVkContext(vkPhysicalDevice_,vkDevice_,deviceQueues_.graphicsQueue,pimpl_->tracyCommandBuffer_);};}LVK_ASSERT(pimpl_->tracyVkCtx_);#endif // LVK_WITH_TRACY_GPU
- Add the destruction code at the very beginning of the
VulkanContext::~VulkanContext()class destructor.lvk::VulkanContext::~VulkanContext() {LVK_PROFILER_FUNCTION();VK_ASSERT(vkDeviceWaitIdle(vkDevice_));#if defined(LVK_WITH_TRACY_GPU)TracyVkDestroy(pimpl_->tracyVkCtx_);if (pimpl_->tracyCommandPool_) {vkDestroyCommandPool(vkDevice_, pimpl_->tracyCommandPool_, nullptr);}#endif // LVK_WITH_TRACY_GPU// ...} - The final scaffolding step occurs in the
VulkanContext::submit()function. We should collect the GPU sampling information using theTracyVkCollect()function before submitting the next command buffer, as shown below:lvk::SubmitHandle lvk::VulkanContext::submit(lvk::ICommandBuffer& commandBuffer, TextureHandle present){LVK_PROFILER_FUNCTION();CommandBuffer* vkCmdBuffer =static_cast<CommandBuffer*>(&commandBuffer);#if defined(LVK_WITH_TRACY_GPU)TracyVkCollect(pimpl_->tracyVkCtx_, vkCmdBuffer->wrapper_->cmdBuf_);#endif // LVK_WITH_TRACY_GPU// ...}
Now we are ready to do Vulkan GPU profiling with Tracy.
How it works…
Section titled “How it works…”The actual GPU profiling takes place inside the CommandBuffer functions, where we can now use the LVK_PROFILER_GPU_ZONE() macro we defined earlier. For example, here’s how some of the functions will look:
void lvk::CommandBuffer::cmdDraw(uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t baseInstance){ LVK_PROFILER_FUNCTION(); LVK_PROFILER_GPU_ZONE( "cmdDraw()", ctx_, wrapper_->cmdBuf_, LVK_PROFILER_COLOR_CMD_DRAW); if (vertexCount == 0) return; vkCmdDraw(wrapper_->cmdBuf_, vertexCount, instanceCount, firstVertex, baseInstance);}void lvk::CommandBuffer::cmdDispatchThreadGroups( const Dimensions& threadgroupCount, const Dependencies& deps){ LVK_PROFILER_FUNCTION(); LVK_PROFILER_GPU_ZONE("cmdDispatchThreadGroups()", ctx_, wrapper_->cmdBuf_, LVK_PROFILER_COLOR_CMD_DISPATCH); // ...}Before returning to Vulkan rendering, let’s explore yet another small but useful profiling trick and learn how to implement a simple yet good frames-per-second counter.
Adding a frames-per-second counter
Section titled “Adding a frames-per-second counter”The frames-per-second (FPS) counter is the cornerstone of all graphical applications profiling and performance measurements. In this recipe, we will learn how to implement a simple FPS counter class and use it to roughly measure the performance of our applications.
Getting ready
Section titled “Getting ready”The source code for this recipe can be found in Chapter04/03_FPS. The FramesPerSecondCounter class is located in shared/UtilsFPS.h.
How to do it…
Section titled “How to do it…”Let’s implement the FramesPerSecondCounter class containing all the machinery required to calculate the average FPS for a given time interval:
- First, we need some member fields to store the duration of a sliding window, the number of frames rendered in the current interval, and the accumulated time of this interval. The
printFPS_Boolean field can be used to enable or disable FPS printing to the console:class FramesPerSecondCounter {public:float avgInterval_ = 0.5f;unsigned int numFrames_ = 0;double accumulatedTime_ = 0;float currentFPS_ = 0.0f;bool printFPS_ = true; - A single explicit constructor can override the averaging interval’s default duration:
public:explicit FramesPerSecondCounter(float avgInterval = 0.5f): avgInterval_(avgInterval){ assert(avgInterval > 0.0f); }
- The
tick()method should be called from the main loop. It accepts the time duration elapsed since the previous call and a Boolean flag, which should be set totrueif a new frame has been rendered during this iteration. This flag is a convenience feature to handle situations where frame rendering can be skipped in the main loop for various reasons, such as simulation pausing. The time accumulates until it reaches the value ofavgInterval_:bool tick(float deltaSeconds, bool frameRendered = true){if (frameRendered) numFrames_++;accumulatedTime_ += deltaSeconds; - Once enough time has accumulated, we can do averaging, update the current FPS value, and print debug info to the console. We should reset the number of frames and accumulated time at this point:
if (accumulatedTime_ > avgInterval_) {currentFPS_ = static_cast<float>(numFrames_ / accumulatedTime_);if (printFPS_)printf("FPS: %.1f\n", currentFPS_);numFrames_ = 0;accumulatedTime_ = 0;return true;}return false;}
- Let’s add a helper method to retrieve the current FPS value:
inline float getFPS() const{ return currentFPS_; }};
Now, let’s take a look at how to use this class in our main loop. Let’s augment the main loop of our demo applications to display an FPS counter in the console:
- First, let us define a
FramesPerSecondCounterobject and a couple of variables to store the current timestamp and the delta since the last rendered frame. We have chosen to use an ad hoc 0.5-second averaging interval; feel free to experiment with different values:double timeStamp = glfwGetTime();float deltaSeconds = 0.0f;FramesPerSecondCounter fpsCounter(0.5f); - Within the main loop, update the current timestamp and calculate the frame duration by finding a delta between two consecutive timestamps. Then, pass this calculated delta to the
tick()method:while (!glfwWindowShouldClose(window)) {fpsCounter.tick(deltaSeconds);const double newTimeStamp = glfwGetTime();deltaSeconds = static_cast<float>(newTimeStamp - timeStamp);timeStamp = newTimeStamp;// ...do the rest of your rendering here...}
The console output of the running application should look similar to the following. Vertical sync is turned off:
FPS: 3924.7FPS: 4322.4FPS: 4458.9FPS: 4445.1FPS: 4581.4The application window should look like that shown in the following screenshot, with an FPS counter rendered in the top-right corner:

Figure 4.3: ImGui and ImPlot user interfaces with an FPS counter
Let’s check the source code to learn how to add this ImGui FPS widget to your app. Here’s a fragment that fills in a command buffer:
- We set up the framebuffer parameters and start rendering. ImGui rendering is started with
imgui->beginFrame()as we learned in the Rendering ImGui user interface recipe:lvk::ICommandBuffer& buf = ctx->acquireCommandBuffer();const lvk::Framebuffer framebuffer = { .color = { {.texture = ctx->getCurrentSwapchainTexture() } } };buf.cmdBeginRendering({ .color = { { .loadOp = lvk::LoadOp_Clear,.clearColor = { 1.0f, 1.0f, 1.0f, 1.0f } } } },framebuffer);imgui->beginFrame(framebuffer); - We get the current viewport parameters from ImGui and set the position of the next ImGui window to be aligned close to the top-right corner of the viewport work area. Sizes are hardcoded to be in the app window’s pixels. The
ImGuiCond_Alwaysflag tells ImGui to set this position every frame:if (const ImGuiViewport* v = ImGui::GetMainViewport()) {ImGui::SetNextWindowPos({v->WorkPos.x + v->WorkSize.x - 15.0f,v->WorkPos.y + 15.0f },ImGuiCond_Always, { 1.0f, 0.0f });} - Set the next window to be transparent. We use
SetNextWindowSize()to assign a fixed size value to the window. The width is calculated usingCalcTextSize(). Note how that"FPS : _______"placeholder string is used here as a parameter to make sure the width of the window does not fluctuate based on the number of digits in the numeric FPS value:ImGui::SetNextWindowBgAlpha(0.30f);ImGui::SetNextWindowSize(ImVec2(ImGui::CalcTextSize("FPS : _______").x, 0)); - An ImGui window that contains the FPS counter is rendered using various ImGui flags so that all unnecessary window decorations are disabled and no user interaction can happen with the window:
if (ImGui::Begin("##FPS", nullptr,ImGuiWindowFlags_NoDecoration |ImGuiWindowFlags_AlwaysAutoResize |ImGuiWindowFlags_NoSavedSettings |ImGuiWindowFlags_NoFocusOnAppearing |ImGuiWindowFlags_NoNav |ImGuiWindowFlags_NoMove)){ImGui::Text("FPS : %i", (int)fpsCounter.getFPS());ImGui::Text("ms : %.1f", 1000.0 / fpsCounter.getFPS());}ImGui::End();
- After we have rendered the FPS window, let’s draw ImPlot and ImGui demo windows so you can explore them. The ImPlot library will be covered a bit more in subsequent recipes:
ImPlot::ShowDemoWindow();ImGui::ShowDemoWindow();imgui->endFrame(buf);buf.cmdEndRendering();
Now you know how to display a window in your apps that includes a nice FPS counter. Although this feature is straightforward, it can be tiresome to repeatedly include this code in every app. In the upcoming recipes, we will introduce a VulkanApp helper class that will handle various utility functions like this. But for now, let’s go back to rendering and explore how to work with cube map textures.
Using cube map textures in Vulkan
Section titled “Using cube map textures in Vulkan”A cube map is a texture that contains 6 individual 2D textures that together form 6 sides of a cube. A useful property of cube maps is that they can be sampled using a direction vector. This comes in handy when representing light coming into a scene from different directions. For example, we can store the diffuse part of the physically based lighting equation in an irradiance cube map, which we will touch on in Chapter 6.
Loading 6 faces of a cube map into LightweightVK is a fairly straightforward operation. However, instead of just 6 faces, cube maps are often stored as equirectangular projections or as vertical or horizontal crosses. The equirectangular projection is such a projection that maps longitude and latitude (vertical and horizontal lines) to straight, even lines, making it a very easy and popular way to store light probe images, as shown in Figure 4.4 later in this recipe.
In this recipe, we will learn how to convert this cube map representation into 6 faces and render them with Vulkan.
Getting ready
Section titled “Getting ready”There are many websites that offer high-dynamic range environment textures under various licenses. Check out https://polyhaven.com and https://hdrmaps.com for useful content.
The complete source code for this recipe can be found in the source code bundle under the name Chapter04/04_CubeMap.
Before we start working with cube maps, let us introduce a simple Bitmap helper class to work with bitmap images in 8-bit and 32-bit floating point formats. You can find it in shared/Bitmap.h:
- Let us declare the interface part of the
Bitmapclass as follows:class Bitmap {public:Bitmap() = default;Bitmap(int w, int h, int comp, eBitmapFormat fmt);Bitmap(int w, int h, int d, int comp, eBitmapFormat fmt);Bitmap(int w, int h, int comp, eBitmapFormat fmt, const void* ptr); - Let’s set the width, height, depth, and number of components per pixel:
int w_ = 0;int h_ = 0;int d_ = 1;int comp_ = 3;
- The type of a single component can be either unsigned byte or float. The type of this bitmap can be a 2D texture or a cube map. We store the actual pixel data of this bitmap in an
std::vectorcontainer for simplicity:eBitmapFormat fmt_ = eBitmapFormat_UnsignedByte;eBitmapType type_ = eBitmapType_2D;std::vector<uint8_t> data_; - Next we need a helper function to get the number of bytes necessary to store one component of a specified format. This also requires a getter and setter for a two-dimensional image. We will come back to this later:
static int getBytesPerComponent(eBitmapFormat fmt);void setPixel(int x, int y, const glm::vec4& c);glm::vec4 getPixel(int x, int y) const;};
The implementation is also located in shared/Bitmap.h. Now let us use this class to build more high-level cube map conversion functions.
How to do it…
Section titled “How to do it…”We have a cube map at data/piazza_bologni_1k.hdr, which is available under the CC0 license and was originally downloaded from https://polyhaven.com/a/piazza_bologni. The environment map image comes in an equirectangular projection and looks like this:

Figure 4.4: Equirectangular projection
Note
An equirectangular projection is very common and straightforward. In this type of projection, each horizontal position on the rectangular image corresponds to a longitude on the sphere, while each vertical position represents a latitude. Because of these relationships, it is also known as a lat/long projection.
Let us convert it into a vertical cross. In the vertical cross format, each cube map face is represented as a square inside the entire 2D image, as follows:

Figure 4.5: Vertical cross
If we use a naïve way to convert an equirectangular projection to cube map faces by iterating over its pixels, calculating the Cartesian coordinates for each pixel, and saving the pixel into a cube map face using the Cartesian coordinates, we will end up with a texture heavily damaged by a Moiré pattern caused by the insufficient sampling of the resulting cube map. A better way is to do it the other way round. That means iterating over each pixel of the resulting cube map faces, calculating source floating-point equirectangular coordinates corresponding to each pixel, and sampling the equirectangular texture using bilinear interpolation. This way the final cube map will be free of artifacts:
- The first step is to introduce a helper function that maps integer coordinates inside a specified cube map face into floating-point normalized coordinates. This helper is handy because all faces in the vertical cross cube map have different vertical orientations:
vec3 faceCoordsToXYZ(int i, int j, int faceID, int faceSize) {const float A = 2.0f * float(i) / faceSize;const float B = 2.0f * float(j) / faceSize;if (faceID == 0) return vec3( -1.0f, A - 1.0f, B - 1.0f);if (faceID == 1) return vec3(A - 1.0f, -1.0f, 1.0f - B);if (faceID == 2) return vec3( 1.0f, A - 1.0f, 1.0f - B);if (faceID == 3) return vec3(1.0f - A, 1.0f, 1.0f - B);if (faceID == 4) return vec3(B - 1.0f, A - 1.0f, 1.0f);if (faceID == 5) return vec3(1.0f - B, A - 1.0f, -1.0f);return vec3();}
- The conversion function starts as follows and calculates the face size, width, and height of the resulting bitmap. It is located in
shared/UtilsCubemap.cpp:Bitmap convertEquirectangularMapToVerticalCross(const Bitmap& b) {if (b.type_ != eBitmapType_2D) return Bitmap();const int faceSize = b.w_ / 4;const int w = faceSize * 3;const int h = faceSize * 4;Bitmap result(w, h, 3); - These points define the locations of individual faces inside the cross:
const ivec2 kFaceOffsets[] = {ivec2(faceSize, faceSize * 3),ivec2(0, faceSize),ivec2(faceSize, faceSize),ivec2(faceSize * 2, faceSize),ivec2(faceSize, 0),ivec2(faceSize, faceSize * 2)};
- Two constants will be necessary to clamp the texture lookup:
const int clampW = b.w_ - 1;const int clampH = b.h_ - 1;
- Now we can start iterating over the 6 cube map faces and each pixel inside each face:
for (int face = 0; face != 6; face++) {for (int i = 0; i != faceSize; i++) {for (int j = 0; j != faceSize; j++) {
- We use trigonometry functions to calculate the latitude and longitude coordinates from the Cartesian cube map coordinates.
const vec3 P = faceCoordsToXYZ(i, j, face, faceSize);const float R = hypot(P.x, P.y);const float theta = atan2(P.y, P.x);const float phi = atan2(P.z, R);
To learn more about spherical coordinate systems, please follow this link: https://en.wikipedia.org/wiki/Spherical_coordinate_system.
- Now we can map the latitude and longitude into floating-point coordinates inside the equirectangular image:
const float Uf =float(2.0f * faceSize * (theta + M_PI) / M_PI);const float Vf =float(2.0f * faceSize * (M_PI / 2.0f - phi) / M_PI);
- Based on these floating-point coordinates, we get two pairs of integer UV coordinates, which we will use to sample 4 texels for bilinear interpolation:
const int U1 = clamp(int(floor(Uf)), 0, clampW);const int V1 = clamp(int(floor(Vf)), 0, clampH);const int U2 = clamp(U1 + 1, 0, clampW);const int V2 = clamp(V1 + 1, 0, clampH);
- Get the fractional part for the bilinear interpolation and fetch 4 samples,
A,B,C, andD, from the equirectangular map:const float s = Uf - U1;const float t = Vf - V1;const vec4 A = b.getPixel(U1, V1);const vec4 B = b.getPixel(U2, V1);const vec4 C = b.getPixel(U1, V2);const vec4 D = b.getPixel(U2, V2); - Do the bilinear interpolation and set the resulting pixel value in the vertical-cross cube map:
const vec4 color =A * (1 - s) * (1 - t) + B * (s) * (1 - t) +C * (1 - s) * t + D * (s) * (t);result.setPixel(i + kFaceOffsets[face].x,j + kFaceOffsets[face].y, color);}}}return result;}
The Bitmap class takes care of the pixel format inside the image data.
Now we can write code to cut the vertical cross into tightly packed rectangular cube map faces. Here is how to do it:
- First, let us review the layout of the vertical cross image corresponding to the Vulkan cube map faces layout.

Figure 4.6: Layout of the vertical cross image
- The layout is
3by4faces, which makes it possible to calculate the dimensions of the resulting cube map as follows. The code is fromshared/UtilsCubemap.cpp:Bitmap convertVerticalCrossToCubeMapFaces(const Bitmap& b) {const int faceWidth = b.w_ / 3;const int faceHeight = b.h_ / 4;Bitmap cubemap(faceWidth, faceHeight, 6, b.comp_, b.fmt_); - Let us set up pointers to read data from and write data to. This function is pixel format-agnostic so it needs to know the size of each pixel in bytes to be able to move pixels around with
memcpy():const uint8_t* src = b.data_.data();uint8_t* dst = cubemap.data_.data();const int pixelSize = cubemap.comp_ *Bitmap::getBytesPerComponent(cubemap.fmt_); - Iterate over the faces and over every pixel of each face. The order of cube map faces here corresponds to the order of Vulkan cube map faces as described in Vulkan specification 16.5.4. Cube Map Face Selection:
for (int face = 0; face != 6; ++face) {for (int j = 0; j != faceHeight; ++j) {for (int i = 0; i != faceWidth; ++i) {int x = 0;int y = 0;
- Calculate the source pixel position in the vertical cross layout based on the destination cube map face index:
switch (face) {case 0: // +Xx = 2 * faceWidth + i;y = 1 * faceHeight + j;break;case 1: // -Xx = i;y = faceHeight + j;break;case 2: // +Yx = 1 * faceWidth + i;y = j;break;case 3: // -Yx = 1 * faceWidth + i;y = 2 * faceHeight + j;break;case 4: // +Zx = faceWidth + i;y = faceHeight + j;break;case 5: // -Zx = 2 * faceWidth - (i + 1);y = b.h_ - (j + 1);break;}
- Copy the pixel and advance to the next one:
memcpy(dst, src + (y * b.w_ + x) * pixelSize, pixelSize);dst += pixelSize;}}}return cubemap;}
The resulting cube map contains an array of six 2D images. Let us write some more C++ code to load and convert the actual texture data and upload it into LightweightVK. The source code is located in Chapter04/04_CubeMap/src/main.cpp:
- Use the
STB_imagefloating point API to load a high dynamic range image from an.hdrfile:int w, h;const float* img = stbi_loadf("data/piazza_bologni_1k.hdr", &w, &h, nullptr, 4);Bitmap in(w, h, 4, eBitmapFormat_Float, img); - Convert an equirectangular map to a vertical cross and save the resulting image to an
.hdrfile for further inspection:Bitmap out = convertEquirectangularMapToVerticalCross(in);stbi_image_free((void*)img);stbi_write_hdr(".cache/screenshot.hdr", out.w_, out.h_, out.comp_,(const float*)out.data_.data()); - Convert the loaded vertical cross image to the actual cube map faces:
Bitmap cubemap = convertVerticalCrossToCubeMapFaces(out);
- Now, uploading texture data to LightweightVK is straightforward. We call the
IContext::createTexture()member function to create a texture and provide a pointer to the cube map data returned bycubemap.data_.data():Holder<TextureHandle> cubemapTex = ctx->createTexture({.type = lvk::TextureType_Cube,.format = lvk::Format_RGBA_F32,.dimensions = {(uint32_t)cubemap.w_, (uint32_t)cubemap.h_},.usage = lvk::TextureUsageBits_Sampled,.data = cubemap.data_.data(),.debugName = "data/piazza_bologni_1k.hdr",});
Now we should take a look at how to write the GLSL shaders for this example:
- Let us make a vertex shader
Chapter04/04_CubeMap/src/main.vertthat will take a model, view, and projection matrices as its inputs. We also need a camera position and bindless texture IDs for a mesh texture and for our cube map:layout(std430, buffer_reference) readonly buffer PerFrameData {mat4 model;mat4 view;mat4 proj;vec4 cameraPos;uint tex;uint texCube;}; - A buffer reference to
PerFrameDatais passed into the shader using Vulkan push constants (pcin the following code):layout(push_constant) uniform PushConstants {PerFrameData pc;}; - The per-vertex attributes are provided to the vertex shader. The
PerVertexstructure is used to pass parameters to a fragment shader. Normal vectors are transformed with a matrix calculated as the inverse-transpose of the model matrix:struct PerVertex {vec2 uv;vec3 worldNormal;vec3 worldPos;};layout (location = 0) in vec3 pos;layout (location = 1) in vec3 normal;layout (location = 2) in vec2 uv;layout (location=0) out PerVertex vtx;void main() {gl_Position = pc.proj * pc.view * pc.model * vec4(pos, 1.0);mat4 model = pc.model;mat3 normalMatrix = transpose( inverse(mat3(pc.model)) );vtx.uv = uv;vtx.worldNormal = normal * normalMatrix;vtx.worldPos = (model * vec4(pos, 1.0)).xyz;}
Now let’s take a look at the fragment shader found at Chapter04/04_CubeMap/src/main.frag:
- It shares the declaration of the
PerVertexstructure with the vertex shader mentioned above. The declaration is located in the fileChapter04/04_CubeMap/src/common.sp. We skip it here for the sake of brevity. The fragment shader uses thetextureBindlessCube()helper function to sample the cube map using the calculated reflection vector. This function was discussed in detail in the Using texture data in Vulkan recipe in Chapter 3. The reflected direction vector is calculated using thereflect()GLSL built-in function:layout (location=0) in PerVertex vtx;layout (location=0) out vec4 out_FragColor;void main() {vec3 n = normalize(vtx.worldNormal);vec3 v = normalize(pc.cameraPos.xyz - vtx.worldPos);vec3 reflection = -normalize(reflect(v, n));vec4 colorRefl = textureBindlessCube(pc.texCube, 0, reflection); - To add a more developed visual appearance, we add some diffuse lighting to our 3D model using a hardcoded light direction of
(0, 0.1, -1):vec4 Ka = colorRefl * 0.3;float NdotL = clamp(dot(n, normalize(vec3(0,0,-1))), 0.1, 1.0);vec4 Kd = textureBindless2D(pc.tex, 0, vtx.uv) * NdotL;out_FragColor = Ka + Kd;};
The resulting output from the application looks as follows. Note the blown-out white areas of the sky in the reflection due to how a high dynamic range image is displayed directly onto a low dynamic range framebuffer. We will come back to this issue in Chapter 10, and implement a simple HDR tone-mapping example.

Figure 4.7: Reflective rubber duck
Now let’s get back to improving the user interaction capabilities and learn how to implement a simple camera class to move around and debug our 3D scenes.
There’s more…
Section titled “There’s more…”In OpenGL, developers had to enable a special cube map sampling mode to ensure seamless filtering across all cube map faces. In Vulkan, all cube map texture fetches are seamless (as described under Cube Map Edge Handling in the Vulkan specification), except the ones with VK_FILTER_NEAREST, which are clamped to the face edge.
Working with a 3D camera and basic user interaction
Section titled “Working with a 3D camera and basic user interaction”To debug a graphical application, it is very helpful to be able to navigate and move around within a 3D scene using a keyboard or mouse. Graphics APIs themselves are not familiar with concepts of cameras and user interaction, so we have to implement a camera model that will convert user input into a view matrix usable by Vulkan. In this recipe, we will learn how to create a simple yet extensible 3D camera implementation and use it to enhance the functionality of our Vulkan examples.
Getting ready
Section titled “Getting ready”The source code for this recipe can be found in Chapter04/05_Camera. The camera classes are declared and implemented in the file shared/Camera.h.
How to do it…
Section titled “How to do it…”Our camera implementation will calculate a view matrix and a 3D position point based on the selected dynamic model. Let’s look at the steps:
- First, let us implement the
Cameraclass, which will represent our main API to work with a 3D camera. The class stores a reference to an instance of theCameraPositionerInterfaceclass, being a polymorphic implementation of the underlying camera model to allow runtime switches of camera behaviors:class Camera final {public:explicit Camera(CameraPositionerInterface& positioner): positioner_(&positioner) {}Camera(const Camera&) = default;Camera& operator = (const Camera&) = default;mat4 getViewMatrix() const {return positioner_->getViewMatrix();}vec3 getPosition() const {return positioner_->getPosition();}private:const CameraPositionerInterface* positioner_;};
The interface of CameraPositionerInterface contains only pure virtual methods and a default virtual destructor:
class CameraPositionerInterface {public: virtual ~CameraPositionerInterface() = default; virtual mat4 getViewMatrix() const = 0; virtual vec3 getPosition() const = 0;};- Now we can implement the actual camera model. We will start with a quaternion-based first-person camera that can be freely moved in space in any direction. Let us look at the
CameraPositioner_FirstPersonclass. The innerMovementstructure contains Boolean flags that define the current motion state of our camera. This is useful to decouple keyboard and mouse inputs from the camera control logic:class CameraPositioner_FirstPerson final:public CameraPositionerInterface{public:struct Movement {bool forward_ = false;bool backward_ = false;bool left_ = false;bool right_ = false;bool up_ = false;bool down_ = false;bool fastSpeed_ = false;} movement_; - Various numeric parameters define how responsive the camera will be to acceleration and damping. These parameters can be tweaked as you see fit:
float mouseSpeed_ = 4.0f;float acceleration_ = 150.0f;float damping_ = 0.2f;float maxSpeed_ = 10.0f;float fastCoef_ = 10.0f;
- We need certain private data members to control the camera state, such as the previous mouse position, the current camera position and orientation, the current movement speed, and the vector representing the “up” direction:
private:vec2 mousePos_ = vec2(0);vec3 cameraPosition_ = vec3(0.0f, 10.0f, 10.0f);quat cameraOrientation_ = quat(vec3(0));vec3 moveSpeed_ = vec3(0.0f);vec3 up_ = vec3(0.0f, 0.0f, 1.0f);
- The non-default constructor takes the camera’s initial position, a target position, and a vector pointing upwards. This input is similar to what one might normally use to construct a look-at viewing matrix. Indeed, we use the
glm::lookAt()function to initialize the camera:public:CameraPositioner_FirstPerson() = default;CameraPositioner_FirstPerson(const vec3& pos,const vec3& target, const vec3& up): cameraPosition_(pos), cameraOrientation_(glm::lookAt(pos, target, up)), up_(up){} - Now, we can add some dynamics to our camera model. The
update()method should be called every frame and take the time elapsed since the previous frame, as well as the mouse position and a mouse-button-pressed flag:void update(double deltaSeconds,const glm::vec2& mousePos, bool mousePressed){if (mousePressed) {const glm::vec2 delta = mousePos - mousePos_;const glm::quat deltaQuat = glm::quat(glm::vec3(mouseSpeed_ * delta.y, mouseSpeed_ * delta.x, 0.0f));cameraOrientation_ =glm::normalize(deltaQuat * cameraOrientation_);setUpVector(up_);}mousePos_ = mousePos;
Now, when the mouse button is pressed, we calculate a delta vector versus the previous mouse position, and use it to construct a rotation quaternion. This quaternion is used to rotate the camera. Once the camera rotation is applied, we should update the mouse position state.
- Now we should establish the camera’s coordinate system to calculate the camera movement. Let us extract the forward, right, and up vectors from the
mat4view matrix:const mat4 v = glm::mat4_cast(cameraOrientation_);const vec3 forward = -vec3(v[0][2], v[1][2], v[2][2]);const vec3 right = vec3(v[0][0], v[1][0], v[2][0]);const vec3 up = cross(right, forward);
The forward vector corresponds to the camera’s direction, which is the direction the camera is pointing at. The right vector corresponds to the positive X-axis of the camera space. The up vector is the positive Y-axis of the camera space, which is perpendicular to the first two vectors and can be calculated as their cross product.
- The camera coordinate system has been established. Now we can apply our input state from the
Movementstructure to control the movement of our camera:vec3 accel(0.0f);if (movement_.forward_ ) accel += forward;if (movement_.backward_) accel -= forward;if (movement_.left_ ) accel -= right;if (movement_.right_) accel += right;if (movement_.up_ ) accel += up;if (movement_.down_) accel -= up;if (movement_.fastSpeed_) accel *= fastCoef_;
Instead of controlling the camera speed or position directly, we let the user input control only the acceleration vector directly. This way, the camera’s behavior is much smoother, more natural, and non-jerky.
- If, based on the input state, the calculated camera acceleration is zero, we should decelerate the camera’s motion gradually, according to the
damping_parameter. Otherwise, we should integrate the camera motion using simple Euler integration. The maximum possible speed value is clamped according to themaxSpeed_parameter:if (accel == vec3(0)) {moveSpeed_ -= moveSpeed_ * std::min((1.0f / damping_) *static_cast<float>(deltaSeconds), 1.0f);}else {moveSpeed_ += accel * acceleration_ *static_cast<float>(deltaSeconds);const float maxSpeed =movement_.fastSpeed_ ? maxSpeed_ * fastCoef_ : maxSpeed_;if (glm::length(moveSpeed_) > maxSpeed)moveSpeed_ = glm::normalize(moveSpeed_) * maxSpeed;}cameraPosition_ += moveSpeed_ *static_cast<float>(deltaSeconds);} - The view matrix can be calculated from the camera orientation quaternion and camera position in the following way:
virtual mat4 getViewMatrix() const override {const mat4 t = glm::translate(mat4(1.0f), -cameraPosition_);const mat4 r = glm::mat4_cast(cameraOrientation_);return r * t;}
The translational part is inferred from the cameraPosition_ vector and the rotational part is calculated directly from the orientation quaternion.
- Helpful getters and setters are trivial, except for the
setUpVector()method, which has to recalculate the camera orientation using the existing camera position and direction as follows:virtual vec3 getPosition() const override {return cameraPosition_;}void setPosition(const vec3& pos) {cameraPosition_ = pos;}void setUpVector(const vec3& up) {const mat4 view = getViewMatrix();const vec3 dir = -vec3(view[0][2], view[1][2], view[2][2]);cameraOrientation_ =glm::lookAt(cameraPosition_, cameraPosition_ + dir, up);} - One additional helper function is necessary to reset the previous mouse position to prevent jerky rotation movements when, for example, the mouse cursor leaves the window:
void resetMousePosition(const vec2& p) { mousePos_ = p; };};
The above class can be used in 3D applications to move the viewer around. Let us see how it works.
How it works…
Section titled “How it works…”The demo application is based on the cube map example from the previous Using cube map textures in Vulkan recipe. The updated code is located at Chapter04/05_Camera/src/main.cpp.
We add a mouse state and define CameraPositioner and Camera. Let them be global variables:
struct MouseState { vec2 pos = vec2(0.0f); bool pressedLeft = false;} mouseState;const vec3 kInitialCameraPos = vec3(0.0f, 1.0f, -1.5f);const vec3 kInitialCameraTarget = vec3(0.0f, 0.5f, 0.0f);CameraPositioner_FirstPerson positioner( kInitialCameraPos, kInitialCameraTarget, vec3(0.0f, 1.0f, 0.0f));Camera camera(positioner);The GLFW cursor position callback should update mouseState the following way:
glfwSetCursorPosCallback( window, { int width, height; glfwGetFramebufferSize(window, &width, &height); mouseState.pos.x = static_cast<float>(x / width); mouseState.pos.y = 1.0f - static_cast<float>(y / height); });Here, we convert window pixel coordinates into normalized 0...1 coordinates and accommodate the inverted Y-axis.
The GLFW mouse button callback passes GLFW mouse events to ImGui and sets the pressedLeft flag when the left mouse button is pressed:
glfwSetMouseButtonCallback( window, { if (button == GLFW_MOUSE_BUTTON_LEFT) mouseState.pressedLeft = action == GLFW_PRESS; double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); const ImGuiMouseButton_ imguiButton = (button == GLFW_MOUSE_BUTTON_LEFT) ? ImGuiMouseButton_Left : (button == GLFW_MOUSE_BUTTON_RIGHT ? ImGuiMouseButton_Right : ImGuiMouseButton_Middle); ImGuiIO& io = ImGui::GetIO(); io.MousePos = ImVec2((float)xpos, (float)ypos); io.MouseDown[imguiButton] = action == GLFW_PRESS; });To handle keyboard input for camera movement, let us write the following GLFW keyboard callback:
glfwSetKeyCallback(window, { const bool press = action != GLFW_RELEASE; if (key == GLFW_KEY_ESCAPE) glfwSetWindowShouldClose(window, GLFW_TRUE); if (key == GLFW_KEY_W) positioner.movement_.forward_ = press; if (key == GLFW_KEY_S) positioner.movement_.backward_= press; if (key == GLFW_KEY_A) positioner.movement_.left_ = press; if (key == GLFW_KEY_D) positioner.movement_.right_ = press; if (key == GLFW_KEY_1) positioner.movement_.up_ = press; if (key == GLFW_KEY_2) positioner.movement_.down_ = press; if (mods & GLFW_MOD_SHIFT) positioner.movement_.fastSpeed_ = press; if (key == GLFW_KEY_SPACE) { positioner.lookAt(kInitialCameraPos, kInitialCameraTarget, vec3(0.0f, 1.0f, 0.0f)); positioner.setSpeed(vec3(0)); } });The WSAD keys are used to move the camera around and the Spacebar is used to reorient the camera up vector to the world (0, 1, 0) vector and reset the position camera back to the initial position. The Shift key is used to move the camera faster.
We can update the camera positioner from the main loop using the following statement:
positioner.update( deltaSeconds, mouseState.pos, mouseState.pressedLeft);Here’s a code fragment to upload matrices into a Vulkan per-frame uniform buffer, similar to how it was done with fixed values in the previous chapters:
const vec4 cameraPos = vec4(camera.getPosition(), 1.0f);const mat4 p = glm::perspective(glm::radians(60.0f), ratio, 0.1f, 1000.0f);const mat4 m1 = glm::rotate( mat4(1.0f), glm::radians(-90.0f), vec3(1, 0, 0));const mat4 m2 = glm::rotate( mat4(1.0f), (float)glfwGetTime(), vec3(0.0f, 1.0f, 0.0f));const mat4 v = glm::translate(mat4(1.0f), vec3(cameraPos));const PerFrameData pc = { .model = m2 * m1, .view = camera.getViewMatrix(), .proj = p, .cameraPos = cameraPos, .tex = texture.index(), .texCube = cubemapTex.index(),};ctx->upload(bufferPerFrame, &pc, sizeof(pc));Run the demo from Chapter04/05_Camera to play around with the keyboard and mouse:

Figure 4.8: Camera
There is more…
Section titled “There is more…”This camera design approach can be extended to accommodate different motion behaviors. In the next recipe, we will learn how to implement some other useful camera positioners.
The 3D camera functionality introduced in this recipe is incredibly valuable for our book. To reduce code duplication, we’ve created a helper class called VulkanApp. This class wraps the first-person camera positioner along with other features such as the frames-per-second counter, ImGuiRenderer, and some others. The VulkanApp class will be utilized in all the subsequent recipes throughout this book. You can find it in the shared/VulkanApp.h and shared/VulkanApp.cpp files.
Adding camera animations and motion
Section titled “Adding camera animations and motion”Besides having a user-controlled first-person camera, it is convenient to be able to position and move the camera programmatically inside a 3D scene – this is helpful for debugging when we need to organize automatic screenshot tests with camera movement, for example. In this recipe, we will show how to do it and extend our minimalistic 3D camera framework from the previous recipe. We will draw a combo box using ImGui to select between two camera modes: a first-person free camera, and a fixed camera moving to a user-specified point settable from the UI.
Getting ready
Section titled “Getting ready”The full source code for this recipe is a part of the final demo application for this chapter, and you can find it in Chapter04/06_DemoApp. Implementations of all new camera-related functionality are located in the shared/Camera.h file.
How to do it…
Section titled “How to do it…”Let’s look at how to programmatically control our 3D camera using a simple ImGui-based user interface:
- First, we need to add a new
CameraPosition_MoveTocamera positioner that automatically moves the camera to a specifiedvec3point. For this purpose, we have to declare a bunch of global constants and variables:const vec3 kInitialCameraPos = vec3(0.0f, 1.0f, -1.5f);const vec3 kInitialCameraAngles = vec3(-18.5f, 180.0f, 0.0f);CameraPositioner_MoveTo positionerMoveTo(kInitialCameraPos, kInitialCameraAngles); - Inside the main loop, we should update our new camera positioner. The first-person camera positioner is updated automatically inside the
VulkanAppclass mentioned in the previous recipe:positioner_moveTo.update(deltaSeconds, mouseState.pos, mouseState.pressedLeft);
Now, let’s draw an ImGui combo box to select which camera positioner should be used to control the camera motion:
- First, a few more global variables will come in handy to store the current camera type, items of the combo box UI, and the new value selected in the combo box:
const char* cameraType = "FirstPerson";const char* comboBoxItems[] = { "FirstPerson", "MoveTo" };const char* currentComboBoxItem = cameraType;
- To render the camera control UI with a combo box, let’s write the following code. A new ImGui window starts with a call to
ImGui::Begin():ImGui::Begin("Camera Controls", nullptr,ImGuiWindowFlags_AlwaysAutoResize);{ - The combo box itself is rendered via
ImGui::BeginCombo(). The second parameter is the previewed label name to show before opening the combo box. This function will return true if the user has clicked on a label:if (ImGui::BeginCombo("##combo", currentComboBoxItem)) {for (int n = 0; n < IM_ARRAYSIZE(comboBoxItems); n++) {const bool isSelected =currentComboBoxItem == comboBoxItems[n]; - You may set the initial focus when opening the combo box. This is useful if you want to support scrolling or keyboard navigation inside the combo box:
if (ImGui::Selectable(comboBoxItems[n], isSelected))currentComboBoxItem = comboBoxItems[n];if (isSelected)ImGui::SetItemDefaultFocus();}
- Finalize the ImGui combo box rendering:
ImGui::EndCombo();}
- If the
MoveTocamera type is selected, rendervec3input sliders to get the camera position and Euler angles from the user:if (!strcmp(cameraType, "MoveTo")) {if (ImGui::SliderFloat3("Position",glm::value_ptr(cameraPos), -10.0f, +10.0f)) {positionerMoveTo.setDesiredPosition(cameraPos);}if (ImGui::SliderFloat3("Pitch/Pan/Roll",glm::value_ptr(cameraAngles), -180.0f, +180.0f)) {positionerMoveTo.setDesiredAngles(cameraAngles);}} - If a new selected combo box item is different from the current camera type, print a debug message and change the active camera mode:
if (currentComboBoxItem &&strcmp(currentComboBoxItem, cameraType)) {printf("Selected new camera type: %s\n", currentComboBoxItem);cameraType = currentComboBoxItem;reinitCamera(app);}
- The resulting combo box should look as in the following screenshot:

Figure 4.9: Camera controls
The preceding code is called from the main loop on every frame to draw ImGui. Check out the Chapter04/06_DemoApp/src/main.cpp file for the complete source code.
How it works…
Section titled “How it works…”Let’s take a look at the implementation of the CameraPositioner_MoveTo class in shared/Camera.h we mentioned earlier in steps 1 and 2. In contrast to the first-person camera positioner introduced in the previous recipe, which relies on quaternions, this new positioner employs a straightforward Euler angles approach to store the camera orientation. This method is more user-friendly and intuitive for controlling the camera. The following are the steps to help us understand how this camera positioner works:
- First, we want to have some user-configurable parameters for linear and angular damping coefficients:
class CameraPositioner_MoveTo final :public CameraPositionerInterface{public:float dampingLinear_ = 10.0f;vec3 dampingEulerAngles_ = vec3(5.0f, 5.0f, 5.0f);
- We store the current and desired positions of the camera as well as two sets of pitch, pan, and roll Euler angles in
vec3member fields. The current camera transformation is updated every frame and saved in amat4field:private:vec3 positionCurrent_ = vec3(0.0f);vec3 positionDesired_ = vec3(0.0f);vec3 anglesCurrent_ = vec3(0.0f); // pitch, pan, rollvec3 anglesDesired_ = vec3(0.0f);mat4 currentTransform_ = mat4(1.0f); - The constructor initializes both the current and desired data sets of the camera:
public:CameraPositioner_MoveTo(const vec3& pos, const vec3& angles): positionCurrent_(pos), positionDesired_(pos), anglesCurrent_(angles), anglesDesired_(angles){}
- The most interesting part happens in the
update()function. The current camera position is changed to move towards the desired camera position. The movement speed is proportional to the distance between these two positions and scaled using the linear damping coefficient:void update(float deltaSeconds, const vec2& mousePos, bool mousePressed){positionCurrent_ += dampingLinear_ *deltaSeconds * (positionDesired_ - positionCurrent_); - Now, let’s deal with Euler angles. We should clip them accordingly to make sure they remain within the
0…360degrees range. This is required to prevent our camera from “spinning” around the object2*Pitimes:anglesCurrent_ = clipAngles(anglesCurrent_);anglesDesired_ = clipAngles(anglesDesired_); - Similar to how we dealt with the camera position, the Euler angles are updated based on the distance between the desired and current set of angles. Before calculating the camera transformation matrix, clip the updated angles again and convert the values from degrees to radians. Note how the pitch, pan, and roll angles are swizzled before they are forwarded into
glm::yawPitchRoll():anglesCurrent_ -= angleDelta(anglesCurrent_, anglesDesired_)* dampingEulerAngles_ * deltaSeconds;anglesCurrent_ = clipAngles(anglesCurrent_);const vec3 ang = glm::radians(anglesCurrent_);currentTransform_ = glm::translate(glm::yawPitchRoll(ang.y, ang.x, ang.z), -positionCurrent_);} - The functions for the angle clipping are straightforward and look as follows:
private:static inline float clipAngle(float d) {if (d < -180.0f) return d + 360.0f;if (d > +180.0f) return d - 360.f;return d;}static inline vec3 clipAngles(const vec3& angles) {return vec3( std::fmod(angles.x, 360.0f),std::fmod(angles.y, 360.0f),std::fmod(angles.z, 360.0f) );}
- The delta between two sets of angles can be calculated in the following way:
static inline vec3 angleDelta( const vec3& anglesCurrent,const vec3& anglesDesired ){const vec3 d =clipAngles(anglesCurrent) - clipAngles(anglesDesired);return vec3(clipAngle(d.x), clipAngle(d.y), clipAngle(d.z));}};
Try running the demo application, Chapter04/06_DemoApp. Switch to the MoveTo camera and change the position and orientation from the ImGui user interface.
There’s more…
Section titled “There’s more…”Further camera functionality can be built on top of this example implementation. One more useful extension might be a camera that follows a spline curve defined using a set of key points for positions and targets. We will leave this as an exercise for you.
Implementing an immediate-mode 3D drawing canvas
Section titled “Implementing an immediate-mode 3D drawing canvas”The Setting up Vulkan debugging capabilities recipe from Chapter 2, only scratched the surface of graphical application debugging. The validation layers provided by the Vulkan API are invaluable but they do not allow you to debug logical and calculation-related errors. To see what is happening in our virtual world, we need to be able to render auxiliary graphical information such as objects’ bounding boxes and plot time-varying charts of different values or plain straight lines. The Vulkan API does not provide any immediate-mode rendering facilities. All it can do is add commands to command buffers scheduled for later submission. To overcome this difficulty and add an immediate-mode rendering canvas to our applications, we have to write some additional code. Let’s learn how to do it in this recipe.
Getting ready
Section titled “Getting ready”Make sure you are proficient with all the rendering recipes from Chapter 3. Check the shared/LineCanvas.h and shared/LineCanvas.cpp files for a working implementation of this recipe. An example of how to use a new LineCanvas3D 3D line drawing class is a part of the demo app at Chapter04/06_DemoApp.
How to do it…
Section titled “How to do it…”The LineCanvas3D class contains a CPU-accessible list of 3D lines defined by two points and a color. Each frame, the user can call the line() method to draw a new 3D line that should be rendered in the current frame. To render these lines into the framebuffer, we maintain a collection of Vulkan buffers to store line geometry data, which we will update every frame.
Let’s take a look at the interface of this class:
- The
LineCanvas3Dclass has its internal 3D line representation as a pair of vertices for each and every line, whereas each vertex consists of avec4position and a color. EachlinesBufferbuffer holds a GPU-visible copy of thelines_container. We have one buffer for each swapchain image to avoid any additional Vulkan synchronization:struct LineCanvas3D {mat4 mvp_ = mat4(1.0f);struct LineData {vec4 pos;vec4 color;};std::vector<LineData> lines_;Holder<ShaderModuleHandle> vert_;Holder<ShaderModuleHandle> frag_;Holder<RenderPipelineHandle> pipeline_;constexpr uint32_t kNumImages = 3;Holder<BufferHandle> linesBuffer_[kNumImages] = {};uint32_t pipelineSamples_ = 1;uint32_t currentBufferSize_[kNumImages] = {};uint32_t currentFrame_ = 0;void setMatrix(const mat4& mvp) { mvp_ = mvp; } - The actual drawing functionality consists of a set of functions. We want to be able to clear the canvas, render one line, and render some useful primitives, such as 3D planes, boxes, and frustums. Further utility functions can easily be built on top of the functionality provided by the
line()member function:void clear() { lines_.clear(); }void line(const vec3& p1, const vec3& p2, const vec4& c);void plane(vec3& orig, const vec3& v1, const vec3& v2,int n1, int n2, float s1, float s2,const vec4& color, const vec4& outlineColor);void box(const mat4& m, const BoundingBox& box, const vec4& color);void box(const mat4& m, const vec3& size, const vec4& color);void frustum(const mat4& camView, const mat4& camProj,const vec4& color); - The longest method of this class is
render(), which generates Vulkan commands into the provided command buffer to render the current contents ofLineCanvas3D. We will look into its implementation in a few moments:void render(lvk::IContext& ctx,const lvk::Framebuffer& desc,lvk::ICommandBuffer& buf,uint32_t numSamples = 1);};
Now, let us deal with the non-Vulkan part of the code:
- The
line()member function itself just adds two coloredvec3points to the container:void LineCanvas3D::line(const vec3& p1, const vec3& p2, const vec4& c) {lines_.push_back({ .pos = vec4(p1, 1.0f), .color = c });lines_.push_back({ .pos = vec4(p2, 1.0f), .color = c });} - The
plane()method usesline()internally to create a visual representation of a three-dimensional plane spanned by thev1andv2vectors with half-sizess1ands2, and an origin pointo. Then1andn2parameters specify how many lines we want to render along each coordinate direction:void LineCanvas3D::plane(const vec3& o, const vec3& v1, const vec3& v2, int n1, int n2,float s1, float s2,const vec4& color, const vec4& outlineColor) - Draw the 4 outer lines representing a plane segment:
line(o - s1 / 2.0f * v1 - s2 / 2.0f * v2,o - s1 / 2.0f * v1 + s2 / 2.0f * v2, outlineColor);line(o + s1 / 2.0f * v1 - s2 / 2.0f * v2,o + s1 / 2.0f * v1 + s2 / 2.0f * v2, outlineColor);line(o - s1 / 2.0f * v1 + s2 / 2.0f * v2,o + s1 / 2.0f * v1 + s2 / 2.0f * v2, outlineColor);line(o - s1 / 2.0f * v1 - s2 / 2.0f * v2,o + s1 / 2.0f * v1 - s2 / 2.0f * v2, outlineColor);
- Draw
n1horizontal lines andn2vertical lines inside the plane:for (int i = 1; i < n1; i++) {float t = ((float)i - (float)n1 / 2.0f) * s1/(float)n1;const vec3 o1 = o + t * v1;line(o1 - s2 / 2.0f * v2,o1 + s2 / 2.0f * v2, color);}for (int i = 1; i < n2; i++) {const float t = ((float)i - (float)n2 / 2.0f) * s2/(float)n2;const vec3 o2 = o + t * v2;line(o2 - s1 / 2.0f * v1,o2 + s1 / 2.0f * v1, color);} - The
box()member function draws a colored box oriented using the providedmmodel matrix and half-sizesizealong theX,Y, andZaxes. The idea is to create 8 corner points of the box and transform them using themmatrix:void LineCanvas3D::box(const mat4& m,const vec3& size, const vec4& color){vec3 pts[8] = { vec3(+size.x, +size.y, +size.z),vec3(+size.x, +size.y, -size.z),vec3(+size.x, -size.y, +size.z),vec3(+size.x, -size.y, -size.z),vec3(-size.x, +size.y, +size.z),vec3(-size.x, +size.y, -size.z),vec3(-size.x, -size.y, +size.z),vec3(-size.x, -size.y, -size.z) };for (auto& p : pts) p = vec3(m * vec4(p, 1.f)); - Then render all 12 edges of the box using the
line()function:line(pts[0], pts[1], color);line(pts[2], pts[3], color);line(pts[4], pts[5], color);line(pts[6], pts[7], color);line(pts[0], pts[2], color);line(pts[1], pts[3], color);line(pts[4], pts[6], color);line(pts[5], pts[7], color);line(pts[0], pts[4], color);line(pts[1], pts[5], color);line(pts[2], pts[6], color);line(pts[3], pts[7], color);} - There’s yet another overload of the
box()function, which takes in theBoundingBoxclass declared inshared/UtilsMath.h. It is just a trivial wrapper over the previous variant of this function:void LineCanvas3D::box(const mat4& m,const BoundingBox& box, const vec4& color){this->box(m * glm::translate(mat4(1.f),0.5f * (box.min_ + box.max_)),0.5f * vec3(box.max_ - box.min_), color);} - The most interesting drawing function is
frustum(), which renders a 3D frustum represented by acamProjview matrix positioned in the world using thecamViewmatrix. Long story short, if you have a 3D camera somewhere in your world and its view and projection matrix arecamViewandcamProjrespectively, you can use this function to visualize that camera’s viewing frustum:
Note
This code is invaluable in debugging things such as shadow maps or culling frustums. We will put it to heavy use in the final chapters of this book.
void LineCanvas3D::frustum( const mat4& camView, const mat4& camProj, const vec4& color){- The idea is somewhat similar to the
box()function mentioned above. We create a set of corner points on a cube corresponding to 8 corners of the camera frustum (points are referred to asppin the following code). Then, we transform each of these points with the inverse of the provided view-projection matrix, essentially warping a box into a frustum shape. Then we useline()to connect the dots:const vec3 corners[] = { vec3(-1, -1, -1),vec3(+1, -1, -1),vec3(+1, +1, -1),vec3(-1, +1, -1),vec3(-1, -1, +1),vec3(+1, -1, +1),vec3(+1, +1, +1),vec3(-1, +1, +1) };vec3 pp[8];for (int i = 0; i < 8; i++) {glm::vec4 q = glm::inverse(camView) *glm::inverse(camProj) *glm::vec4(corners[i], 1.0f);pp[i] = glm::vec3(q.x/q.w, q.y/q.w, q.z/q.w);} - These are four lines representing the side edges of the camera frustum:
line(pp[0], pp[4], color);line(pp[1], pp[5], color);line(pp[2], pp[6], color);line(pp[3], pp[7], color);
- With the side edges done, we need to draw the near plane. The extra two lines are used to draw a cross inside the near plane:
line(pp[0], pp[1], color);line(pp[1], pp[2], color);line(pp[2], pp[3], color);line(pp[3], pp[0], color);line(pp[0], pp[2], color);line(pp[1], pp[3], color);
- Next, we do the far plane. Here again, the extra two lines are used to draw a cross to give better visual cues:
line(pp[4], pp[5], color);line(pp[5], pp[6], color);line(pp[6], pp[7], color);line(pp[7], pp[4], color);line(pp[4], pp[6], color);line(pp[5], pp[7], color);
- Now let’s draw the sides of the frustum to give a nice perception of volume. We use a dimmed color and
100lines on each side:const vec4 gridColor = color * 0.7f;const int gridLines = 100; - Here are the bottom and the top sides:
vec3 p1 = pp[0];vec3 p2 = pp[1];const vec3 s1 = (pp[4]-pp[0]) / float(gridLines);const vec3 s2 = (pp[5]-pp[1]) / float(gridLines);for (int i = 0; i != gridLines; i++, p1 += s1, p2 += s2)line(p1, p2, gridColor);p1 = pp[2];p2 = pp[3];const vec3 s1 = (pp[6]-pp[2]) / float(gridLines);const vec3 s2 = (pp[7]-pp[3]) / float(gridLines);for (int i = 0; i != gridLines; i++, p1 += s1, p2 += s2)line(p1, p2, gridColor);
- The same should be done with the left and right sides of our frustum:
p1 = pp[0];p2 = pp[3];const vec3 s1 = (pp[4]-pp[0]) / float(gridLines);const vec3 s2 = (pp[7]-pp[3]) / float(gridLines);for (int i = 0; i != gridLines; i++, p1 += s1, p2 += s2)line(p1, p2, gridColor);p1 = pp[1];p2 = pp[2];const vec3 s1 = (pp[5]-pp[1]) / float(gridLines);const vec3 s2 = (pp[6]-pp[2]) / float(gridLines);for (int i = 0; i != gridLines; i++, p1 += s1, p2 += s2)line(p1, p2, gridColor);}
That covers the user-facing part of our line-drawing API. Let’s take a look at the actual rendering code to learn how it works in an app.
How it works…
Section titled “How it works…”All the rendering and graphics pipeline creation is done within a single render() function.
The function accepts a LightweightVK context, a framebuffer, and a command buffer:
void LineCanvas3D::render(lvk::IContext& ctx, const lvk::Framebuffer& desc, lvk::ICommandBuffer& buf, uint32_t numSamples){ if (lines_.empty()) return;The required GPU buffer size is calculated based on the current number of lines. If the current buffer capacity is not sufficient, the buffer is reallocated:
const uint32_t requiredSize = lines_.size() * sizeof(LineData);if (currentBufferSize_[currentFrame_] < requiredSize) { linesBuffer_[currentFrame_] = ctx.createBuffer({ .usage = lvk::BufferUsageBits_Storage, .storage = lvk::StorageType_HostVisible, .size = requiredSize, .data = lines_.data() }); currentBufferSize_[currentFrame_] = requiredSize;} else { ctx.upload(linesBuffer_[currentFrame_], lines_.data(), requiredSize);}If there’s no rendering pipeline available, we should create a new one. We use lvk::Topology_Line, which matches VK_PRIMITIVE_TOPOLOGY_LINE_LIST. Simple alpha blending is used to render all the lines:
if (pipeline_.empty() || pipelineSamples_ != numSamples) { pipelineSamples_ = numSamples; vert_ = ctx.createShaderModule({ codeVS, lvk::Stage_Vert, "Shader Module: imgui (vert)" }); frag_ = ctx.createShaderModule({ codeFS, lvk::Stage_Frag, "Shader Module: imgui (frag)" }); pipeline_ = ctx.createRenderPipeline({ .topology = lvk::Topology_Line, .smVert = vert_, .smFrag = frag_, .color = { { .format = ctx.getFormat(desc.color[0].texture), .blendEnabled = true, .srcRGBBlendFactor = lvk::BlendFactor_SrcAlpha, .dstRGBBlendFactor = lvk::BlendFactor_OneMinusSrcAlpha, } }, .depthFormat = desc.depthStencil.texture ? ctx.getFormat(desc.depthStencil.texture) : lvk::Format_Invalid, .cullMode = lvk::CullMode_None, .samplesCount = numSamples, }, nullptr);}Our line-drawing vertex shader accepts the current combined model-view-projection matrix mvp and a GPU reference to the buffer containing the line data. Everything is updated using Vulkan push constants:
struct { mat4 mvp; uint64_t addr;} pc { .mvp = mvp_, .addr = ctx.gpuAddress(linesBuffer_[currentFrame_]),};buf.cmdBindRenderPipeline(pipeline_);buf.cmdPushConstants(pc);Once the Vulkan rendering state is prepared, we can render the lines and switch to the next frame to use one of the available buffers:
buf.cmdDraw(lines_.size()); currentFrame_ = (currentFrame_ + 1) % LVK_ARRAY_NUM_ELEMENTS(linesBuffer_);}It is also worth taking a quick look at the line-drawing GLSL shaders.
The vertex shader is as follows. Programmable vertex pulling is used to extract line data from the provided buffer:
layout (location = 0) out vec4 out_color;layout (location = 1) out vec2 out_uv;struct Vertex { vec4 pos; vec4 rgba;};layout(std430, buffer_reference) readonly buffer VertexBuffer { Vertex vertices[];};layout(push_constant) uniform PushConstants { mat4 mvp; VertexBuffer vb;};void main() { Vertex v = vb.vertices[gl_VertexIndex]; out_color = v.rgba; gl_Position = mvp * v.pos;}The fragment shader is trivial and simply outputs the provided color:
layout (location = 0) in vec4 in_color;layout (location = 0) out vec4 out_color;void main() { out_color = in_color;}That is everything regarding drawing 3D lines. For a comprehensive example showing how to use this 3D drawing canvas, check the final Putting it all together into a Vulkan application recipe in this chapter.
The next recipe will conclude Vulkan auxiliary rendering by showing how to render 2D lines and charts with the help of the ImGui and ImPlot libraries.
Rendering on-screen graphs with ImGui and ImPlot
Section titled “Rendering on-screen graphs with ImGui and ImPlot”In the previous recipe, we learned how to create immediate mode drawing facilities in Vulkan with basic drawing functionality. That 3D canvas was rendered on top of a 3D scene sharing a view-projection matrix with it. In this recipe, we will continue adding useful debugging features to our framework and learn how to implement pure 2D line drawing functionality. It is possible to implement such a class in a way similar to LineCanvas3D. However, we already use the ImGui library in our apps as described in the Rendering ImGui user interface recipe. Let’s put it to use to render our 2D lines.
Getting ready
Section titled “Getting ready”We recommend revisiting the Rendering ImGui user interfaces and Implementing an immediate-mode 3D drawing canvas recipes to get a better grasp of how a simple Vulkan drawing canvas can be implemented.
How to do it…
Section titled “How to do it…”What we need at this point essentially boils down to decomposing a 2D chart or graph into a set of lines and rendering them using ImGui. Let’s go through the code to see how to do it:
- We introduce a
LineCanvas2Dclass to render 2D lines. It stores a collection of 2D lines:class LineCanvas2D {public:void clear() { lines_.clear(); }void line(const vec2& p1, const vec2& p2, const vec4& c) {lines_.push_back({ .p1 = p1, .p2 = p2, .color = c }); }void render(const char* name, uint32_t width, uint32_t height);private:struct LineData {vec2 p1, p2;vec4 color;};std::vector<LineData> lines_;}; - The
render()method is quite simple. We create a new full-screen ImGui window with all decorations removed and user input disabled:void LineCanvas2D::render(const char* nameImGuiWindow) {ImGui::SetNextWindowPos(ImVec2(0, 0));ImGui::SetNextWindowSize(ImGui::GetMainViewport()->Size);ImGui::Begin(nameImGuiWindow, nullptr,ImGuiWindowFlags_NoDecoration |ImGuiWindowFlags_AlwaysAutoResize |ImGuiWindowFlags_NoSavedSettings |ImGuiWindowFlags_NoFocusOnAppearing |ImGuiWindowFlags_NoNav |ImGuiWindowFlags_NoBackground |ImGuiWindowFlags_NoInputs); - Then we obtain ImGui’s background draw list and add all our colored lines to it one by one. The rest of the rendering will be handled as a part of the ImGui user interface rendering, as described in the Rendering ImGui user interfaces recipe:
ImDrawList* drawList = ImGui::GetBackgroundDrawList();for (const LineData& l : lines_) {drawList->AddLine(ImVec2(l.p1.x, l.p1.y),ImVec2(l.p2.x, l.p2.y),ImColor(l.color.r, l.color.g, l.color.b, l.color.a));}ImGui::End();}
- Inside the
Chapter04/06_DemoApp/src/main.cppdemo application, we can work with an instance ofLineCanvas2Dthe following way:canvas2d.clear();canvas2d.line({ 100, 300 }, { 100, 400 }, vec4(1, 0, 0, 1));canvas2d.line({ 100, 400 }, { 200, 400 }, vec4(0, 1, 0, 1));canvas2d.line({ 200, 400 }, { 200, 300 }, vec4(0, 0, 1, 1));canvas2d.line({ 200, 300 }, { 100, 300 }, vec4(1, 1, 0, 1));canvas2d.render("##plane");
This functionality is sufficient to render 2D lines for various debugging purposes. However, there’s yet another way to do rendering using the ImPlot library. Let’s use it to render an FPS graph. The helper code is in shared/Graph.h:
- We declare another small
LinearGraphhelper class to draw a graph of changing values, such as the number of rendered frames per second:class LinearGraph {const char* name_ = nullptr;const size_t maxPoints_ = 0;std::deque<float> graph_;public:explicit LinearGraph(const char* name,size_t maxGraphPoints = 256): name_(name), maxPoints_(maxGraphPoints){} - As we add more points to the graph, the old points are popped out, making the graph look like it is scrolling on the screen right-to-left. This is helpful to observe local fluctuations in values such as frames per second counters, and so on:
void addPoint(float value) {graph_.push_back(value);if (graph_.size() > maxPoints_) graph_.erase(graph_.begin());}
- The idea is to find the minimum and maximum values and normalize the graph into the
0...1range:void renderGraph(uint32_t x, uint32_t y,uint32_t width, uint32_t height,const vec4& color = vec4(1.0)) const {float minVal = std::numeric_limits<float>::max();float maxVal = std::numeric_limits<float>::min();for (float f : graph_) {if (f < minVal) minVal = f;if (f > maxVal) maxVal = f;}const float range = maxVal - minVal;float valX = 0.0;std::vector<float> dataX_;std::vector<float> dataY_;dataX_.reserve(graph_.size());dataY_.reserve(graph_.size());for (float f : graph_) {const float valY = (f - minVal) / range;valX += 1.0f / maxPoints_;dataX_.push_back(valX);dataY_.push_back(valY);} - Then we need to create an ImGui window to hold our graph. ImPlot drawing can work only inside an ImGui window. All decorations and user interactions are disabled:
ImGui::SetNextWindowPos(ImVec2(x, y));ImGui::SetNextWindowSize(ImVec2(width, height));ImGui::Begin(_, nullptr,ImGuiWindowFlags_NoDecoration |ImGuiWindowFlags_AlwaysAutoResize |ImGuiWindowFlags_NoSavedSettings |ImGuiWindowFlags_NoFocusOnAppearing |ImGuiWindowFlags_NoNav |ImGuiWindowFlags_NoBackground |ImGuiWindowFlags_NoInputs);
- A new ImPlot plot can be started in a similar way. We disable decorations for the ImPlot axes and set up colors for the line drawing:
if (ImPlot::BeginPlot(name_, ImVec2(width, height),ImPlotFlags_CanvasOnly |ImPlotFlags_NoFrame | ImPlotFlags_NoInputs)) {ImPlot::SetupAxes(nullptr, nullptr,ImPlotAxisFlags_NoDecorations,ImPlotAxisFlags_NoDecorations);ImPlot::PushStyleColor(ImPlotCol_Line,ImVec4(color.r, color.g, color.b, color.a));ImPlot::PushStyleColor(ImPlotCol_PlotBg,ImVec4(0, 0, 0, 0));
- The
ImPlot::PlotLine()function uses our collection of points’XandYvalues to render a graph:ImPlot::PlotLine("#line", dataX_.data(), dataY_.data(),(int)graph_.size(), ImPlotLineFlags_None);ImPlot::PopStyleColor(2);ImPlot::EndPlot();}ImGui::End();}
This is the entire underlying implementation code.
Let’s now take a look at Chapter04/06_DemoApp/src/main.cpp to learn how 2D chart rendering works.
How it works…
Section titled “How it works…”The app at Chapter04/06_DemoApp makes use of LinearGraph to render an FPS graph, and a simple sine graph for reference. Here is how it works:
- Both graphs are declared as global variables. They can render up to
2048points:LinearGraph fpsGraph("##fpsGraph", 2048);LinearGraph sinGraph("##sinGraph", 2048); - Inside the main loop, we add points to both graphs like this:
fpsGraph.addPoint(app.fpsCounter_.getFPS());sinGraph.addPoint(sinf(glfwGetTime() * 20.0f));
- Then we render both graphs as follows:
sinGraph.renderGraph(0, height * 0.7f, width, height * 0.2f,vec4(0.0f, 1.0f, 0.0f, 1.0f));fpsGraph.renderGraph(0, height * 0.8f, width, height * 0.2f);
The resulting graphs look as shown in the following screenshot.

Figure 4.10: Frames-per-second and sine wave graphs
Putting it all together into a Vulkan application
Section titled “Putting it all together into a Vulkan application”In this recipe, we use all the material from previous recipes of this chapter to build a Vulkan demo application combining 3D scene rendering with 2D and 3D debug line drawing functionality.
Getting ready
Section titled “Getting ready”This recipe is a consolidation of all the material in this chapter into a final demo app. It might be useful to revisit all the previous recipes to get to grips with the different user interaction and debugging techniques described in this chapter.
The full source code for this recipe can be found in Chapter04/06_DemoApp. The VulkanApp class used in this recipe is declared in shared/VulkanApp.h.
How to do it…
Section titled “How to do it…”Let’s skim through the source code to see how we can integrate the functionality from all the recipes together into a single application. We put all of the source code here so we can reference it in the subsequent chapters when necessary. All error checking is skipped again for the sake of brevity:
- The
shared/VulkanApp.hheader provides a wrapper for LightweightVK context creation and GLFW window lifetime management. Check the Initializing the Vulkan instance and graphical device and Initializing Vulkan swapchain recipes in Chapter 2 for more details:#include "shared/VulkanApp.h"#include <assimp/cimport.h>#include <assimp/postprocess.h>#include <assimp/scene.h>#include "shared/LineCanvas.h" - Here we demonstrate a camera positioner for the Adding camera animations and motion recipe:
const vec3 kInitialCameraPos = vec3(0.0f, 1.0f, -1.5f);const vec3 kInitialCameraTarget = vec3(0.0f, 0.5f, 0.0f);const vec3 kInitialCameraAngles = vec3(-18.5f, 180.0f, 0.0f);CameraPositioner_MoveTo positionerMoveTo(kInitialCameraPos, kInitialCameraAngles);vec3 cameraPos = kInitialCameraPos;vec3 cameraAngles = kInitialCameraAngles;const char* cameraType = "FirstPerson";const char* comboBoxItems[] = { "FirstPerson", "MoveTo" };const char* currentComboBoxItem = cameraType;
- The following is for the FPS graph described in the previous Rendering on-screen graphs with ImGui and ImPlot recipe:
LinearGraph fpsGraph("##fpsGraph", 2048);LinearGraph sinGraph("##sinGraph", 2048);
- The
VulkanAppclass has a built-in first-person camera as described in the Working with a 3D camera and basic user interaction recipe. We provide an initial camera position and target, as well as reducing the FPS-averaging interval for the purpose of drawing a nice fast-moving graph. Let’s create a local variable to make the access tolvk::IContextstored inVulkanAppmore convenient. We callctx.release()explicitly later:int main(){VulkanApp app({.initialCameraPos = kInitialCameraPos,.initialCameraTarget = kInitialCameraTarget });app.fpsCounter_.avgInterval_ = 0.002f;app.fpsCounter_.printFPS_ = false;LineCanvas2D canvas2d;LineCanvas3D canvas3d;unique_ptr<lvk::IContext> ctx(app.ctx_.get()); - All the shaders are loaded from files. The cube map rendering was described in the Using cube map textures in Vulkan recipe:
Holder<ShaderModuleHandle> vert = loadShaderModule(ctx, "Chapter04/04_CubeMap/src/main.vert");Holder<ShaderModuleHandle> frag = loadShaderModule(ctx, "Chapter04/04_CubeMap/src/main.frag");Holder<ShaderModuleHandle> vertSkybox = loadShaderModule(ctx, "Chapter04/04_CubeMap/src/skybox.vert");Holder<ShaderModuleHandle> fragSkybox = loadShaderModule(ctx, "Chapter04/04_CubeMap/src/skybox.frag");
- The rubber duck mesh rendering pipeline is created as follows:
struct VertexData {vec3 pos;vec3 n;vec2 tc;};const lvk::VertexInput vdesc = {.attributes = {{ .location = 0,.format = lvk::VertexFormat::Float3,.offset = offsetof(VertexData, pos) },{ .location = 1,.format = lvk::VertexFormat::Float3,.offset = offsetof(VertexData, n) },{ .location = 2,.format = lvk::VertexFormat::Float2,.offset = offsetof(VertexData, tc) }, },.inputBindings = { { .stride = sizeof(VertexData) } },};Holder<RenderPipelineHandle> pipeline =ctx->createRenderPipeline({.vertexInput = vdesc,.smVert = vert,.smFrag = frag,.color = { {.format = ctx->getSwapchainFormat()} },.depthFormat = app.getDepthFormat(),.cullMode = lvk::CullMode_Back,});
- The skybox rendering pipeline uses programmable-vertex pulling and has no vertex input state. See the Using cube map textures in Vulkan recipe for details:
Holder<RenderPipelineHandle> pipelineSkybox =ctx->createRenderPipeline({.smVert = vertSkybox,.smFrag = fragSkybox,.color = { {.format = ctx->getSwapchainFormat()} },.depthFormat = app.getDepthFormat(),});
- Let’s load the rubber duck from a
.gltffile and pack it into theverticesandindicesarrays:const aiScene* scene = aiImportFile("data/rubber_duck/scene.gltf", aiProcess_Triangulate);const aiMesh* mesh = scene->mMeshes[0];std::vector<VertexData> vertices;for (uint32_t i = 0; i != mesh->mNumVertices; i++) {const aiVector3D v = mesh->mVertices[i];const aiVector3D n = mesh->mNormals[i];const aiVector3D t = mesh->mTextureCoords[0][i];vertices.push_back({ .pos = vec3(v.x, v.y, v.z),.n = vec3(n.x, n.y, n.z),.tc = vec2(t.x, t.y) });}std::vector<uint32_t> indices;for (uint32_t i = 0; i != mesh->mNumFaces; i++)for (uint32_t j = 0; j != 3; j++)indices.push_back(mesh->mFaces[i].mIndices[j]);aiReleaseImport(scene); - Create two GPU buffers to hold
indicesandvertices:const size_t kSizeIndices = sizeof(uint32_t) * indices.size();const size_t kSizeVertices = sizeof(VertexData) * vertices.size();Holder<BufferHandle> bufferIndices =ctx->createBuffer({.usage = lvk::BufferUsageBits_Index,.storage = lvk::StorageType_Device,.size = kSizeIndices,.data = indices.data(),.debugName = "Buffer: indices" });Holder<BufferHandle> bufferVertices =ctx->createBuffer({.usage = lvk::BufferUsageBits_Vertex,.storage = lvk::StorageType_Device,.size = kSizeVertices,.data = vertices.data(),.debugName = "Buffer: vertices" }); - A uniform buffer is used to hold per-frame data, such as model-view-projection matrices, the camera position, and bindless IDs for both textures:
struct PerFrameData {mat4 model;mat4 view;mat4 proj;vec4 cameraPos;uint32_t tex = 0;uint32_t texCube = 0;};Holder<BufferHandle> bufferPerFrame =ctx->createBuffer({.usage = lvk::BufferUsageBits_Uniform,.storage = lvk::StorageType_Device,.size = sizeof(PerFrameData),.debugName = "Buffer: per-frame" });
- Now let’s bring in a 2D texture for the rubber duck model and a cube map texture for our skybox, as described in the Using cube map textures in Vulkan recipe:
Holder<TextureHandle> texture = loadTexture(ctx, "data/rubber_duck/textures/Duck_baseColor.png");Holder<TextureHandle> cubemapTex;int w, h;const float* img = stbi_loadf("data/piazza_bologni_1k.hdr", &w, &h, nullptr, 4);Bitmap in(w, h, 4, eBitmapFormat_Float, img);Bitmap out = convertEquirectangularMapToVerticalCross(in);stbi_image_free((void*)img);stbi_write_hdr(".cache/screenshot.hdr", out.w_, out.h_,out.comp_, (const float*)out.data_.data());Bitmap cubemap = convertVerticalCrossToCubeMapFaces(out);cubemapTex = ctx->createTexture({.type = lvk::TextureType_Cube,.format = lvk::Format_RGBA_F32,.dimensions = {(uint32_t)cubemap.w_, (uint32_t)cubemap.h_},.usage = lvk::TextureUsageBits_Sampled,.data = cubemap.data_.data(),.debugName = "data/piazza_bologni_1k.hdr" });
- Run the main loop using a lambda provided by the
VulkanApp::run()method. The camera positioner is updated as described in the Adding camera animations and motion recipe:app.run([&](uint32_t width, uint32_t height,float aspectRatio, float deltaSeconds) {positionerMoveTo.update(deltaSeconds, app.mouseState_.pos,ImGui::GetIO().WantCaptureMouse ?false : app.mouseState_.pressedLeft);const mat4 p = glm::perspective(glm::radians(60.0f),aspectRatio, 0.1f, 1000.0f);const mat4 m1 = glm::rotate(mat4(1.0f),glm::radians(-90.0f), vec3(1, 0, 0));const mat4 m2 = glm::rotate(mat4(1.0f),(float)glfwGetTime(), vec3(0.0f, 1.0f, 0.0f));const mat4 v = glm::translate(mat4(1.0f), app.camera_.getPosition());const PerFrameData pc = {.model = m2 * m1,.view = app.camera_.getViewMatrix(),.proj = p,.cameraPos = vec4(app.camera_.getPosition(), 1.0f),.tex = texture.index(),.texCube = cubemapTex.index(),};ctx->upload(bufferPerFrame, &pc, sizeof(pc)); - To recap the details on render passes and frame buffers, check the Dealing with buffers in Vulkan recipe in Chapter 3:
const lvk::RenderPass renderPass = {.color = { { .loadOp = lvk::LoadOp_Clear,.clearColor = {1.0f, 1.0f, 1.0f, 1.0f} } },.depth = { .loadOp = lvk::LoadOp_Clear,.clearDepth = 1.0f } };const lvk::Framebuffer framebuffer = {.color = {{ .texture = ctx->getCurrentSwapchainTexture() } },.depthStencil = { .texture = app.getDepthTexture() } };ICommandBuffer& buf = ctx->acquireCommandBuffer();buf.cmdBeginRendering(renderPass, framebuffer);
- We render the skybox as described in the Using cube map textures in Vulkan recipe. Note that 36 vertices are used to draw the skybox:
buf.cmdPushConstants(ctx->gpuAddress(bufferPerFrame));buf.cmdPushDebugGroupLabel("Skybox", 0xff0000ff);buf.cmdBindRenderPipeline(pipelineSkybox);buf.cmdDraw(36);buf.cmdPopDebugGroupLabel();
- Rendering the rubber duck mesh is done as follows:
buf.cmdPushDebugGroupLabel("Mesh", 0xff0000ff);buf.cmdBindVertexBuffer(0, bufferVertices);buf.cmdBindRenderPipeline(pipeline);buf.cmdBindDepthState({.compareOp = lvk::CompareOp_Less,.isDepthWriteEnabled = true } );buf.cmdBindIndexBuffer(bufferIndices, lvk::IndexFormat_UI32);buf.cmdDrawIndexed(indices.size());buf.cmdPopDebugGroupLabel();
- Rendering an ImGui window with a memo for keyboard hints is done as follows:
app.imgui_->beginFrame(framebuffer);ImGui::SetNextWindowPos(ImVec2(10, 10));ImGui::Begin("Keyboard hints:", nullptr,ImGuiWindowFlags_AlwaysAutoResize |ImGuiWindowFlags_NoFocusOnAppearing |ImGuiWindowFlags_NoInputs |ImGuiWindowFlags_NoCollapse);ImGui::Text("W/S/A/D - camera movement");ImGui::Text("1/2 - camera up/down");ImGui::Text("Shift - fast movement");ImGui::Text("Space - reset view");ImGui::End();
- We render a frames-per-second counter as described in the Adding a frames-per-second counter recipe:
if (const ImGuiViewport* v = ImGui::GetMainViewport()) {ImGui::SetNextWindowPos({v->WorkPos.x + v->WorkSize.x - 15.0f,v->WorkPos.y + 15.0f }, ImGuiCond_Always,{ 1.0f, 0.0f });}ImGui::SetNextWindowBgAlpha(0.30f);ImGui::SetNextWindowSize(ImVec2(ImGui::CalcTextSize("FPS : _______").x, 0));if (ImGui::Begin("##FPS", nullptr,ImGuiWindowFlags_NoDecoration |ImGuiWindowFlags_AlwaysAutoResize |ImGuiWindowFlags_NoSavedSettings |ImGuiWindowFlags_NoFocusOnAppearing |ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoMove)) {ImGui::Text("FPS : %i", (int)app.fpsCounter_.getFPS());ImGui::Text("Ms : %.1f", 1000.0 / app.fpsCounter_.getFPS());}ImGui::End();
- Our on-screen graphs and a 2D drawing canvas are handled as shown in the Rendering on-screen graphs with ImGui and ImPlot recipe:
sinGraph.renderGraph(0, height * 0.7f, width,height * 0.2f, vec4(0.0f, 1.0f, 0.0f, 1.0f));fpsGraph.renderGraph(0, height * 0.8f, width, height * 0.2f);canvas2d.clear();canvas2d.line({ 100, 300 }, { 100, 400 }, vec4(1, 0, 0, 1));canvas2d.line({ 100, 400 }, { 200, 400 }, vec4(0, 1, 0, 1));canvas2d.line({ 200, 400 }, { 200, 300 }, vec4(0, 0, 1, 1));canvas2d.line({ 200, 300 }, { 100, 300 }, vec4(1, 1, 0, 1));canvas2d.render("##plane");
- The following code handles a 3D drawing canvas, as described in the Implementing immediate mode 3D drawing canvas recipe. To demonstrate the
frustum()function, we render an ad hoc rotating frustum constructed via thelootAt()andperspective()GLM functions:canvas3d.clear();canvas3d.setMatrix(pc.proj * pc.view);canvas3d.plane(vec3(0, 0, 0), vec3(1, 0, 0), vec3(0, 0, 1),40, 40, 10.0f, 10.0f, vec4(1, 0, 0, 1), vec4(0, 1, 0, 1));canvas3d.box(mat4(1.0f), BoundingBox(vec3(-2), vec3(+2)),vec4(1, 1, 0, 1));canvas3d.frustum(glm::lookAt(vec3(cos(glfwGetTime()),kInitialCameraPos.y, sin(glfwGetTime())),kInitialCameraTarget, vec3(0.0f, 1.0f, 0.0f)),glm::perspective(glm::radians(60.0f), aspectRatio, 0.1f,30.0f), vec4(1, 1, 1, 1));canvas3d.render(*ctx.get(), framebuffer, buf, width, height); - Lastly, finalize the rendering, submit the command buffer to the GPU, and update the graphs:
app.imgui_->endFrame(buf);buf.cmdEndRendering();ctx->submit(buf, ctx->getCurrentSwapchainTexture());fpsGraph.addPoint(app.fpsCounter_.getFPS());sinGraph.addPoint(sinf(glfwGetTime() * 20.0f));});ctx.release();return 0;}
The following is a screenshot from the running application. The white graph displays the average FPS values and the rotating white frustum can be used to debug shadow mapping, as we will do in subsequent chapters:

Figure 4.11: Demo application
This chapter focused on combining multiple rendering aspects into one working Vulkan application. The graphical side still lacks some essential features, such as advanced lighting and materials, but we have almost everything in place to start rendering much more complex scenes. The next few chapters will cover more complicated mesh rendering techniques and physically-based lighting calculations based on the glTF2 format.