Skip to content
ImagineWorld

Working with Geometry Data

node_idnode-book_vulkan-3d-graphics-rendering-cookbook_chapter-05-working-with-geometry-data
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleWorking with Geometry Data
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Previously, we tried different ad hoc approaches to storing and handling 3D geometry data in our graphical applications. The mesh data layout for vertex and index buffers was hardcoded in each of our demo apps. This way it was easier to focus on other important parts of the graphics pipeline. As we go into the territory of more complex graphics applications, we require additional control over the storage of different 3D meshes in system memory and GPU buffers. However, our focus still remains on guiding you through the main principles and practices rather than on pure efficiency.

In this chapter, we will learn how to store and handle mesh geometry data in a more organized way. We will cover the following recipes:

  • Generating level-of-detail meshes using MeshOptimizer
  • Implementing programmable vertex pulling
  • Rendering instanced geometry
  • Implementing instanced meshes with compute shaders
  • Implementing an infinite grid GLSL shader
  • Integrating tessellation into the graphics pipeline
  • Organizing the mesh data storage
  • Implementing automatic geometry conversion
  • Indirect rendering in Vulkan
  • Generating textures in Vulkan using compute shaders
  • Implementing computed meshes

To run the code from this chapter on your Linux or Windows PC, you’ll require a GPU with up-to-date drivers that support Vulkan 1.3. The source code can be downloaded from https://github.com/PacktPublishing/3D-Graphics-Rendering-Cookbook-Second-Edition.

To run the demo applications from this chapter, you have to use the Amazon Lumberyard Bistro dataset from the McGuire Computer Graphics Archive http://casual-effects.com/data/index.html. You can download it automatically by running the deploy_deps.py script.

Generating level-of-detail meshes using MeshOptimizer

Section titled “Generating level-of-detail meshes using MeshOptimizer”

To get started with geometry manipulations, let’s implement a mesh geometry simplification demo using the MeshOptimizer library that, besides mesh optimizations, can generate simplified meshes for real-time discrete level-of-detail (LOD) algorithms we might want to use later. Simplification is an efficient way to improve rendering performance.

For GPUs to render a mesh efficiently, all vertices in the vertex buffer should be unique and without duplicates. Solving this problem efficiently can be a complicated and computationally intensive task in any modern 3D content pipeline. MeshOptimizer is an open-source C++ library developed by Arseny Kapoulkine, which provides algorithms to help optimize meshes for modern GPU vertex and index processing pipelines. It can reindex an existing index buffer or generate an entirely new set of indices from an unindexed vertex buffer.

Let’s learn how to optimize and generate simplified meshes with MeshOptimizer.

It is recommended that you revisit Chapter 3. The complete source code for this recipe can be found in Chapter05/01_MeshOptimizer.

MeshOptimizer can generate all necessary LOD meshes for a specified set of indices and vertices. Once we have our loaded mesh with Assimp, we can pass it to MeshOptimizer. Here’s how to do it:

  1. Let’s load a mesh from a .gltf file using Assimp. For this demo, we need only vertex positions and indices:
    const aiScene* scene = aiImportFile(
    "data/rubber_duck/scene.gltf", aiProcess_Triangulate);
    const aiMesh* mesh = scene->mMeshes[0];
    std::vector<vec3> positions;
    std::vector<uint32_t> indices;
    for (unsigned int i = 0; i != mesh->mNumVertices; i++) {
    const aiVector3D v = mesh->mVertices[i];
    positions.push_back(vec3(v.x, v.y, v.z));
    }
    for (unsigned int i = 0; i != mesh->mNumFaces; i++) {
    for (int j = 0; j != 3; j++)
    indices.push_back(mesh->mFaces[i].mIndices[j]);
    }
    aiReleaseImport(scene);
  2. The LOD meshes are represented as a collection of indices that construct a new simplified mesh from the same vertices that are used for the original mesh. This way we have to store only one set of vertices and can render corresponding LODs just by switching index buffers data. As done previously, we store all indices as unsigned 32-bit integers for simplicity. Now we should generate a remap table for our existing vertex and index data:
    std::vector<uint32_t> remap(indices.size());
    const size_t vertexCount = meshopt_generateVertexRemap(
    remap.data(), indices.data(), indices.size(),
    positions.data(), indices.size(), sizeof(vec3));

The MeshOptimizer documentation (https://github.com/zeux/meshoptimizer) tells us the following:

“…the remap table is generated based on binary equivalence of the input vertices, so the resulting mesh will be rendered in the same way.”

  1. The returned vertexCount value corresponds to the number of unique vertices that have remained after remapping. Let’s allocate space and generate new vertex and index buffers:
    std::vector<uint32_t> remappedIndices(indices.size());
    std::vector<vec3> remappedVertices(vertexCount);
    meshopt_remapIndexBuffer(remappedIndices.data(),
    indices.data(), indices.size(), remap.data());
    meshopt_remapVertexBuffer(remappedVertices.data(),
    positions.data(), positions.size(),
    sizeof(vec3), remap.data());

Now we can use other MeshOptimizer algorithms to optimize these buffers even further. The official documentation is pretty straightforward.

  1. When we want to render a mesh, the GPU has to transform each vertex via a vertex shader. GPUs can reuse transformed vertices by means of a small built-in cache, usually storing between 16 and 128 vertices inside it. In order to use this small cache effectively, we need to reorder the triangles to maximize the locality of vertex references. How to do this with MeshOptimizer in place is shown next. Pay attention to how only the indices data is being touched here:
    meshopt_optimizeVertexCache(remappedIndices.data(),
    remappedIndices.data(), indices.size(), vertexCount);
  2. Transformed vertices form triangles that are sent for rasterization to generate fragments. Usually, each fragment is run through a depth test first, and fragments that pass the depth test get the fragment shader executed to compute the final color. As fragment shaders get more and more expensive, it becomes increasingly important to reduce the number of fragment shader invocations.

This can be achieved by reducing pixel overdraw in a mesh, and, in general, it requires the use of view-dependent algorithms. However, MeshOptimizer implements heuristics to reorder triangles and minimize overdraw from all directions. We can use it as follows:

meshopt_optimizeOverdraw(remappedIndices.data(),
remappedIndices.data(), indices.size(),
glm::value_ptr(remappedVertices[0]), vertexCount,
sizeof(vec3), 1.05f);

The last parameter, 1.05, is the threshold that determines how much the algorithm can compromise the vertex cache hit ratio. We use the recommended default value from the documentation.

  1. Once we have optimized the mesh to reduce pixel overdraw, the vertex buffer access pattern can still be optimized for memory efficiency. The GPU has to fetch specified vertex attributes from the vertex buffer and pass this data into the vertex shader. To speed up this fetch, a memory cache is used, which means optimizing the locality of vertex buffer access is very important. We can use MeshOptimizer to optimize our index and vertex buffers for vertex fetch efficiency, as follows:
    meshopt_optimizeVertexFetch(remappedVertices.data(),
    remappedIndices.data(), indices.size(),
    remappedVertices.data(), vertexCount, sizeof(vec3));

This function will reorder vertices in the vertex buffer and regenerate indices to match the new contents of the vertex buffer.

  1. The last thing we will do in this recipe is simplify the mesh. MeshOptimizer can generate a new index buffer that uses existing vertices from the vertex buffer with a reduced number of triangles. This new index buffer can be used to render LOD meshes. The following code snippet shows you how to do this using the default threshold and target error values:
    const float threshold = 0.2f;
    const size_t target_index_count = size_t(remappedIndices.size() * threshold);
    const float target_error = 0.01f;
    std::vector<uint32_t> indicesLod;
    indicesLod.resize(remappedIndices.size());
    indicesLod.resize(meshopt_simplify(&indicesLod[0],
    remappedIndices.data(), remappedIndices.size(),
    &remappedVertices[0].x, vertexCount, sizeof(vec3),
    target_index_count, target_error));
    indices = remappedIndices;
    positions = remappedVertices;

Now let’s take a look at how rendering of the LOD meshes works.

In order to render the mesh and its lower-level LOD, we need to store a vertex buffer and two index buffers – one for the mesh and one for the LOD:

  1. Here’s the vertex buffer for storing all vertex positions:
    Holder<BufferHandle> vertexBuffer = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Vertex,
    .storage = lvk::StorageType_Device,
    .size = sizeof(vec3) * positions.size(),
    .data = positions.data(),
    .debugName = "Buffer: vertex" });
  2. We use two index buffers to store both sets of indices, one for each LOD:
    Holder<BufferHandle> indexBuffer = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Index,
    .storage = lvk::StorageType_Device,
    .size = sizeof(uint32_t) * indices.size(),
    .data = indices.data(),
    .debugName = "Buffer: index" });
    Holder<BufferHandle> indexBufferLod = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Index,
    .storage = lvk::StorageType_Device,
    .size = sizeof(uint32_t) * indicesLod.size(),
    .data = indicesLod.data(),
    .debugName = "Buffer: index LOD" });
  3. The rendering part is trivial, and the graphics pipeline setup is skipped here for the sake of brevity. We render the main mesh using the first index buffer:
    ICommandBuffer& buf = ctx->acquireCommandBuffer();
    buf.cmdBeginRendering({ ... }, { ... });
    buf.cmdBindVertexBuffer(0, vertexBuffer, 0);
    buf.cmdBindRenderPipeline(pipeline);
    buf.cmdBindDepthState({ .compareOp = lvk::CompareOp_Less,
    .isDepthWriteEnabled = true });
    buf.cmdPushConstants(p * v1 * m);
    buf.cmdBindIndexBuffer(indexBuffer, lvk::IndexFormat_UI32);
    buf.cmdDrawIndexed(indices.size());
  4. Then we render the LOD mesh using the second index buffer:
    buf.cmdPushConstants(p * v2 * m);
    buf.cmdBindIndexBuffer(indexBufferLod, lvk::IndexFormat_UI32);
    buf.cmdDrawIndexed(indicesLod.size());
    buf.cmdEndRendering();
    ctx->submit(buf, ctx->getCurrentSwapchainTexture());

Here’s a screenshot from the running demo application.

Figure 5.1: A mesh with a discrete LOD

Try changing the threshold parameter in the code to generate meshes with different LOD.

The MeshOptimizer library contains many other useful algorithms, such as triangle strip generation, index and vertex buffer compression, and mesh animation data compression. All of these algorithms might be very useful for your geometry preprocessing stage depending on the kind of graphics software you are writing. Check out the official documentation and the releases page to get the latest features at https://github.com/zeux/meshoptimizer.

The concept of programmable vertex pulling (PVP) was proposed in an article called Introducing the Programmable Vertex Pulling Rendering Pipeline by Daniel Rákos, published in the amazing book OpenGL Insights in 2012. The article delves into the GPU architecture of that era and explains why this data storage approach was advantageous. Initially, vertex pulling involved storing vertex data in one-dimensional buffer textures.

Instead of setting up traditional vertex input bindings, data was accessed using texelFetch() and the GLSL samplerBuffer in the vertex shader. The built-in OpenGL GLSL variable gl_VertexID was used as an index to calculate texture coordinates for texel fetching. This technique emerged as a solution to CPU bottlenecks caused by numerous draw calls. By combining multiple meshes into a single buffer and rendering them with a single draw call, developers could avoid rebinding vertex arrays or buffer objects, significantly improving draw call batching.

Nowadays, buffer textures are no longer necessary, as vertex data can be fetched directly from storage or uniform buffers using offsets calculated with the built-in Vulkan GLSL variable gl_VertexIndex.

This technique enables merge-instancing, where multiple small meshes are combined into a larger one to be processed as part of the same batch. We will make extensive use of this approach in various examples.

In this recipe, we’ll use storage buffers to implement a similar technique with Vulkan 1.3 and LightweightVK.

The complete source code for this recipe can be found in the source code bundle under the name Chapter05/02_VertexPulling.

Let’s render the rubber duck 3D model data/rubber_duck/scene.gltf from the previous recipe. However, this time, instead of using vertex attributes, we’ll use the programmable vertex-pulling technique, which requires revisiting the loading code. The approach involves allocating two buffers: one for indices and another storage buffer for vertex data. These buffers will be accessed in the vertex shader to fetch vertex positions. Here’s how it can be done:

  1. First, we load the 3D model via Assimp, as in the previous recipe:
    const aiScene* scene = aiImportFile(
    "data/rubber_duck/scene.gltf", aiProcess_Triangulate);
    const aiMesh* mesh = scene->mMeshes[0];
  2. Convert per-vertex data into a format suitable for our GLSL shaders. We are going to use vec3 for positions and vec2 for texture coordinates:
    struct Vertex {
    vec3 pos;
    vec2 uv;
    };
    std::vector<Vertex> positions;
    for (unsigned int i = 0; i != mesh->mNumVertices; i++) {
    const aiVector3D v = mesh->mVertices[i];
    const aiVector3D t = mesh->mTextureCoords[0][i];
    positions.push_back({
    .pos = vec3(v.x, v.y, v.z), .uv = vec2(t.x, t.y) });
    }
  3. For simplicity, we store indices as unsigned 32-bit integers. In real-world applications, consider using 16-bit indices for small meshes and be capable of switching between them:
    std::vector<uint32_t> indices;
    for (unsigned int i = 0; i != mesh->mNumFaces; i++) {
    for (int j = 0; j != 3; j++)
    indices.push_back(mesh->mFaces[i].mIndices[j]);
    }
    aiReleaseImport(scene);
  4. Once the index and vertex data are ready, we can upload them into the Vulkan buffers. We should create two buffers, one for the vertices and one for the indices. Not that here, despite calling it a vertex buffer, we set the usage flag to lvk::BufferUsageBits_Storage:
    Holder<BufferHandle> vertexBuffer = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Storage,
    .storage = lvk::StorageType_Device,
    .size = sizeof(Vertex) * positions.size(),
    .data = positions.data(),
    .debugName = "Buffer: vertex" });
    Holder<BufferHandle> indexBuffer = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Index,
    .storage = lvk::StorageType_Device,
    .size = sizeof(uint32_t) * indices.size(),
    .data = indices.data(),
    .debugName = "Buffer: index" });
  5. Now we can load a texture, compile the shaders, and create a render pipeline for our mesh. We’ll examine the shader code shortly:
    Holder<TextureHandle> texture =
    loadTexture(ctx, "data/rubber_duck/textures/Duck_baseColor.png");
    Holder<ShaderModuleHandle> vert =
    loadShaderModule(ctx, "Chapter05/02_VertexPulling/src/main.vert");
    Holder<ShaderModuleHandle> geom =
    loadShaderModule(ctx, "Chapter05/02_VertexPulling/src/main.geom");
    Holder<ShaderModuleHandle> frag =
    loadShaderModule(ctx, "Chapter05/02_VertexPulling/src/main.frag");
    Holder<RenderPipelineHandle> pipelineSolid =
    ctx->createRenderPipeline({
    .smVert = vert,
    .smGeom = geom,
    .smFrag = frag,
    .color = { { .format = ctx->getSwapchainFormat() } },
    .depthFormat = app.getDepthFormat(),
    .cullMode = lvk::CullMode_Back,
    });
  6. Before we can proceed with the actual rendering, we should pass the texture ID and storage buffer address to our GLSL shader. We can do it using Vulkan push constants. Model-view-projection matrix calculations are reused from the previous recipe.
    const struct PushConstants {
    mat4 mvp;
    uint64_t vertices;
    uint32_t texture;
    } pc {
    .mvp = p * v * m,
    .vertices = ctx->gpuAddress(vertexBuffer),
    .texture = texture.index(),
    };
    lvk::ICommandBuffer& buf = ctx->acquireCommandBuffer();
    buf.cmdBeginRendering(renderPass, framebuffer);
    buf.cmdPushConstants(pc);
  7. Now, the mesh rendering can be done as follows.
    buf.cmdBindIndexBuffer(indexBuffer, lvk::IndexFormat_UI32);
    buf.cmdBindRenderPipeline(pipelineSolid);
    buf.cmdBindDepthState({ .compareOp = lvk::CompareOp_Less,
    .isDepthWriteEnabled = true });
    buf.cmdDrawIndexed(indices.size());
    buf.cmdEndRendering();

The rest of the C++ code can be found in Chapter05/02_VertexPulling/src/main.cpp. Now, we have to look into the GLSL vertex shader to understand how to read the vertex data from buffers. The vertex shader can be found in Chapter05/02_VertexPulling/src/main.vert:

  1. First, we have some declarations shared between all shaders. The reason for this sharing is that our fragment shader needs to access push constants to retrieve the texture ID. Note that the Vertex structure does not use vec2 and vec3 member fields to maintain tight padding and prevent any GPU alignment issues. This structure reflects how our C++ code writes vertex data into the buffer. The buffer holds an unbounded array in_Vertices[]. Each element corresponds to exactly one vertex.
    struct Vertex {
    float x, y, z;
    float u, v;
    };
    layout(std430, buffer_reference) readonly buffer Vertices {
    Vertex in_Vertices[];
    };
    layout(push_constant) uniform PerFrameData {
    mat4 MVP;
    Vertices vtx;
    uint texture;
    };
  2. Let’s introduce two accessor functions to make the shader code more readable. The assemble vec3 and vec2 values are from the raw float values in the storage buffer.
    vec3 getPosition(int i) {
    return vec3(vtx.in_Vertices[i].x,
    vtx.in_Vertices[i].y,
    vtx.in_Vertices[i].z);
    }
    vec2 getTexCoord(int i) {
    return vec2(vtx.in_Vertices[i].u,
    vtx.in_Vertices[i].v);
    }
  3. The rest of the shader is trivial. The previously mentioned functions are used to load the vertex positions and texture coordinates, which are passed further into the graphics pipeline.
    layout (location=0) out vec2 uv;
    void main() {
    gl_Position = MVP * vec4(getPosition(gl_VertexIndex), 1.0);
    uv = getTexCoord(gl_VertexIndex);
    }

That’s it for the PVP part. The fragment shader applies the texture and uses the barycentric coordinates trick for wireframe rendering as was described in the previous chapter. The resulting output from the program should look like the following screenshot:

Figure 5.2: Textured mesh rendering using PVP

PVP is a complex topic and has different performance implications. There is an open-source project that does an in-depth analysis and run-time metrics of PVP performance based on different vertex data layouts and access methods, such as storing data as an array of structures or a structure of arrays, reading data as multiple floats or a single vector type, and so on. Check it out at https://github.com/nlguillemot/ProgrammablePulling. It should become one of your go-to tools when designing PVP pipelines in your applications.

A common task in 3D rendering is drawing multiple meshes that share the same geometry but have different transformations and materials. This can result in additional CPU overhead from generating commands for the GPU to draw each mesh individually, even though the Vulkan API already reduces CPU overhead significantly.

One solution to this issue, provided by modern graphics APIs like Vulkan, is instanced rendering. This approach allows API draw commands to include the number of instances as a parameter, while the vertex shader gains access to the current instance number via gl_InstanceIndex. When combined with the PVP approach from the previous recipe, this technique becomes extremely flexible. The gl_InstanceIndex can be used to fetch material properties, transformations, and other data directly from buffers.

Let’s explore a basic instanced geometry demo to learn how to implement this in Vulkan.

Be sure to review the previous recipe, Implementing programmable vertex pulling, to understand the concept of generating vertex data within vertex shaders. The source code for this recipe is located in Chapter05/03_MillionCubes.

To demonstrate how instanced rendering works, let’s render 1 million colored rotating cubes. Each cube will have its own position and distinct rotation angle around its diagonal and will be textured with one of several different colors. Let’s take a look at the C++ code in Chapter05/03_MillionCubes/src/main.cpp:

  1. First, let’s generate a procedural texture for our cubes. An XOR pattern texture looks quite interesting. It’s created by XOR-ing the x and y coordinates of the current texel, then applying the result to all three BGR channels using bit shifts.
    const uint32_t texWidth = 256;
    const uint32_t texHeight = 256;
    std::vector<uint32_t> pixels(texWidth * texHeight);
    for (uint32_t y = 0; y != texHeight; y++) {
    for (uint32_t x = 0; x != texWidth; x++) {
    pixels[y * texWidth + x] =
    0xFF000000 + ((x^y) << 16) + ((x^y) << 8) + (x^y);
    }
    }
    Holder<TextureHandle> texture = ctx->createTexture({
    .type = lvk::TextureType_2D,
    .format = lvk::Format_BGRA_UN8,
    .dimensions = { texWidth, texHeight },
    .usage = lvk::TextureUsageBits_Sampled,
    .data = pixels.data(),
    .debugName = "XOR pattern",
    });
  2. Let’s create vec3 positions and float initial rotation angles for 1 million cubes. We can organize this data into vec4 containers and store them in an immutable storage buffer. The GLSL shader code will then perform calculations based on the elapsed time.
    const uint32_t kNumCubes = 1024 * 1024;
    std::vector<vec4> centers(kNumCubes);
    for (vec4& p : centers) {
    p = vec4(glm::linearRand(-vec3(500.0f), +vec3(500.0f)),
    glm::linearRand(0.0f, 3.14159f));
    }
    Holder<BufferHandle> bufferPosAngle = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Storage,
    .storage = lvk::StorageType_Device,
    .size = sizeof(vec4) * kNumCubes,
    .data = centers.data(),
    });
  3. We skip the usual framebuffer and pipeline creation code and jump straight into the main rendering loop. The camera motion is hardcoded to move back and forth through the swarm of cubes.
    buf.cmdBeginRendering(renderPass, framebuffer);
    const mat4 view = translate(mat4(1.0f),
    vec3(0.0f, 0.0f,
    -1000.0f + 500.0f * (1.0f - cos(-glfwGetTime() * 0.5f))));
  4. We pass all the necessary data to the shaders using push constants. The vertex shader will need the current time to perform calculations based on the initial cube positions and rotations.
    const struct {
    mat4 viewproj;
    uint32_t textureId;
    uint64_t bufferPosAngle;
    float time;
    } pc {
    .viewproj = proj * view,
    .textureId = texture.index(),
    .bufferPosAngle = ctx->gpuAddress(bufferPosAngle),
    .time = (float)glfwGetTime(),
    };
  5. Rendering is initiated with vkCmdDraw(), which is wrapped inside cmdDraw(). The first parameter, 36, is the number of vertices required to generate a cube using triangle primitives. We’ll explore how this is handled in the vertex shader shortly. The second parameter, kNumCubes, represents the number of instances to be rendered.
    buf.cmdPushConstants(pc);
    buf.cmdBindRenderPipeline(pipelineSolid);
    buf.cmdBindDepthState({ .compareOp = lvk::CompareOp_Less,
    .isDepthWriteEnabled = true });
    buf.cmdDraw(36, kNumCubes);
    buf.cmdEndRendering();

Now let’s take a look at the GLSL code to understand how this instancing demo works under the hood.

  1. Our vertex shader starts by declaring the same PerFrameData structure as in our C++ code mentioned above. The shader outputs per-vertex color and texture coordinates. The storage buffer contains positions and initial angles for all the cubes.
    layout(push_constant) uniform PerFrameData {
    mat4 viewproj;
    uint textureId;
    uvec2 bufId;
    float time;
    };
    layout (location=0) out vec3 color;
    layout (location=1) out vec2 uv;
    layout(std430, buffer_reference) readonly buffer Positions {
    vec4 pos[]; // pos: xyz, initialAngle: w
    };
  2. As you may have noticed, the C++ code in the How to do it… section did not provide any index data to shaders. Instead, we a going to generate vertex data in the vertex shader. Let’s declare indices mapping right here. We need indices to construct 6 cube faces using triangles. Two triangles per face gives 6 points per face and 36 indices in total. That is the number passed to vkCmdDraw().
    const int indices[36] = int[36](
    0, 2, 1, 2, 3, 1, 5, 4, 1, 1, 4, 0,
    0, 4, 6, 0, 6, 2, 6, 5, 7, 6, 4, 5,
    2, 6, 3, 6, 7, 3, 7, 1, 3, 7, 5, 1);
  3. Here are the per-instance colors for our cubes.
    const vec3 colors[7] = vec3[7](
    vec3(1.0, 0.0, 0.0),
    vec3(0.0, 1.0, 0.0),
    vec3(0.0, 0.0, 1.0),
    vec3(1.0, 1.0, 0.0),
    vec3(0.0, 1.0, 1.0),
    vec3(1.0, 0.0, 1.0),
    vec3(1.0, 1.0, 1.0));
  4. Since no translation or rotation matrices are passed to the vertex shader, we need to generate everything ourselves right here. Here’s a GLSL function to apply a translation by a vector v to the current transformation m. This function serves as the GLSL counterpart to the C++ function glm::translate().
    mat4 translate(mat4 m, vec3 v) {
    mat4 Result = m;
    Result[3] = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3];
    return Result;
    }
  5. Rotations are handled in a similar way. This is an analogue of glm::rotate() ported to GLSL.
    mat4 rotate(mat4 m, float angle, vec3 v) {
    float a = angle;
    float c = cos(a);
    float s = sin(a);
    vec3 axis = normalize(v);
    vec3 temp = (float(1.0) - c) * axis;
    mat4 r;
    r[0][0] = c + temp[0] * axis[0];
    r[0][1] = temp[0] * axis[1] + s * axis[2];
    r[0][2] = temp[0] * axis[2] - s * axis[1];
    r[1][0] = temp[1] * axis[0] - s * axis[2];
    r[1][1] = c + temp[1] * axis[1];
    r[1][2] = temp[1] * axis[2] + s * axis[0];
    r[2][0] = temp[2] * axis[0] + s * axis[1];
    r[2][1] = temp[2] * axis[1] - s * axis[0];
    r[2][2] = c + temp[2] * axis[2];
    mat4 res;
    res[0] = m[0] * r[0][0] + m[1] * r[0][1] + m[2] * r[0][2];
    res[1] = m[0] * r[1][0] + m[1] * r[1][1] + m[2] * r[1][2];
    res[2] = m[0] * r[2][0] + m[1] * r[2][1] + m[2] * r[2][2];
    res[3] = m[3];
    return res;
    }
  6. With this extensive arsenal at our disposal, we can now write the main() function of our vertex shader. The built-in gl_InstanceIndex variable is used to index the storage buffer and retrieve positions and angles. Then, a model matrix for the current cube is computed using the rotate() and translate() helper functions.
    void main() {
    vec4 center = Positions(bufId).pos[gl_InstanceIndex];
    mat4 model = rotate(translate(mat4(1.0f), center.xyz),
    time + center.w, vec3(1.0f, 1.0f, 1.0f));
  7. The built-in gl_VertexIndex variable ranges from 0 to 35, allowing us to extract the specific index for 8 of our vertices. We then apply this formula to generate vec3 positions for each of those 8 vertices using bit shifts.
    uint idx = indices[gl_VertexIndex];
    vec3 xyz = vec3(idx & 1, (idx & 4) >> 2, (idx & 2) >> 1);
  8. Remap the generated 0...1 vertex coordinates to the -0.5…+0.5 range and then scale them by the desired edge length:
    const float edge = 1.0;
    gl_Position =
    viewproj * model * vec4(edge * (xyz - vec3(0.5)), 1.0);
  9. The UV coordinates are selected on a per-face basis, while the colors are applied per instance:
    int face = gl_VertexIndex / 6;
    if (face == 0 || face == 3) uv = vec2(xyz.x, xyz.z);
    if (face == 1 || face == 4) uv = vec2(xyz.x, xyz.y);
    if (face == 2 || face == 5) uv = vec2(xyz.y, xyz.z);
    color = colors[gl_InstanceIndex % 7];
    }
  10. That’s all the magic that happens in the vertex shader. The fragment shader is quite simple and short:
    layout (location=0) in vec3 color;
    layout (location=1) in vec2 uv;
    layout (location=0) out vec4 out_FragColor;
    layout(push_constant) uniform PerFrameData {
    mat4 proj;
    uint textureId;
    };
    void main() {
    out_FragColor = textureBindless2D(
    textureId, 0, uv) * vec4(color, 1.0);
    }

The running demo should look like the following screenshot, where you’re flying through a swarm of 1 million cubes, moving forth and back again:

Figure 5.3: One million cubes using instanced rendering

Now, let’s extend this instancing example further and draw some meshes using real mesh data.

While this example is self-contained and much faster compared to non-instanced rendering, it can be made even faster by moving the indices out of the vertex shader and storing them in a dedicated index buffer. This allows us to take advantage of the hardware vertex cache, and model matrices can be calculated per-instance instead of per-vertex. We’ll cover this in the next recipe.

This instanced rendering approach can be combined with Vulkan’s indirect rendering technique for greater flexibility. We’ll learn how to implement this in Chapter 8, in the recipe Implementing indirect rendering with Vulkan. The basics of indirect rendering will be covered later in this chapter in the recipe Indirect rendering in Vulkan.

Implementing instanced meshes with compute shaders

Section titled “Implementing instanced meshes with compute shaders”

In the previous recipe, we learned the fundamentals of instanced rendering. While that approach covers various aspects of rendering geometry instances, such as handling model matrices and materials, it’s not yet a practical implementation. Let’s build on that example and show how to render instanced meshes loaded from a .gltf file.

To make this recipe more interesting, we’ll enhance the example by precalculating per-instance model matrices using a compute shader.

Make sure you read the previous recipe, Rendering instanced geometry. The source code for this recipe can be found in Chapter05/04_InstancedMeshes.

Let’s skim the C++ code to understand the big picture

  1. First, we generate random positions and initial rotation angles for our meshes. We use 32,000 meshes because our GPU cannot handle 1 million meshes with this naïve brute-force approach. Pushing it to 1 million meshes is possible, and we will show some tricks to approach that number in Chapter 11, Advanced Rendering Techniques and Optimizations.
    const uint32_t kNumMeshes = 32 * 1024;
    std::vector<vec4> centers(kNumMeshes);
    for (vec4& p : centers) {
    p = vec4(glm::linearRand(-vec3(500.0f), +vec3(500.0f)),
    glm::linearRand(0.0f, 3.14159f));
    }
  2. The center points and angles are loaded into a storage buffer in exactly the same way as in the previous recipe:
    Holder<BufferHandle> bufferPosAngle = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Storage,
    .storage = lvk::StorageType_Device,
    .size = sizeof(vec4) * kNumMeshes,
    .data = centers.data(),
    .debugName = "Buffer: angles & positions",
    });
  3. To store model matrices for our instances, we’ll require two buffers. We’ll alternate between them in a round-robin fashion during even and odd frames to skip unnecessary synchronization.
    Holder<BufferHandle> bufferMatrices[] = {
    ctx->createBuffer({ .usage = lvk::BufferUsageBits_Storage,
    .storage = lvk::StorageType_Device,
    .size = sizeof(mat4) * kNumMeshes,
    .debugName = "Buffer: matrices 1" }),
    ctx->createBuffer({ .usage = lvk::BufferUsageBits_Storage,
    .storage = lvk::StorageType_Device,
    .size = sizeof(mat4) * kNumMeshes,
    .debugName = "Buffer: matrices 2" }),
    };.
  4. The rubber duck 3D model is loaded from .gltf the following way. This time, besides vertex positions and texture coordinates, we require normal vectors to do some improvized lighting. We are going to need it when we render so many meshes.
    const aiScene* scene =
    aiImportFile("data/rubber_duck/scene.gltf", aiProcess_Triangulate);
    struct Vertex {
    vec3 pos;
    vec2 uv;
    vec3 n;
    };
    const aiMesh* mesh = scene->mMeshes[0];
    std::vector<Vertex> vertices;
    std::vector<uint32_t> indices;
    for (unsigned int i = 0; i != mesh->mNumVertices; i++) {
    const aiVector3D v = mesh->mVertices[i];
    const aiVector3D t = mesh->mTextureCoords[0][i];
    const aiVector3D n = mesh->mNormals[i];
    vertices.push_back({ .pos = vec3(v.x, v.y, v.z),
    .uv = vec2(t.x, t.y),
    .n = vec3(n.x, n.y, n.z) });
    }
    for (unsigned int i = 0; i != mesh->mNumFaces; i++) {
    for (int j = 0; j != 3; j++)
    indices.push_back(mesh->mFaces[i].mIndices[j]);
    }
    aiReleaseImport(scene);
  5. The mesh data is uploaded into index and vertex buffers:
    Holder<BufferHandle> vertexBuffer = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Storage,
    .storage = lvk::StorageType_Device,
    .size = sizeof(Vertex) * vertices.size(),
    .data = vertices.data(),
    .debugName = "Buffer: vertex" });
    Holder<BufferHandle> indexBuffer = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Index,
    .storage = lvk::StorageType_Device,
    .size = sizeof(uint32_t) * indices.size(),
    .data = indices.data(),
    .debugName = "Buffer: index" });
  6. Let’s load the texture and create compute and rendering pipelines. The compute shader will generate model matrices for our instances based on the elapsed time, following the approach used in the vertex shader in the previous recipe, Rendering instanced meshes. However, this time, we’ll do it on a per-instance basis instead of per vertex.
    Holder<TextureHandle> texture =
    loadTexture(ctx, "data/rubber_duck/textures/Duck_baseColor.png");
    Holder<ShaderModuleHandle> comp =
    loadShaderModule(ctx, "Chapter05/04_InstancedMeshes/src/main.comp");
    Holder<ComputePipelineHandle> pipelineComputeMatrices =
    ctx->createComputePipeline({ smComp = comp });
    Holder<ShaderModuleHandle> vert =
    loadShaderModule(ctx, "Chapter05/04_InstancedMeshes/src/main.vert");
    Holder<ShaderModuleHandle> frag =
    loadShaderModule(ctx, "Chapter05/04_InstancedMeshes/src/main.frag");
    Holder<RenderPipelineHandle> pipelineSolid =
    ctx->createRenderPipeline({
    .smVert = vert,
    .smFrag = frag,
    .color = { { .format = ctx->getSwapchainFormat() } },
    .depthFormat = app.getDepthFormat(),
    .cullMode = lvk::CullMode_Back });
  7. The main loop goes like this. We use the frameId counter to facilitate the switching of buffers containing model matrices between even and odd frames.
    uint32_t frameId = 0;
    app.run([&](uint32_t width, uint32_t height,
    float aspectRatio, float deltaSeconds)
    {
    const mat4 proj = glm::perspective(45.0f, aspectRatio, 0.2f, 1500.0f);
    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() },
    };
  8. For convenience, push constants are shared between compute and rendering pipelines:
    lvk::ICommandBuffer& buf = ctx->acquireCommandBuffer();
    const mat4 view = translate(mat4(1.0f), vec3(0.0f, 0.0f,
    -1000.0f + 500.0f * (1.0f - cos(-glfwGetTime() * 0.5f))));
    const struct {
    mat4 viewproj;
    uint32_t textureId;
    uint64_t bufferPosAngle;
    uint64_t bufferMatrices;
    uint64_t bufferVertices;
    float time;
    } pc {
    .viewproj = proj * view,
    .textureId = texture.index(),
    .bufferPosAngle = ctx->gpuAddress(bufferPosAngle),
    .bufferMatrices = ctx->gpuAddress(bufferMatrices[frameId]),
    .bufferVertices = ctx->gpuAddress(vertexBuffer),
    .time = (float)glfwGetTime(),
    };
    buf.cmdPushConstants(pc);
  9. Dispatch the compute shader. Each local workgroup handles 32 meshes – a common portable baseline supported by many GPUs:
    buf.cmdBindComputePipeline(pipelineComputeMatrices);
    buf.cmdDispatchThreadGroups({ .width = kNumMeshes / 32 } });
  10. After the compute shader has finished updating model matrices, we can start rendering. Note that we have a non-empty dependencies parameter here, which refers to the buffer with model matrices. This is necessary to make sure a proper Vulkan buffer memory barrier is issued by LightweightVK to prevent race conditions between the compute shader and the vertex shader.
    buf.cmdBeginRendering(renderPass, framebuffer,
    { .buffers = { BufferHandle(bufferMatrices[frameId]) } });

Note

Now let’s look at the barrier. The source and destination stages, respectively, are:

VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT

And:

VK_PIPELINE_STAGE_VERTEX_SHADER_BIT |
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT

The underlying Vulkan barrier looks as follows:

void lvk::CommandBuffer::bufferBarrier(BufferHandle handle,
VkPipelineStageFlags srcStage,
VkPipelineStageFlags dstStage)
{
lvk::VulkanBuffer* buf = ctx_->buffersPool_.get(handle);
const VkBufferMemoryBarrier barrier = {
.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
.srcAccessMask = VK_ACCESS_SHADER_READ_BIT |
VK_ACCESS_SHADER_WRITE_BIT,
.dstAccessMask = VK_ACCESS_SHADER_READ_BIT |
VK_ACCESS_SHADER_WRITE_BIT,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.buffer = buf->vkBuffer_,
.offset = 0,
.size = VK_WHOLE_SIZE,
};
vkCmdPipelineBarrier(wrapper_->cmdBuf_,
srcStage, dstStage, VkDependencyFlags{},
0, nullptr, 1, &barrier, 0, nullptr);
}
  1. The rest of the rendering code is pretty standard. The LightweightVK draw call command, cmdDrawIndexed(), takes the number of indices in our mesh and the number of instances kNumMeshes.
    buf.cmdBindRenderPipeline(pipelineSolid);
    buf.cmdBindDepthState({ .compareOp = lvk::CompareOp_Less,
    .isDepthWriteEnabled = true });
    buf.cmdBindIndexBuffer(indexBuffer, lvk::IndexFormat_UI32);
    buf.cmdDrawIndexed(indices.size(), kNumMeshes);
    buf.cmdEndRendering();
    ctx->submit(buf, ctx->getCurrentSwapchainTexture());
    frameId = (frameId + 1) & 1;
    });

Now, let’s delve into the GLSL implementation details to understand how it works internally.

The first part is the compute shader, which prepares data for rendering. Let’s take a look at Chapter05/04_InstancedMeshes/src/main.comp:

  1. The compute shader processes 32 meshes in one local workgroup. Push constants are shared between the compute shader and the graphics pipeline. They are declared in an include file, Chapter05/04_InstancedMeshes/src/common.sp. We provide that file here for your convenience:
    layout(local_size_x = 32, local_size_y = 1, local_size_z = 1) in;
    // included from <Chapter05/04_InstancedMeshes/src/common.sp>
    layout(push_constant) uniform PerFrameData {
    mat4 viewproj;
    uint textureId;
    uvec2 bufPosAngleId;
    uvec2 bufMatricesId;
    uvec2 bufVerticesId;
    float time;
    };
    layout(std430, buffer_reference) readonly buffer Positions {
    vec4 pos[]; // pos, initialAngle
    };
    // end of #include
  2. The matrices buffer reference is not shared. In the compute shader, it is declared as writeonly, while in the vertex shader, it will be declared as readonly.
    layout(std430, buffer_reference) writeonly buffer Matrices {
    mat4 mtx[];
    };
  3. The helper functions translate() and rotate() mimic the glm::translate() and glm::rotate() C++ functions in GLSL. They are reused in their entirety from the previous recipe, Rendering instanced geometry. Since they are quite long, we won’t duplicate them here.
    mat4 translate(mat4 m, vec3 v);
    mat4 rotate(mat4 m, float angle, vec3 v);
  4. The main() function reads a vec4 value containing the vec3 center point and initial angle, and calculates a model matrix. This is the same computation we did in the vertex shader in the previous recipe. The model matrix is then stored in a storage buffer referenced by bufMatricesId.
    void main() {
    uint idx = gl_GlobalInvocationID.x;
    vec4 center = Positions(bufPosAngleId).pos[idx];
    mat4 model = rotate(translate(mat4(1.0f),
    center.xyz), time + center.w, vec3(1.0f, 1.0f, 1.0f));
    Matrices(bufMatricesId).mtx[idx] = model;
    }

On to the rendering pipeline shaders… As we moved most of the calculations into the compute shader, the shaders for the rendering pipeline became significantly shorter.

  1. The vertex shader uses the same shared declarations for push constants and buffer references:
    #include <Chapter05/04_InstancedMeshes/src/common.sp>
    layout (location=0) out vec2 uv;
    layout (location=1) out vec3 normal;
    layout (location=2) out vec3 color;
    layout(std430, buffer_reference) readonly buffer Matrices {
    mat4 mtx[];
    };
  2. The vertex data contains normal vectors, as was declared in the C++ code earlier in this recipe:
    struct Vertex {
    float x, y, z;
    float u, v;
    float nx, ny, nz;
    };
    layout(std430, buffer_reference) readonly buffer Vertices {
    Vertex in_Vertices[];
    };
  3. The vertex data is fetched from the “vertex” storage buffer, and the model matrix is retrieved from the matrices buffer, which was updated by the compute shader:
    const vec3 colors[3] = vec3[3](vec3(1.0, 0.0, 0.0),
    vec3(0.0, 1.0, 0.0),
    vec3(1.0, 1.0, 1.0));
    void main() {
    Vertex vtx = Vertices(bufVerticesId).in_Vertices[gl_VertexIndex];
    mat4 model = Matrices(bufMatricesId).mtx[gl_InstanceIndex];
  4. Now we can compute the value of gl_Position and pass the normal vector and texture coordinates to the fragment shader:
    const float scale = 10.0;
    gl_Position = viewproj * model *
    vec4(scale * vtx.x, scale * vtx.y, scale * vtx.z, 1.0);
    mat3 normalMatrix = transpose( inverse(mat3(model)) );
    uv = vec2(vtx.u, vtx.v);
    normal = normalMatrix * vec3(vtx.nx, vtx.ny, vtx.nz);
    color = colors[gl_InstanceIndex % 3];
    }
  5. The fragment shader is fairly straightforward. We perform some improvised diffuse lighting calculations to enhance the visual distinctiveness of the meshes:
    layout (location=0) in vec2 uv;
    layout (location=1) in vec3 normal;
    layout (location=2) in vec3 color;
    layout (location=0) out vec4 out_FragColor;
    layout(push_constant) uniform PerFrameData {
    mat4 viewproj;
    uint textureId;
    };
    void main() {
    vec3 n = normalize(normal);
    vec3 l = normalize(vec3(1.0, 0.0, 1.0));
    float NdotL = clamp(dot(n, l), 0.3, 1.0);
    out_FragColor =
    textureBindless2D(textureId, 0, uv) * NdotL * vec4(color, 1.0);
    };

The running demo application should display a swarm of rotating ducks, as shown in the following screenshot, with the camera flying back and forth through them.

Figure 5.4: A swarm of rotating ducks using instanced rendering

As you may have noticed, this demo uses only 32'768 instances compared to 1 million in the previous recipe. The difference is due to the cube in the previous example having just 36 indices, while the rubber duck model used here has 33'216 —nearly one thousand times more.

The naïve brute-force approach won’t work for this dataset. To render 1 million duckies, we need to use additional techniques such as culling and GPU-level-of-detail management. We’ll touch some of these topics in Chapter 11.

Now, let’s switch gears and learn how to render debug grid geometry before moving on to examples of more complex mesh rendering.

In the previous recipes of this chapter, we explored some approaches to geometry rendering. When debugging applications, it’s helpful to have a visible representation of the coordinate system, allowing viewers to quickly infer the camera’s orientation and position by examining the rendered image. A practical way to represent a coordinate system is by rendering an infinite grid aligned with one of the coordinate planes. Let’s learn how to implement a visually appealing grid in GLSL.

The complete C++ source code for this recipe is available in Chapter05/05_Grid. The accompanying GLSL shaders, which will be reused in later recipes, are stored in the shared data folder under data/shaders/Grid.vert and data/shaders/Grid.frag.

To parameterize our grid, we should introduce some constants. These constants can be found and adjusted in the data/shaders/GridParameters.h GLSL include file. Let’s take a look inside:

  1. First, we need to define the size of our grid extents in world coordinates. This determines how far from the camera the grid is visible:
    float gridSize = 100.0;
  2. The size of one grid cell is specified in the same units as the grid size:
    float gridCellSize = 0.025;
  3. Let’s define the colors for the grid lines. We’ll use two different colors: one for regular thin lines and another for thick lines, which are rendered every tenth line. Since everything is rendered against a white background, black and 50% gray will work well.
    vec4 gridColorThin = vec4(0.5, 0.5, 0.5, 1.0);
    vec4 gridColorThick = vec4(0.0, 0.0, 0.0, 1.0);
  4. Our grid implementation will adjust the number of rendered lines based on the grid LOD. We will switch the LOD when the number of pixels between two adjacent grid cell lines drops below a certain threshold, which is calculated in the fragment shader:
    const float gridMinPixelsBetweenCells = 2.0;
  5. Let’s take a look at a simple vertex shader, data/shaders/Grid.vert, which we use to generate and transform grid vertices. It takes in the current model-view-projection matrix, the current camera position, and the grid origin. The origin is in world space and can be used to move the grid around.
    #version 460 core
    #include <data/shaders/GridParameters.h>
    layout(push_constant) uniform PerFrameData {
    mat4 MVP;
    vec4 cameraPos;
    vec4 origin;
    };
    layout (location=0) out vec2 uv;
    layout (location=1) out vec2 out_camPos;
    const vec3 pos[4] = vec3[4](
    vec3(-1.0, 0.0, -1.0),
    vec3( 1.0, 0.0, -1.0),
    vec3( 1.0, 0.0, 1.0),
    vec3(-1.0, 0.0, 1.0)
    );
    const int indices[6] = int[6]( 0, 1, 2, 2, 3, 0 );
  6. The built-in gl_VertexIndex variable is used to access hardcoded quad indices and the vertices in pos[]. The -1 to +1 points are scaled by the desired grid size. The resulting vertex position is then translated by the 2D camera position in the horizontal plane and, finally, by the 3D origin position:
    void main() {
    int idx = indices[gl_VertexIndex];
    vec3 position = pos[idx] * gridSize;
    position.x += cameraPos.x;
    position.z += cameraPos.z;
    position += origin.xyz;
    out_camPos = cameraPos.xz;
    gl_Position = MVP * vec4(position, 1.0);
    uv = position.xz;
    }

The fragment shader, data/shaders/Grid.frag, is somewhat more complex. It calculates a programmatic texture that resembles a grid. The grid lines are rendered based on how quickly the UV coordinates change in screen space to avoid the Moiré pattern. For this, we’ll need screen space derivatives. The screen space derivative of a variable in your shader measures how much that variable changes from one pixel to the next. The GLSL function dFdx() represents the horizontal change, while dFdy() represents the vertical change. These functions measure how fast a GLSL variable changes as you move across the screen, approximating partial derivatives in calculus. This approximation comes from relying on discrete samples at each fragment, rather than performing a full mathematical evaluation of the change:

  1. First, we introduce several GLSL helper functions to assist with our calculations. These can be found in data/shaders/GridCalculation.h. The function names satf() and satv() stand for saturate-float and saturate-vector, respectively:
    float log10(float x) {
    return log(x) / log(10.0);
    }
    float satf(float x) {
    return clamp(x, 0.0, 1.0);
    }
    vec2 satv(vec2 x) {
    return clamp(x, vec2(0.0), vec2(1.0));
    }
    float max2(vec2 v) {
    return max(v.x, v.y);
    }
  2. Let’s take a look at the gridColor() function, which is called from main(), and begin by calculating the screen space length of the derivatives of the UV coordinates we previously generated in the vertex shader. We use the built-in dFdx() and dFdy() functions to calculate the necessary derivatives:
    vec4 gridColor(vec2 uv, vec2 camPos) {
    vec2 dudv = vec2( length(vec2(dFdx(uv.x), dFdy(uv.x))),
    length(vec2(dFdx(uv.y), dFdy(uv.y))) );
  3. Knowing the derivatives, the current LOD of our grid can be calculated in the following way. The gridMinPixelsBetweenCells value controls how fast we want our LOD to increase. In this case, it is the minimum number of pixels between two adjacent cell lines of the grid:
    float lodLevel = max(0.0, log10((length(dudv) *
    gridMinPixelsBetweenCells) / gridCellSize) + 1.0);
    float lodFade = fract(lodLevel);

Besides the LOD value, we are going to need a fading factor to render smooth transitions between the adjacent levels. It can be obtained by taking a fractional part of the floating point LOD level. The logarithm base 10 is used to ensure each LOD covers pow(10, lodLevel) more cells than the previous size.

  1. The LOD levels are blended with each other. To render them, we have to calculate the cell size for each LOD. Here, instead of calculating pow() three times, we can calculate it only for lod0 and multiply each subsequent LOD cell size by 10.0:
    float lod0 = gridCellSize * pow(10.0, floor(lodLevel));
    float lod1 = lod0 * 10.0;
    float lod2 = lod1 * 10.0;
  2. To be able to draw anti-aliased lines using alpha transparency, we need to increase the screen coverage of our lines. Let’s make sure each line covers up to 4 pixels. Shift grid coordinates to the centers of anti-aliased lines for subsequent alpha calculations:
    dudv *= 4.0;
    uv += dudv * 0.5;
  3. Now we should get coverage alpha value corresponding to each calculated LOD level. To do that, we calculate absolute distances to cell line centers for each LOD and pick the maximum coordinate:
    float lod0a = max2( vec2(1.0) - abs(
    satv(mod(uv, lod0) / dudv) * 2.0 - vec2(1.0)) );
    float lod1a = max2( vec2(1.0) - abs(
    satv(mod(uv, lod1) / dudv) * 2.0 - vec2(1.0)) );
    float lod2a = max2( vec2(1.0) - abs(
    satv(mod(uv, lod2) / dudv) * 2.0 - vec2(1.0)) );
  4. Non-zero alpha values represent non-empty transition areas of the grid. Let’s blend between them using two colors to handle LOD transitions:
    vec4 c = lod2a > 0.0 ?
    gridColorThick :
    lod1a > 0.0 ?
    mix(gridColorThick, gridColorThin, lodFade) : gridColorThin;
  5. Last but not least, make the grid disappear when it is far away from the camera. Use the gridSize value to calculate the opacity falloff:
    uv -= camPos;
    float opacityFalloff = (1.0 - satf(length(uv) / gridSize));
  6. Now we can blend between the LOD level alpha values and scale the result with the opacity falloff factor. The resulting pixel color value can be stored in the framebuffer:
    c.a *= lod2a > 0.0 ?
    lod2a : lod1a > 0.0 ? lod1a : (lod0a * (1.0-lodFade));
    c.a *= opacityFalloff;
    return c;
    }
  7. The shaders mentioned earlier in data/shaders/GridCalculation.h should be rendered using the following render pipeline state, which is created in Chapter05/05_Grid/src/main.cpp:
    Holder<RenderPipelineHandle> pipeline =
    ctx->createRenderPipeline({
    .smVert = vert,
    .smFrag = frag,
    .color = { {
    .format = ctx->getSwapchainFormat(),
    .blendEnabled = true,
    .srcRGBBlendFactor = lvk::BlendFactor_SrcAlpha,
    .dstRGBBlendFactor = lvk::BlendFactor_OneMinusSrcAlpha,
    } },
    .depthFormat = app.getDepthFormat() });
  8. The C++ rendering code in the same file looks as follows:
    buf.cmdBindRenderPipeline(pipeline);
    buf.cmdBindDepthState({});
    struct {
    mat4 mvp;
    vec4 camPos;
    vec4 origin;
    } pc = {
    .mvp = glm::perspective(
    45.0f, aspectRatio, 0.1f, 1000.0f) * app.camera_.getViewMatrix(),
    .camPos = vec4(app.camera_.getPosition(), 1.0f),
    .origin = vec4(0.0f),
    };
    buf.cmdPushConstants(pc);
    buf.cmdDraw(6);

Check out the complete Chapter05/05_Grid for a self-contained demo app. The camera can be controlled with the WASD keys and a mouse. The resulting image should look like in the following screenshot:

Figure 5.5: GLSL grid

Besides considering only the distance to the camera to calculate the antialiasing falloff factor, we can use the angle between the viewing vector and the grid line. This will make the overall look and feel of the grid more visually pleasing and can be an interesting improvement if you want to implement a grid not only as an internal debugging tool but also as a part of a customer-facing product, like an editor.

This implementation was inspired by the Our Machinery blog. Unfortunately, it is not available anymore. However, there are some other advanced materials available on the Internet showing how to render a more complex grid suitable for customer-facing rendering. Make sure you read the blog post The Best Darn Grid Shader (Yet) by Ben Golus https://bgolus.medium.com/the-best-darn-grid-shader-yet-727f9278b9d8, which takes grid rendering a lot further.

Before moving on to the next recipe, it’s worth noting that grid rendering is quite useful, and we’ve incorporated it into most of our subsequent demo applications. You can use the VulkanApp::drawGrid() function from shared/VulkanApp.cpp to render the grid wherever needed. This version supports MSAA multisampling, which will be used in Chapters 10 and 11.

Integrating tessellation into the graphics pipeline

Section titled “Integrating tessellation into the graphics pipeline”

Let’s switch gears and learn how to integrate hardware tessellation into our Vulkan graphics rendering pipeline. Hardware tessellation consists of two new shader stages in the graphics pipeline. The first stage is called the tessellation control shader (TCS), and the second is the tessellation evaluation shader (TES). The tessellation control shader works with a set of vertices, known as control points, which define a geometric surface referred to as a patch. This shader can modify the control points and determine the level of tessellation required. The tessellation evaluation shader then uses the barycentric coordinates of the tessellated triangles to interpolate per-vertex attributes like texture coordinates and colors. Let’s dive into the code to see how these stages can be used to dynamically triangulate a mesh based on the camera’s distance.

While tessellation shaders are a powerful tool for hardware tessellation, they may not be as efficient as using mesh shaders on modern GPUs. Unfortunately, as of the time this book was written, Vulkan does not have a standardized API for mesh shaders in its core specification. Therefore, for now, we will stick with the traditional tessellation approach to manage mesh triangulation.

The complete source code for this recipe is located in Chapter05/06_Tessellation.

Now, we want to write GLSL shaders that calculate per-vertex tessellation levels based on the distance from the camera. This will allow us to render more geometric detail in areas closer to the viewer. To get started, we’ll begin with the vertex shader in Chapter05/06_Tessellation/src/main.vert, which will compute the world positions of the vertices and pass them to the tessellation control shader:

  1. Our per-frame data includes the usual view and projection matrices, the current camera position in world space, and the tessellation scaling factor, which the user can control via an ImGui widget. Since this data doesn’t fit within 128 bytes of push constants, we store everything in a buffer. The geometry is accessed using the PVP technique and stored in the following format: vertex positions are stored as 3 floats, and texture coordinates as 2 floats:
    // included from <Chapter05/06_Tessellation/src/common.sp>
    struct Vertex {
    float x, y, z;
    float u, v;
    };
    layout(std430, buffer_reference) readonly buffer Vertices {
    Vertex in_Vertices[];
    };
  2. The PerFrameData structure is the same across all shader stages in this example.
    layout(std430, buffer_reference) readonly buffer PerFrameData {
    mat4 model;
    mat4 view;
    mat4 proj;
    vec4 cameraPos;
    uint texture;
    float tesselationScale;
    Vertices vtx;
    };
    layout(push_constant) uniform PushConstants {
    PerFrameData pc;
    };
  3. Let’s write some helper functions to access vertex positions and texture coordinates using the standard GLSL data types:
    vec3 getPosition(int i) {
    return vec3(pc.vtx.in_Vertices[i].x,
    pc.vtx.in_Vertices[i].y,
    pc.vtx.in_Vertices[i].z);
    }
    vec2 getTexCoord(int i) {
    return vec2(pc.vtx.in_Vertices[i].u,
    pc.vtx.in_Vertices[i].v);
    }
  4. The vertex shader outputs UV texture coordinates and per-vertex world positions. The calculation is done as follows:
    layout (location=0) out vec2 uv_in;
    layout (location=1) out vec3 worldPos_in;
    void main() {
    vec4 pos = vec4(getPosition(gl_VertexIndex), 1.0);
    gl_Position = pc.proj * pc.view * pc.model * pos;
    uv_in = getTexCoord(gl_VertexIndex);
    worldPos_in = (pc.model * pos).xyz;
    }

Next, let’s move on to the next shader stage and take a look at the tessellation control shader in Chapter05/06_Tessellation/src/main.tesc:

  1. The shader operates on a group of 3 vertices, each corresponding to a single triangle in the input data. The uv_in[] and worldPos_in[] variables correspond to those in the vertex shader. Notice that here we have arrays instead of single values.
    #include <Chapter05/06_Tessellation/src/common.sp>
    layout (vertices = 3) out;
    layout (location = 0) in vec2 uv_in[];
    layout (location = 1) in vec3 worldPos_in[];
  2. Let’s describe the input and output data structures that correspond to each individual vertex. Besides the required vertex position, we store vec2 texture coordinates:
    in gl_PerVertex {
    vec4 gl_Position;
    } gl_in[];
    out gl_PerVertex {
    vec4 gl_Position;
    } gl_out[];
    struct vertex {
    vec2 uv;
    };
    struct vertex {
    vec2 uv;
    };
    layout(location = 0) out vertex Out[];
  3. The getTessLevel() function calculates the desired tessellation level based on the distance of two adjacent vertices from the camera. The hardcoded distance values that are used to switch the levels are scaled using the tessellationScale uniform coming from the UI:
    float getTessLevel(float distance0, float distance1) {
    const float distanceScale1 = 1.2;
    const float distanceScale2 = 1.7;
    const float avgDistance =
    (distance0 + distance1) / (2.0 * pc.tesselationScale);
    if (avgDistance <= distanceScale1) return 5.0;
    if (avgDistance <= distanceScale2) return 3.0;
    return 1.0;
    }
  4. The main() function is straightforward. It simply passes the positions and UV coordinates as they are, then calculates the distance from each vertex in the triangle to the camera:
    void main() {
    gl_out[gl_InvocationID].gl_Position =
    gl_in[gl_InvocationID].gl_Position;
    Out[gl_InvocationID].uv = uv_in[gl_InvocationID];
    vec3 c = pc.cameraPos.xyz;
    float eyeToVertexDistance0 = distance(c, worldPos_in[0]);
    float eyeToVertexDistance1 = distance(c, worldPos_in[1]);
    float eyeToVertexDistance2 = distance(c, worldPos_in[2]);
  5. Based on these distances, we can calculate the required inner and outer tessellation levels in the following way. The inner tessellation level defines how the inner part of a triangle is subdivided into smaller triangles. The outer level defines how the outer edges of the triangle are subdivided so that they can be correctly connected to adjacent triangles:
    gl_TessLevelOuter[0] =
    getTessLevel(eyeToVertexDistance1, eyeToVertexDistance2);
    gl_TessLevelOuter[1] =
    getTessLevel(eyeToVertexDistance2, eyeToVertexDistance0);
    gl_TessLevelOuter[2] =
    getTessLevel(eyeToVertexDistance0, eyeToVertexDistance1);
    gl_TessLevelInner[0] = gl_TessLevelOuter[2];
    };

Let’s take a look at the tessellation evaluation shader Chapter05/06_Tessellation/src/main.tese:

  1. We should specify triangles as the input. The equal_spacing spacing mode tells Vulkan that the tessellation level n should be clamped to the range 0...64 and rounded to the nearest integer. After that, the corresponding edge should be divided into n equal segments. When the tessellation primitive generator produces triangles, the orientation of triangles can be specified by an input layout declaration using the identifiers cw and ccw. We use the counter-clockwise orientation:
    layout(triangles, equal_spacing, ccw) in;
    struct vertex {
    vec2 uv;
    };
    in gl_PerVertex {
    vec4 gl_Position;
    } gl_in[];
    layout(location = 0) in vertex In[];
    out gl_PerVertex {
    vec4 gl_Position;
    };
    layout (location=0) out vec2 uv;
  2. These two helper functions are useful for interpolating between the vec2 and vec4 attribute values at the corners of the original triangle, using the barycentric coordinates of the current vertex. The built-in gl_TessCoord variable contains the required barycentric coordinates, ranging from 0 to 1:
    vec2 interpolate2(in vec2 v0, in vec2 v1, in vec2 v2) {
    return v0 * gl_TessCoord.x +
    v1 * gl_TessCoord.y +
    v2 * gl_TessCoord.z;
    }
    vec4 interpolate4(in vec4 v0, in vec4 v1, in vec4 v2) {
    return v0 * gl_TessCoord.x +
    v1 * gl_TessCoord.y +
    v2 * gl_TessCoord.z;
    }
  3. The actual interpolation code in main() is straightforward and can be written in the following way:
    void main() {
    gl_Position = interpolate4(gl_in[0].gl_Position,
    gl_in[1].gl_Position,
    gl_in[2].gl_Position);
    uv = interpolate2(In[0].uv, In[1].uv, In[2].uv);
    };

The next stage of our hardware tessellation graphics pipeline is the geometry shader Chapter05/06_Tessellation/src/main.geom. We use it to generate new barycentric coordinates for all the small tessellated triangles. It is used to render a nice antialiased wireframe overlay on top of our colored mesh, as we did earlier in this chapter in the Generating level-of-detail meshes using MeshOptimizer recipe:

  1. The geometry shader processes the triangles generated by the hardware tessellator and outputs triangle strips, each containing a single triangle:
    #version 460 core
    layout(triangles) in;
    layout(triangle_strip, max_vertices = 3) out;
    layout(location=0) in vec2 uv[];
    layout(location=0) out vec2 uvs;
    layout(location=1) out vec3 barycoords;
  2. Barycentric coordinates are assigned per vertex using these hardcoded constants:
    void main() {
    const vec3 bc[3] = vec3,
    vec3(0.0, 1.0, 0.0),
    vec3(0.0, 0.0, 1.0) );
    for ( int i = 0; i < 3; i++ ) {
    gl_Position = gl_in[i].gl_Position;
    uvs = uv[i];
    barycoords = bc[i];
    EmitVertex();
    }
    EndPrimitive();
    }

The final stage of this rendering pipeline is the fragment shader Chapter05/06_Tessellation/src/main.frag:

  1. We take in the barycentric coordinates from the geometry shader and use them to calculate a wireframe overlay covering our mesh:
    #include <Chapter05/06_Tessellation/src/common.sp>
    layout(location=0) in vec2 uvs;
    layout(location=1) in vec3 barycoords;
    layout(location=0) out vec4 out_FragColor;
  2. The edgeFactor() helper function returns the blending factor based on the distance to the edge and the desired thickness of the wireframe contour. Essentially, when one of the 3 barycentric coordinate values is close to 0, it indicates that the current fragment is near one of the triangle’s edges. The distance to zero controls the visible thickness of a rendered edge:
    float edgeFactor(float thickness) {
    vec3 a3 = smoothstep( vec3(0.0),
    fwidth(barycoords) * thickness, barycoords);
    return min( min( a3.x, a3.y ), a3.z );
    }
  3. Let’s sample the texture using the provided UV values and call it a day:
    void main() {
    vec4 color = textureBindless2D(pc.texture, 0, uvs);
    out_FragColor = mix( vec4(0.1), color, edgeFactor(0.75) );
    }

The GLSL shader part of our Vulkan hardware tessellation pipeline is over, and it is time to look into the C++ code. The source code is located in the Chapter05/06_Tessellation/src/main.cpp file:

  1. The shaders for the tessellated mesh rendering are loaded the following way:
    Holder<ShaderModuleHandle> vert =
    loadShaderModule(ctx, "Chapter05/06_Tessellation/src/main.vert");
    Holder<ShaderModuleHandle> tesc =
    loadShaderModule(ctx, "Chapter05/06_Tessellation/src/main.tesc");
    Holder<ShaderModuleHandle> geom =
    loadShaderModule(ctx, "Chapter05/06_Tessellation/src/main.geom");
    Holder<ShaderModuleHandle> tese =
    loadShaderModule(ctx, "Chapter05/06_Tessellation/src/main.tese");
    Holder<ShaderModuleHandle> frag =
    loadShaderModule(ctx, "Chapter05/06_Tessellation/src/main.frag");
  2. Then, we should create a corresponding rendering pipeline:
    Holder<RenderPipelineHandle> pipelineSolid =
    ctx->createRenderPipeline({
    .topology = lvk::Topology_Patch,
    .smVert = vert,
    .smTesc = tesc,
    .smTese = tese,
    .smGeom = geom,
    .smFrag = frag,
    .color = { { .format = ctx->getSwapchainFormat() } },
    .depthFormat = app.getDepthFormat(),
    .patchControlPoints = 3,
    });;

The data/rubber_duck/scene.gltf mesh loading code is identical to that from the previous recipes, so we’ll skip it here. What’s more important is how we render the mesh and ImGui widget to control the tessellation scale factor. Let’s take a look at the body of the rendering loop:

  1. First, we calculate model-view-projection matrices for our mesh:
    const mat4 m = glm::rotate(mat4(1.0f),
    glm::radians(-90.0f), vec3(1, 0, 0));
    const mat4 v = glm::rotate(glm::translate(mat4(1.0f),
    vec3(0.0f, -0.5f, -1.5f)),
    (float)glfwGetTime(), vec3(0.0f, 1.0f, 0.0f));
    const mat4 p = glm::perspective(45.0f, aspectRatio, 0.1f, 1000.0f);
  2. Next, per-frame data is uploaded into the bufferPerFrame. To avoid any extra synchronization and because the data size is small, we can use the vkCmdUpdateBuffer() function wrapped in cmdUpdateBuffer(). This stores the buffer data directly in the Vulkan command buffer memory before uploading and supports updates of up to 65536 bytes.
    const PerFrameData pc = {
    .model = v * m,
    .view = app.camera_.getViewMatrix(),
    .proj = p,
    .cameraPos = vec4(app.camera_.getPosition(), 1.0f),
    .texture = texture.index(),
    .tessellationScale = tessellationScale,
    .vertices = ctx->gpuAddress(vertexBuffer),
    };
    lvk::ICommandBuffer& buf = ctx->acquireCommandBuffer();
    buf.cmdUpdateBuffer(bufferPerFrame, pc);
  3. As usual, push constants are used to pass the address of the bufferPerFrame buffer into the shaders. After that, we can render the mesh using our tessellation pipeline.
    buf.cmdBeginRendering(renderPass, framebuffer);
    buf.cmdPushConstants(ctx->gpuAddress(bufferPerFrame));
    buf.cmdBindIndexBuffer(indexBuffer, lvk::IndexFormat_UI32);
    buf.cmdBindRenderPipeline(pipelineSolid);
    buf.cmdBindDepthState({ .compareOp = lvk::CompareOp_Less,
    .isDepthWriteEnabled = true });
    buf.cmdDrawIndexed(indices.size());
  4. We render a grid on top, as described earlier in this chapter in the Implementing an infinite grid GLSL shader recipe. The origin is used to position the grid just below the duck model. Inside our frame rendering loop, we can access all our ImGui rendering functionality. Here, we render a single slider with a floating-point value for the tessellation scale factor:
    app.drawGrid(buf, p, vec3(0, -0.5f, 0));
    app.imgui_->beginFrame(framebuffer);
    ImGui::Begin("Camera Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize);
    ImGui::SliderFloat(
    "Tessellation scale", &tessellationScale, 0.7f, 1.2f, "%.1f");
    ImGui::End();
    app.imgui_->endFrame(buf);
    buf.cmdEndRendering();

Here is a screenshot from the running demo application:

Figure 5.6: Tessellated duck

Notice how the tessellation level changes based on the distance to the camera. Try adjusting the control slider or moving the camera around to emphasize the effect.

This recipe can be used as a cornerstone of hardware mesh tessellation techniques in your Vulkan applications. One natural step forward would be to apply a displacement map to the fine-grained tessellated vertices using the direction of normal vectors. Check out this page for further inspiration: https://www.geeks3d.com/20100804/test-opengl-4-tessellation-with-displacement-mapping. For those who want to go serious on adaptive tessellation of subdivision surfaces, there is a chapter in the GPU Gems 2 book covering this advanced topic in great detail. It is now available online at https://developer.nvidia.com/gpugems/gpugems2/part-i-geometric-complexity/chapter-7-adaptive-tessellation-subdivision-surfaces.

In the previous chapters, we used fixed, hardcoded vertex formats for our meshes, which changed between demos, and also implicitly included the material description. For example, a hardcoded texture was used to provide color information. A triangle mesh is defined by indices and vertices, with each vertex consisting of a set of attributes with distinct data formats that correspond to the lvk::VertexInput vertex input description. All auxiliary physical properties of an object, such as collision detection data, mass, and moments of inertia, can be represented by a mesh, while other information, like surface material properties, can be stored outside the mesh as external metadata. It’s also worth noting that small 3D models, like the rubber duck we used earlier, can be loaded quite quickly.

However, larger and more intricate real-world 3D models, especially when using transmission formats like .gltf, may take several minutes to load. Using a runtime mesh format can address this issue by eliminating the need for parsing and instead loading flat buffers that match the internal rendering data structures. This involves using fast I/O functions like fread() and similar mechanisms.

Let’s define a unified mesh storage format that covers most of the use cases for the rest of this book.

The full corresponding source code can be found in the header file shared/Scene/VtxData.h. Make sure you’ve read Chapter 2 before going forward.

A vector of homogeneous vertex attributes stored contiguously is called a vertex stream. Examples of such attributes are vertex positions, texture coordinates, and normal vectors, each of the three representing one attribute. Each stream must have a format. Vertex positions are vec3, texture coordinates can be vec2, normal vectors can use the packed format Int_2_10_10_10_REV, and so on.

Let’s define a LOD as an index buffer of reduced size that uses existing vertices and hence can be used directly for rendering with the original vertex buffer. We learned how to create LODs earlier in this chapter in the Generating level-of-detail meshes using MeshOptimizer recipe.

We define a mesh as a collection of all vertex data streams and a collection of all index buffers, one for each LOD. The number of elements in each vertex data stream is the same and is called the “vertex count”, which we will encounter in the code below. To make things a bit simpler, we always use 32-bit offsets and indices for our data.

All the vertex data streams and LOD index buffers are packed into a single blob. This allows us to load the data with a single fread() call or even use memory mapping for direct data access. This simple vertex data representation also enables direct upload of meshes to the GPU. What makes it particularly useful is the ability to merge data for multiple meshes into a single file. Alternatively, this can be done by consolidating the data into two large buffers — one for indices and the other for vertex attributes. This will be especially handy later when we discuss how to implement an LOD switching technique on the GPU.

In this recipe, we will focus solely on geometrical data. The LOD creation process is covered in the recipe Generating level-of-detail meshes using MeshOptimizer, and the material data export process is covered in the following chapters. Let’s take a look at shared/Scene/VtxData.h and declare the main data structures for our mesh:

  1. First, we need to define an individual mesh description. We deliberately avoid using pointers, as they obscure memory allocations and complicate the saving and loading of data. Instead, we store offsets to individual data streams and LOD index buffers. These offsets function similarly to pointers but are more flexible and, importantly, more GPU-friendly. All offsets in the Mesh structure are given relative to the beginning of the data block. Let’s declare our main data structure for a mesh. It includes the number of LODs and vertex data streams.

The LOD count, with the original mesh counting as one of the LODs, must be strictly less than kMaxLODs, as we don’t store LOD index buffer sizes directly but calculate them from the offsets. To calculate these sizes, we store an extra empty LOD level at the end. The number of vertex data streams is stored directly, without any modifications.

constexpr const uint32_t kMaxLODs = 8;
struct Mesh final {
uint32_t lodCount = 1;
uint32_t indexOffset = 0;
uint32_t vertexOffset = 0;
  1. The vertexCount field contains the total number of vertices in this mesh. This number is described the content of the vertex buffer and can be greater than the number of vertices on any individual level of detail. We postpone the question of material data storage to the next chapters. To do this in an elegant manner, let’s introduce one extra level of indirection. The materialID field contains an abstract identifier that allows us to reference any material data stored elsewhere:
    uint32_t vertexCount = 0;
    uint32_t materialID = 0;
  2. Each mesh can potentially be displayed at different LODs. The file contains all indices for all levels of detail and offsets for the beginning of each LOD are stored in the lodOffset array. This array contains one extra item at the end, which serves as a marker to calculate the size of the last LOD:
    uint32_t lodOffset[kMaxLODs+1] = { 0 };
  3. Instead of storing the number of indices of each LOD, we define a little helper function to calculate that number from individual offsets:
    uint32_t getLODIndicesCount(uint32_t lod) const {
    return lod < lodCount ? lodOffset[lod + 1] - lodOffset[lod] : 0;
    }
    };

As you might have noticed, the Mesh structure is essentially an index into other buffers containing data, such as index and vertex buffers. Let’s take a look at that data container:

  1. The format of the vertex streams is described by the structure lvk::VertexInput. We already used it in Chapter 2. This form of vertex stream description allows very flexible storage.
    struct MeshData {
    lvk::VertexInput streams = {};
  2. The actual index and vertex buffer data are stored in these containers. They can accommodate multiple meshes. We use only 32-bit indices in our book for the sake of simplicity.
    std::vector<uint32_t> indexData;
    std::vector<uint8_t> vertexData;
  3. Another std::vector stores each individual mesh description:
    std::vector<Mesh> meshes;
  4. For completeness, we’ll also store a bounding box for each mesh right here. Bounding boxes are extremely useful for culling, and having them pre-calculated can significantly speed up the loading process. Materials and textures are also stored here, but they’ll be covered in the subsequent chapters.
    std::vector<BoundingBox> boxes;
    std::vector<Material> materials;
    std::vector<std::string> textureFiles;
    };

Important note

The proposed schema supports both interleaved and non-interleaved vertex data storage formats by making use of the stride parameter in lvk::VertexInput::VertexInputBinding. One major drawback is that we have to account for this data reorganization in all the programmable vertex-pulling code in our shaders when we don’t use the normal Vulkan vertex input. If you’re developing production code, make sure to profile which storage format works faster on your target hardware before committing to one particular approach.

Before we can store these Mesh data structures in a file, we require some sort of a file header:

  1. To ensure data integrity and to check the validity of the header, a magic hexadecimal value of 0x12345678 is stored in the first 4 bytes of the header:
    struct MeshFileHeader {
    uint32_t magicValue = 0x12345678;
  2. The number of individual Mesh descriptors in this file is stored in the meshCount field:
    uint32_t meshCount = 0;
  3. The last two member fields store the sizes of index and vertex data in bytes, respectively. These values come in handy when checking the integrity of a mesh file as well:
    uint32_t indexDataSize = 0;
    uint32_t vertexDataSize = 0;
    };

The file continues with the list of Mesh structures. After the header and a list of individual mesh descriptors, we store a large index and vertex data block, which can be loaded all at once.

Let’s go through the pseudocode from shared/Scene/VtxData.cpp for loading such a file is just a few fread() calls that look as follows. Error checks are omitted from the book text but are present in the actual code:

  1. First, we read the file header with the mesh count. Error checks are skipped here in the book but are present in the bundled source code:
    MeshFileHeader loadMeshData(const char* meshFile, MeshData& out) {
    FILE* f = fopen(meshFile, "rb");
    SCOPE_EXIT { fclose(f); };
    MeshFileHeader header;
    fread(&header, 1, sizeof(header), f)
    fread(&out.streams, 1, sizeof(out.streams), f);
  2. Having read the header, we resize the mesh descriptors array and read in all Mesh descriptions:
    out.meshes.resize(header.meshCount);
    fread(out.meshes.data(), sizeof(Mesh), header.meshCount, f);
    out.boxes.resize(header.meshCount);
    fread(out.boxes.data(), sizeof(BoundingBox), header.meshCount, f);
  3. Then we read the main geometry data blocks for this mesh, which contain the actual index and vertex data:
    out.indexData.resize(header.indexDataSize / sizeof(uint32_t));
    out.vertexData.resize(header.vertexDataSize);
    fread(out.indexData.data(), 1, header.indexDataSize, f);
    fread(out.vertexData.data(), 1, header.vertexDataSize, f);
    return header;
    };

Alternatively, index and vertex buffers can be combined into a single large byte buffer. We leave this as an exercise for our readers.

Later on, the indexData and vertexData containers can be directly uploaded to the GPU. We’ll revisit this idea in the subsequent recipes in this chapter.

Although you can see the result of this code in the demo app Chapter05/07_MeshRenderer for this chapter, there are some additional functionalities that need to be implemented. Let’s cover a few more topics before we can run and witness the demo.

This geometry data format is pretty simple and straightforward for the purpose of storing static mesh data. If the meshes may be changed, reloaded, or loaded asynchronously, we may store separate meshes in dedicated files.

Since it is impossible to predict all the use cases and since this book is all about the rendering and not some general gaming engine creation, it is up to the reader to make decisions on adding extra features such as mesh skinning or others. One simple example of such a decision is the addition of material data directly into the mesh file. Technically, all we need to do is add a materialCount field to MeshFileHeader and store a list of material descriptions right after the list of meshes. Even such a simple thing immediately raises more questions. Should we pack texture data in the same file? If yes, how complex should the texture format be? What material model should we use? And so on, and so forth. For now, we just leave mesh geometry data separated from material descriptions. We will come back to materials in subsequent chapters.

Implementing automatic geometry conversion

Section titled “Implementing automatic geometry conversion”

In the previous chapters, we learned how to use the Assimp library to load and render 3D models stored in different file formats. In real-world graphics applications, the process of loading a model can be tedious and multistage. Besides just loading, we might want to optimize a mesh in some specific way, such as optimizing geometry and computing multiple LOD meshes. This process might become slow for sizable meshes, so it makes perfect sense to preprocess meshes offline, before an application starts, and load them later in the app as described in the previous recipe, Organizing mesh data storage. Let’s learn how to implement a simple framework for automatic geometry preprocessing and conversion.

In the previous edition of this book, we created a standalone tool for geometry conversion that needs to be executed before subsequent demo apps can load the converted data. It turned out to be a significant oversight on our part because many readers dove straight into running the demo apps and then reported issues when things didn’t work out-of-the-box as they expected. Here, we have rectified that mistake. If an app requires converted data and cannot find it, it triggers all the necessary code to load the data from storage assets and convert it into our run-time format.

The source code for our geometry conversion framework is in Chapter05/07_MeshRenderer. Low-level loader functions are defined in shared/Scene/VtxData.cpp. The entire demo application is covered by multiple recipes from this chapter, including Organizing mesh data storage, Implementing automatic geometry conversion, and Indirect rendering in Vulkan.

Let us see how the Assimp library is used to export the mesh data and save it into the binary file using the data structures defined in the Organizing mesh data storage recipe:

  1. We start by exploring a function called convertAIMesh(), which converts the Assimp mesh representation into our run-time format and appends it to the referenced MeshData parameter. Global index and vertex offsets are updated as well. The function is quite lengthy, but we will explore it in full detail here. Error checks are omitted:
    Mesh convertAIMesh(const aiMesh* m, MeshData& meshData,
    uint32_t& indexOffset, uint32_t& vertexOffset)
    {
    const bool hasTexCoords = m->HasTextureCoords(0);
  2. The actual mesh geometry data are stored in two following arrays. We cannot output converted meshes one by one, at least not in a single-pass tool, because we do not know the total size of data in advance, so we allocate in-memory storage for all the data and then write these data blobs into the output file. We also need a reference to the global vertex buffer, where we would append new vertices from this aiMesh. The outLods container is for per-LOD index buffers. Then we just go through all vertices of aiMesh and convert them:
    std::vector<float> srcVertices;
    std::vector<uint32_t> srcIndices;
    std::vector<uint8_t>& vertices = meshData.vertexData;
    std::vector<std::vector<uint32_t>> outLods;
  3. For this recipe, we assume there is a single LOD and that all the vertex data is stored as a continuous data stream. In other words, we have an interleaved storage of the data. We also ignore all the material information and deal exclusively with the index and vertex data for now.
    for (size_t i = 0; i != m->mNumVertices; i++) {
    const aiVector3D v = m->mVertices[i];
    const aiVector3D n = m->mNormals[i];
    const aiVector2D t = !hasTexCoords ? aiVector2D() : aiVector2D(
    m->mTextureCoords[0][i].x,
    m->mTextureCoords[0][i].y);
    if (g_calculateLODs) {
    srcVertices.push_back(v.x);
    srcVertices.push_back(v.y);
    srcVertices.push_back(v.z);
    }
  4. Once we have the stream data for the vertex, we can output it into the vertex buffer. The position v is stored as vec3. The texture coordinates uv are stored as half-float vec2 to save some space. The normal vector is converted into 2_10_10_10_REV, which has the size of uint32_t – not bad for 3 floats.

More information

put() is a templated function, which mem-copies the value from its second argument into a vector of uint8_t:

template <typename T> void put(
std::vector<uint8_t>& v, const T& value)
{
const size_t pos = v.size();
v.resize(v.size() + sizeof(value));
memcpy(v.data() + pos, &value, sizeof(value));
}
put(vertices, v);
put(vertices, glm::packHalf2x16(vec2(t.x, t.y)));
put(vertices, glm::packSnorm3x10_1x2(vec4(n.x, n.y, n.z, 0)));
}
  1. Describe the vertex streams for our demo: positions, texture coordinates, and normal vectors. The stride comes from the size of vec3 positions, half-float vec2 texture coordinates packed into uint32_t, and 2_10_10_10_REV normals packed into uint32_t.
    meshData.streams = {
    .attributes = {{ .location = 0,
    .format = lvk::VertexFormat::Float3,
    .offset = 0 },
    { .location = 1,
    .format = lvk::VertexFormat::HalfFloat2,
    .offset = sizeof(vec3) },
    { .location = 2,
    .format = lvk::VertexFormat::Int_2_10_10_10_REV,
    .offset = sizeof(vec3) + sizeof(uint32_t) } },
    .inputBindings = { { .stride =
    sizeof(vec3) + sizeof(uint32_t) + sizeof(uint32_t) } },
    };
  2. Go through all the mesh faces and create an index buffer:
    for (unsigned int i = 0; i != m->mNumFaces; i++) {
    if (m->mFaces[i].mNumIndices != 3) continue;
    for (unsigned j = 0; j != m->mFaces[i].mNumIndices; j++)
    srcIndices.push_back(m->mFaces[i].mIndices[j]);
    }
  3. If no LOD calculation is required, we can just store srcIndices as LOD 0. Otherwise, we call the processLods() function, which calculates LOD levels for this mesh, as described in the Generating LODs using MeshOptimizer recipe.
    if (!g_calculateLODs) {
    outLods.push_back(srcIndices);
    } else {
    processLods(srcIndices, srcVertices, outLods);
    }
  4. Before updating the indexOffset and vertexOffset parameters, let’s store their values in the resulting Mesh structure. Their values represent where all the previous index and vertex data ended before we started converting this aiMesh.
    Mesh result = {
    .indexOffset = indexOffset,
    .vertexOffset = vertexOffset,
    .vertexCount = m->mNumVertices,
    };
  5. Stream out all the indices for all the LOD levels one after another:
    uint32_t numIndices = 0;
    for (size_t l = 0; l < outLods.size(); l++) {
    for (size_t i = 0; i < outLods[l].size(); i++) {
    meshData.indexData.push_back(outLods[l][i]);
    }
    result.lodOffset[l] = numIndices;
    numIndices += (int)outLods[l].size();
    }
    result.lodOffset[outLods.size()] = numIndices;
    result.lodCount = (uint32_t)outLods.size();
  6. After processing the input mesh, we increment offset counters for indices and the current starting vertex:
    indexOffset += numIndices;
    vertexOffset += m->mNumVertices;
    return result;
    }

Processing a 3D asset file by Assimp comprises loading the scene and converting each mesh into the internal format. Let’s take a look at the loadMeshFile() function to see how to do it:

  1. The list of flags for the aiImportFile() function includes options that allow further usage of imported data without any extra processing on our side. For example, all the transformation hierarchies are flattened, and the resulting transformation matrices are applied to mesh vertices.
    void loadMeshFile(const char* fileName, MeshData& meshData)
    {
    const unsigned int flags = aiProcess_JoinIdenticalVertices |
    aiProcess_Triangulate |
    aiProcess_GenSmoothNormals |
    aiProcess_LimitBoneWeights |
    aiProcess_SplitLargeMeshes |
    aiProcess_ImproveCacheLocality |
    aiProcess_RemoveRedundantMaterials |
    aiProcess_FindDegenerates |
    aiProcess_FindInvalidData |
    aiProcess_GenUVCoords;
    const aiScene* scene = aiImportFile(fileName, flags);
  2. After importing an Assimp scene, we resize the mesh descriptor container accordingly and call convertAIMesh() for each mesh in the scene. The indexOffset and vertexOffset offsets are accumulated incrementally:
    meshData.meshes.reserve(scene->mNumMeshes);
    meshData.boxes.reserve(scene->mNumMeshes);
    uint32_t indexOffset = 0;
    uint32_t vertexOffset = 0;
    for (unsigned int i = 0; i != scene->mNumMeshes; i++)
    meshData.meshes.push_back(
    convertAIMesh(scene->mMeshes[i], meshData,
    indexOffset, vertexOffset));
  3. In the end, we precalculate axis-aligned bounding boxes for our mesh data. This helper function is defined in shared/Scene/VtxData.cpp:
    recalculateBoundingBoxes(meshData);
    }

Although loading and preprocessing of data should be customizable to accommodate needs of each individual demo app, saving is pretty much standard because MeshData contains all the information we need. As such, the saving function saveMeshData() is defined in shared/Scene/VtxData.cpp.

Saving converted meshes into our file format is the reverse process of reading meshes from the file described in the Organizing mesh data storage recipe:

  1. First, we fill the file header structure using the mesh number and offsets:
    void saveMeshData(const char* fileName, const MeshData& m) {
    FILE* f = fopen(fileName, "wb");
  2. We calculate byte sizes of index and vertex data buffers and store them in the header:
    const MeshFileHeader header = {
    .magicValue = 0x12345678,
    .meshCount = (uint32_t)m.meshes.size(),
    .indexDataSize = (uint32_t)(m.indexData.size() * sizeof(uint32_t)),
    .vertexDataSize = (uint32_t)(m.vertexData.size()),
    };
  3. Once all the sizes are known, we save the header and the list of mesh descriptions:
    fwrite(&header, 1, sizeof(header), f);
    fwrite(&m.streams, 1, sizeof(m.streams), f);
    fwrite(m.meshes.data(), sizeof(Mesh), header.meshCount, f);
    fwrite(m.boxes.data(), sizeof(BoundingBox), header.meshCount, f);
  4. After the header and other metadata, two blobs with index and vertex data are stored.
    fwrite(m.indexData.data(), 1, header.indexDataSize, f);
    fwrite(m.vertexData.data(), 1, header.vertexDataSize, f);
    fclose(f);
    }

Let’s put all this code to work in our demo app.

The mesh conversion framework is a part of our demo app. Let’s take a look at that part in the Chapter05/07_MeshRenderer/src/main.cpp file:

  1. First, we check if there’s any valid cached mesh data available. The isMeshDataValid() function checks if the specified cached mesh file exists and does some routine sanity checks on the data sizes.
    bool isMeshDataValid(const char* meshFile) {
    FILE* f = fopen(meshFile, "rb");
    if (!f) false;
    SCOPE_EXIT { fclose(f); };
    MeshFileHeader header;
    if (fread(&header, 1, sizeof(header), f) != sizeof(header))
    return false;
    if (fseek(f, sizeof(Mesh) * header.meshCount, SEEK_CUR))
    return false;
    if (fseek(f, sizeof(BoundingBox) * header.meshCount, SEEK_CUR))
    return false;
    if (fseek(f, header.indexDataSize, SEEK_CUR))
    return false;
    if (fseek(f, header.vertexDataSize, SEEK_CUR))
    return false;
    return true;
    }
  2. Then, we use the isMeshDataValid() function to load the Lumberyard Bistro dataset:
    const char* meshMeshes = ".cache/ch05_bistro.meshes";
    int main() {
    if (!isMeshDataValid(meshMeshes)) {
    printf("No cached mesh data found. Precaching...\n\n");
    MeshData meshData;
    loadMeshFile("deps/src/bistro/Exterior/exterior.obj", meshData);
    saveMeshData(meshMeshes, meshData);
    }
  3. If the data is already precached, we just load it using the loadMeshData() described earlier in this recipe:
    MeshData meshData;
    const MeshFileHeader header = loadMeshData(meshMeshes, meshData);

The output mesh data is saved into the file .cache/ch05_bistro.meshes. Let’s go through the rest of this chapter to learn how to render this mesh with Vulkan.

Indirect rendering is the process of issuing drawing commands to the graphics API, where most of the parameters to those commands come from GPU buffers. It is a part of many modern GPU usage paradigms and exists in all contemporary rendering APIs in some form. For example, we can do indirect rendering with Vulkan using the vkCmdDraw*Indirect*() family of functions. Instead of dealing with low-level Vulkan here, let’s get more technical and learn how to combine indirect rendering in Vulkan with the mesh data format we introduced in the Organizing mesh data storage recipe.

In the earlier recipes, we covered building a mesh preprocessing pipeline and converting 3D meshes from transmission formats such as .gltf2 into our run-time mesh data format. To wrap up this chapter, let’s demonstrate how to render this data. To delve into something new, let’s explore how to achieve this using the indirect rendering technique.

Once we have defined the mesh data structures, we also need to render them. To do so, we allocate GPU buffers for vertex and index data using the previously described functions, upload all the data to the GPU, and finally, render all the meshes.

The whole point of the previously defined Mesh data structure is the ability to render multiple meshes in a single Vulkan command. Since version 1.0 of the API, Vulkan supports the technique of indirect rendering. This means we do not need to issue the vkCmdDraw() command for each and every mesh. Instead, we create a GPU buffer and fill it with an array of VkDrawIndirectCommand structures, then fill these structures with appropriate offsets into our index and vertex data buffers, and finally emit a single vkCmdDrawIndirect() call. The Mesh structure described in the Organizing mesh data storage recipe contains the data required to fill in VkDrawIndirectCommand.

The full source code for this recipe is located in Chapter05/07_MeshRenderer. It is recommended to revisit the Organizing mesh data storage and Implementing automatic geometry conversion recipes before reading further.

Let’s implement a simple helper class called VKMesh, located in Chapter05/07_MeshRenderer/src/main.cpp, to render our mesh using LightweightVK:

  1. We need three buffers, an index buffer, a vertex buffer, and an indirect buffer, as well as three shaders and a rendering pipeline:
    class VKMesh final {
    Holder<BufferHandle> bufferIndices_;
    Holder<BufferHandle> bufferVertices_;
    Holder<BufferHandle> bufferIndirect_;
    Holder<ShaderModuleHandle> vert_;
    Holder<ShaderModuleHandle> geom_;
    Holder<ShaderModuleHandle> frag_;
    Holder<RenderPipelineHandle> pipeline_;
  2. The constructor accepts references to MeshFileHeader and MeshData, which we loaded in the previous recipe, Implemented automatic geometry conversion. The data buffers are used as-is and uploaded directly into the respective Vulkan buffers. The number of indices is inferred from the indices buffer size, assuming indices are stored as 32-bit unsigned integers. The depth format specification is required to create a corresponding rendering pipeline right here in this class:
    public:
    uint32_t numIndices_ = 0;
    VKMesh(const std::unique_ptr<lvk::IContext>& ctx,
    const MeshFileHeader& header,
    const MeshData& meshData,
    lvk::Format depthFormat)
    : numIndices_(header.indexDataSize / sizeof(uint32_t)) {
    const uint32_t* indices = meshData.indexData.data();
    const uint8_t* vertexData = meshData.vertexData.data();
  3. Create vertex and index buffers and upload the data into them:
    bufferVertices_ = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Vertex,
    .storage = lvk::StorageType_Device,
    .size = header.vertexDataSize,
    .data = vertexData,
    .debugName = "Buffer: vertex" });
    bufferIndices_ = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Index,
    .storage = lvk::StorageType_Device,
    .size = header.indexDataSize,
    .data = indices,
    .debugName = "Buffer: index" });
  4. Allocate the data storage for our indirect buffer:
    std::vector<uint8_t> drawCommands;
    const uint32_t numCommands = header.meshCount;
    drawCommands.resize(
    sizeof(DrawIndexedIndirectCommand) * numCommands + sizeof(uint32_t));
  5. Store the number of draw commands at the very beginning of the indirect buffer. This approach is not used in this demo but can be useful for GPU-driven rendering when the GPU calculates the number of draw commands and stores it in a buffer.
    memcpy(drawCommands.data(), &numCommands, sizeof(numCommands));
    DrawIndexedIndirectCommand* cmd = std::launder(
    reinterpret_cast<DrawIndexedIndirectCommand*>(
    drawCommands.data() + sizeof(uint32_t)));
  6. Fill in the content of our indirect commands buffer. Each command corresponds to a single Mesh structure. The indirect buffer should be allocated with the BufferUsageBits_Indirect usage flag.
    for (uint32_t i = 0; i != numCommands; i++)
    *cmd++ = {
    .count = meshData.meshes[i].getLODIndicesCount(0),
    .instanceCount = 1,
    .firstIndex = meshData.meshes[i].indexOffset,
    .baseVertex = meshData.meshes[i].vertexOffset,
    .baseInstance = 0,
    };

More information

The DrawIndexedIndirectCommand structure is just our mirror-image of VkDrawIndexedIndirectCommand to prevent including Vulkan headers into our app. While this might be an exaggeration for a Vulkan book, this type of separation might be useful in real-world apps considering this data structure is compatible in Vulkan, Metal, DirectX, and OpenGL.

struct DrawIndexedIndirectCommand {
uint32_t count;
uint32_t instanceCount;
uint32_t firstIndex;
int32_t baseVertex;
uint32_t baseInstance;
};
bufferIndirect_ = ctx->createBuffer({
.usage = lvk::BufferUsageBits_Indirect,
.storage = lvk::StorageType_Device,
.size = sizeof(DrawIndexedIndirectCommand) *
numCommands + sizeof(uint32_t),
.data = drawCommands.data(),
.debugName = "Buffer: indirect" });
  1. The rendering pipeline is created using a set of vertex, geometry, and fragment shaders. The geometry shader is used for barycentric coordinates generation to render beautiful wireframes. The vertex stream descriptions from meshData.streams can be used directly to initialize the pipeline’s vertex input:
    vert_ = loadShaderModule(
    ctx, "Chapter05/07_MeshRenderer/src/main.vert");
    geom_ = loadShaderModule(
    ctx, "Chapter05/07_MeshRenderer/src/main.geom");
    frag_ = loadShaderModule(
    ctx, "Chapter05/07_MeshRenderer/src/main.frag");
    pipeline_ = ctx->createRenderPipeline({
    .vertexInput = meshData.streams,
    .smVert = vert_,
    .smGeom = geom_,
    .smFrag = frag_,
    .color = { { .format = ctx->getSwapchainFormat() } },
    .depthFormat = depthFormat,
    .cullMode = lvk::CullMode_Back,
    });
    }
  2. The draw() method fills in a corresponding Vulkan command buffer to render the entire mesh. Note how cmdDrawIndexedIndirect() skips the first 32 bits of the indirect buffer where the number of commands is located. We will put that number to use in Chapter 11, Advanced Rendering Techniques and Optimizations:
    void draw(lvk::ICommandBuffer& buf, const MeshFileHeader& header) {
    buf.cmdBindIndexBuffer(bufferIndices_, lvk::IndexFormat_UI32);
    buf.cmdBindVertexBuffer(0, bufferVertices_);
    buf.cmdBindRenderPipeline(pipeline_);
    buf.cmdBindDepthState({ .compareOp = lvk::CompareOp_Less,
    .isDepthWriteEnabled = true });
    buf.cmdDrawIndexedIndirect(
    bufferIndirect_, sizeof(uint32_t), header.meshCount);
    }
    };
  3. This class is used as follows after the Bistro mesh is loaded:
    MeshData meshData;
    const MeshFileHeader header = loadMeshData(meshMeshes, meshData);
    const VKMesh mesh(ctx, header, meshData, app.getDepthFormat());

This completes the description of our initialization process. Now, let’s turn to the GLSL source code:

  1. The vertex shader Chapter05/07_MeshRenderer/src/main.vert is quite simple. We do not use programmable vertex fetching here for the sake of simplicity. Only standard per-vertex attributes are used to simplify the example.
    layout(push_constant) uniform PerFrameData {
    mat4 MVP;
    };
    layout (location=0) in vec3 in_pos;
    layout (location=1) in vec2 in_tc;
    layout (location=2) in vec3 in_normal;
    layout (location=0) out vec2 uv;
    layout (location=1) out vec3 normal;
    void main() {
    gl_Position = MVP * vec4(in_pos, 1.0);
    uv = in_tc;
    normal = in_normal;
    };
  2. The geometry shader, Chapter05/07_MeshRenderer/src/main.geom, provides the necessary barycentric coordinates, as described earlier in this chapter:
    #version 460 core
    layout (triangles) in;
    layout (triangle_strip, max_vertices = 3) out;
    layout (location=0) in vec2 uv[];
    layout (location=1) in vec3 normal[];
    layout (location=0) out vec2 uvs;
    layout (location=1) out vec3 barycoords;
    layout (location=2) out vec3 normals;
    void main() {
    const vec3 bc[3] = vec3,
    vec3(0.0, 1.0, 0.0),
    vec3(0.0, 0.0, 1.0) );
    for ( int i = 0; i < 3; i++ ) {
    gl_Position = gl_in[i].gl_Position;
    uvs = uv[i];
    barycoords = bc[i];
    normals = normal[i];
    EmitVertex();
    }
    EndPrimitive();
    }
  3. The fragment shader, Chapter05/07_MeshRenderer/src/main.frag, calculates some improvized lighting and applies a wireframe outline based on the barycentric coordinates generated by the geometry shader, as described in the Integrating tessellation into the graphics pipeline recipe:
    layout (location=0) in vec2 uvs;
    layout (location=1) in vec3 barycoords;
    layout (location=2) in vec3 normal;
    layout (location=0) out vec4 out_FragColor;
    float edgeFactor(float thickness) {
    vec3 a3 = smoothstep(
    vec3( 0.0 ), fwidth(barycoords) * thickness, barycoords);
    return min( min( a3.x, a3.y ), a3.z );
    }
    void main() {
    float NdotL = clamp(dot(normalize(normal),
    normalize(vec3(-1,1,-1))), 0.5, 1.0);
    vec4 color = vec4(1.0, 1.0, 1.0, 1.0) * NdotL;
    out_FragColor = mix( vec4(0.1), color, edgeFactor(1.0) );
    };
  4. The final C++ rendering code snippet is straightforward because all the heavy lifting is already done inside the VKMesh helper class:
    buf.cmdBeginRendering(renderPass, framebuffer);
    buf.cmdPushConstants(mvp);
    mesh.draw(buf, header);
    app.drawGrid(buf, p, vec3(0, -0.0f, 0));
    app.imgui_->beginFrame(framebuffer);
    app.drawFPS();
    app.imgui_->endFrame(buf);
    buf.cmdEndRendering();

The running application will render the following image, if the image is loaded with the Lumberyard Bistro mesh:

Figure 5.7: Lumberyard Bistro mesh geometry loaded and rendered

Generating textures in Vulkan using compute shaders

Section titled “Generating textures in Vulkan using compute shaders”

We learned how to use basic compute shaders earlier in this chapter, in the Implementing instanced meshes with compute shaders recipe. It is time to go through a few examples of how to use them. Let’s start with some basic procedural texture generation. In this recipe, we implement a small program to display animated textures whose texel values are calculated in real time inside our custom compute shader. To add even more value to this recipe, we will port a GLSL shader from https://www.shadertoy.com to our Vulkan compute shader.

The compute pipeline creation code and Vulkan application initialization are the same as in the Implementing instanced meshes with compute shaders recipe. Make sure you read it before proceeding further. To use and display the generated texture, we need a textured full-screen quad renderer. Its GLSL source code can be found in data/shaders/Quad.vert and data/shaders/Quad.frag. However, the geometry used is actually a triangle covering the entire screen. We will not focus on its internals here because at this point, it should be easy for you to render a full-screen quad on your own using the material from the previous chapters.

The original shader, “Industrial Complex,” that we are going to use here to generate a Vulkan texture was created by Gary “Shane” Warne (http://rhomboid.com/) and can be downloaded from ShaderToy: https://www.shadertoy.com/view/MtdSWS.

Let’s start by discussing the process of writing a texture-generating GLSL compute shader. The simplest shader to generate an RGBA image without using any input data outputs an image by using the gl_GlobalInvocationID built-in variable to calculate which pixel to output. This maps directly to how ShaderToy shaders operate, thus we can transform them into a compute shader just by adding some input and output parameters and layout modifiers that are specific to compute shaders and Vulkan. Let’s take a look at a minimalistic compute shader that creates a red-green gradient texture:

  1. As in all other compute shaders, one mandatory line at the beginning tells the driver how to distribute the workload on the GPU. In our case, we are processing tiles of 16x16 pixels – the local workgroup size, 16x16, is supported on many GPUs, and we will use it for compatibility purposes:
    layout (local_size_x = 16, local_size_y = 16) in;
  2. The only buffer binding that we need to specify is the output image. This is the first time we have used the image type image2D in this book. Here, it means that the array kTextures2DOut contains an array of 2D images whose elements are nothing but pixels of a texture. The writeonly layout qualifier instructs the compiler to assume we will not read from this image in the shader. The binding is updated from the C++ code in the Using Vulkan descriptor indexing recipe in Chapter 2:
    layout (set = 0, binding = 2, rgba8)
    uniform writeonly image2D kTextures2DOut[];
  3. The GLSL compute shading language provides a set of helper functions to retrieve various image attributes. We use the built-in imageSize() function to determine the size of an image in pixels, and the image ID is loaded from push constants:
    layout(push_constant) uniform uPushConstant {
    uint tex;
    float time;
    } pc;
    void main() {
    ivec2 dim = imageSize(kTextures2DOut[pc.tex]);
  4. The built-in gl_GlobalInvocationID variable tells us which global element of our compute grid we are processing. To convert its value into 2D image coordinates, we divide it by the image dimensions. As we are dealing with 2D textures, only x and y components matter. The calling code from the C++ side executes the vkCmdDispatch() function and passes the output image size as the X and Y numbers of local workgroups:
    vec2 uv = vec2(gl_GlobalInvocationID.xy) / dim;
  5. The actual real work we do in this shader is to call the imageStore() GLSL function:
    imageStore(kTextures2DOut[pc.tex],
    ivec2(gl_GlobalInvocationID.xy), vec4(uv, 0.0, 1.0));
    }

Now, this example is rather limited, and all you get is a red-and-green gradient image. Let’s change it a little bit to use the actual shader code from ShaderToy. The compute shader that renders a Vulkan version of the “Industrial Complex” shader from ShaderToy, available via the following URL https://shadertoy.com/view/MtdSWS, can be found in the Chapter05/08_ComputeTexture/src/main.comp file.

  1. First, let’s copy the entire original ShaderToy GLSL code into our new compute shader. There is a function called mainImage() in there, which is declared as follows:
    void mainImage(out vec4 fragColor, in vec2 fragCoord)
  2. We should replace it with a function that returns a vec4 color instead of storing it in the output parameter:
    vec4 mainImage(in vec2 fragCoord)

Don’t forget to add an appropriate return statement at the end.

  1. Now, let’s change the main() function of our compute shader to invoke mainImage() properly and do 5x5 accumulative antialiasing. It is a pretty neat trick:
    void main() {
    ivec2 dim = imageSize(kTextures2DOut[pc.tex]);
    vec4 c = vec4(0.0);
    for (int dx = -2; dx != 3; dx++) {
    for (int dy = -2; dy != 3; dy++) {
    vec2 uv = vec2(gl_GlobalInvocationID.xy) / dim +
    vec2(dx, dy) / (3.0 * dim);
    c += mainImage(uv * dim);
    }
    }
    imageStore(kTextures2DOut[pc.tex],
    ivec2(gl_GlobalInvocationID.xy), c / 25.0);
    }
  2. There is still one issue that needs to be resolved before we can run this code. The ShaderToy code uses two custom input variables, iTime for the elapsed time and iResolution, which contains the size of the resulting image. To prevent any search and replace in the original GLSL code, we mimic these variables, one as a push constant and the other with a hardcoded value for simplicity.
    layout(push_constant) uniform uPushConstant {
    uint tex;
    float time;
    } pc;
    vec2 iResolution = vec2( 1280.0, 720.0 );
    float iTime = pc.time;

Important note

The GLSL imageSize() function can be used to obtain the iResolution value based on the actual size of our texture. We leave it as an exercise to the reader.

The C++ code is rather short and consists of creating a texture and invoking the previously mentioned compute shader, inserting a Vulkan pipeline barrier, and rendering a textured full-screen quad:

  1. A texture is created using the TextureUsageBits_Storage usage flag to make it accessible to compute shaders:
    Holder<TextureHandle> texture = ctx->createTexture({
    .type = lvk::TextureType_2D,
    .format = lvk::Format_RGBA_UN8,
    .dimensions = {1280, 720},
    .usage = lvk::TextureUsageBits_Sampled |
    lvk::TextureUsageBits_Storage,
    .debugName = "Texture: compute",
    });
  2. Compute and rendering pipelines are created the following way:
    Holder<ShaderModuleHandle> comp = loadShaderModule(
    ctx, "Chapter05/08_ComputeTexture/src/main.comp");
    Holder<ComputePipelineHandle> pipelineComputeMatrices =
    ctx->createComputePipeline({ smComp = comp });
    Holder<ShaderModuleHandle> vert = loadShaderModule(
    ctx, "data/shaders/Quad.vert");
    Holder<ShaderModuleHandle> frag = loadShaderModule(
    ctx, "data/shaders/Quad.frag");
    Holder<RenderPipelineHandle> pipelineFullScreenQuad =
    ctx->createRenderPipeline({
    .smVert = vert,
    .smFrag = frag,
    .color = { { .format = ctx->getSwapchainFormat() } },
    });
  3. When doing rendering, we provide the texture ID to both shaders and the current time to the compute shader using push constants:
    lvk::ICommandBuffer& buf = ctx->acquireCommandBuffer();
    const struct {
    uint32_t textureId;
    float time;
    } pc {
    .textureId = texture.index(),
    .time = (float)glfwGetTime(),
    };
    buf.cmdPushConstants(pc);
    buf.cmdBindComputePipeline(pipelineComputeMatrices);
    buf.cmdDispatchThreadGroups(
    { .width = 1280 / 16, .height = 720 / 16 });
  4. A pipeline barrier that ensures that the compute shader finishes before texture sampling happens is created by LightweightVK when we specify a required texture dependency. Take a look at lvk::CommandBuffer::transitionToShaderReadOnly() for the low-level image barrier code. As our fullscreen shader uses a triangle covering the entire screen, draw 3 vertices of that triangle.
    buf.cmdBeginRendering(renderPass, framebuffer,
    { .textures = { { TextureHandle(texture) } } });
    buf.cmdBindRenderPipeline(pipelineFullScreenQuad);
    buf.cmdDraw(3);
    buf.cmdEndRendering();
    ctx->submit(buf, ctx->getCurrentSwapchainTexture());

The running application should render the following image, which is similar to the output of https://www.shadertoy.com/view/MtdSWS:

Figure 5.8: Using compute shaders to generate textures

In the next recipe, we will continue learning the Vulkan compute pipeline and implement a mesh generation compute shader.

In the Generating textures in Vulkan using compute shaders recipe, we learned how to write pixel data into textures from compute shaders. We are going to need that data in the next chapter to implement a BRDF precomputation tool for our physically-based rendering pipeline. But before that, let’s learn a few simple and interesting ways to use compute shaders in Vulkan and combine this feature with mesh geometry generation on the GPU.

We are going to run a compute shader to create the triangulated geometry of a 3D torus knot shape with different P and Q parameters.

Important note

A torus knot is a special kind of knot that lies on the surface of an unknotted torus in 3D space. Each torus knot is specified by a pair of coprime integers, p and q. To find out more, check out the Wikipedia page: https://en.wikipedia.org/wiki/Torus_knot.

A compute shader generates vertex data, including positions, texture coordinates, and normal vectors. This data is stored in a buffer and later utilized as a vertex buffer to render a mesh in a graphics pipeline. To make the results more visually pleasing, we will implement real-time morphing between two different torus knots that is controllable from an ImGui widget. Let’s get started.

The source code for this example is located in Chapter05/09_ComputeMesh.

The application consists of multiple parts: the C++ part (which drives the UI and Vulkan commands), the mesh generation compute shader, the texture generations compute shader, and a rendering pipeline with simple vertex and fragment shaders. The C++ part in Chapter05/09_ComputeMesh/src/main.cpp is quite short, so let’s tackle it first:

  1. We store a queue of P-Q pairs, which defines the order of morphing. The queue always has at least two elements, which define the current and the next torus knot. We also store a floating point value, g_MorphCoef, which is the morphing factor 0...1 between the two adjacent P-Q pairs in the queue. The mesh is regenerated in every frame, and the morphing coefficient is increased until it reaches 1.0. At this point, we will either stop morphing or, if there are more than two elements in the queue, remove the top element from it, reset g_MorphCoef to zero, and repeat. The g_AnimationSpeed value defines how fast one torus knot mesh morphs into another. The g_UseColoredMesh Boolean flag is used to switch between colored and textured shading of the mesh:
    std::deque<std::pair<uint32_t, uint32_t>> morphQueue =
    { { 5, 8 }, { 5, 8 } };
    float morphCoef = 0.0f;
    float animationSpeed = 1.0f;
    bool g_UseColoredMesh = false;
  2. Two global constants define the tessellation level of a torus knot. Feel free to play around with them:
    constexpr uint32_t kNumU = 1024;
    constexpr uint32_t kNumV = 1024;
  3. Regardless of the P and Q parameter values, we have a single order in which we should traverse vertices to produce torus knot triangles. The generateIndices() function prepares index buffer data for this purpose. Here, 6 is the number of indices generated for each rectangular grid element consisting of 2 triangles:
    void generateIndices(uint32_t* indices) {
    for (uint32_t j = 0; j < kNumV - 1; j++) {
    for (uint32_t i = 0; i < kNumU - 1; i++) {
    uint32_t ofs = (j * (kNumU - 1) + i) * 6;
    uint32_t i1 = (j + 0) * kNumU + (i + 0);
    uint32_t i2 = (j + 0) * kNumU + (i + 1);
    uint32_t i3 = (j + 1) * kNumU + (i + 1);
    uint32_t i4 = (j + 1) * kNumU + (i + 0);
    indices[ofs + 0] = i1;
    indices[ofs + 1] = i2;
    indices[ofs + 2] = i4;
    indices[ofs + 3] = i2;
    indices[ofs + 4] = i3;
    indices[ofs + 5] = i4;
    }
    }
    }

Additionally, our C++ code operates an ImGui UI for selecting a configuration of a torus knot and managing various parameters. This offers insights into the code’s flow, so let’s examine it more closely:

  1. Each torus knot is specified by a pair of coprime integers, P and Q. Here, we have preselected a few pairs that produce visually interesting results.
    void renderGUI(TextureHandle texture) {
    static const std::vector<std::pair<uint32_t, uint32_t>> PQ = {
    {1, 1}, {2, 3}, {2, 5}, {2, 7}, {3, 4},
    {2, 9}, {3, 5}, {5, 8}, {8, 9} };
    ImGui::SetNextWindowPos(ImVec2(0, 0), ImGuiCond_Appearing);
    ImGui::Begin("Torus Knot params", nullptr,
    ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse);
  2. We can control the morphing animation speed. That is how fast one mesh morphs into another. We can also switch between colored and textured shading of the mesh.
    ImGui::Checkbox("Use colored mesh", &g_UseColoredMesh);
    ImGui::SliderFloat(
    "Morph animation speed", &g_AnimationSpeed, 0.0f, 2.0f);
  3. When we click a button with a different set of P - Q parameters, we don’t regenerate the mesh right away. Instead, we let any ongoing animations complete by adding a new pair to a queue. In the main loop, after the current morphing animation concludes, we remove the front element from the queue and initiate the animation again.
    for (size_t i = 0; i != PQ.size(); i++) {
    const std::string title = std::to_string(PQ[i].first) + ", " +
    std::to_string(PQ[i].second);
    if (ImGui::Button(title.c_str(), ImVec2(128, 0))) {
    if (PQ[i] != g_MorphQueue.back())
    g_MorphQueue.push_back(PQ[i]);
    }
    }
  4. The content of the morph queue is printed here for you. The current P - Q pair is marked with "<---":
    ImGui::Text("Morph queue:");
    for (size_t i = 0; i != g_MorphQueue.size(); i++) {
    const bool isLastElement = (i + 1) == g_MorphQueue.size();
    ImGui::Text(" P = %u, Q = %u %s", g_MorphQueue[i].first,
    g_MorphQueue[i].second, isLastElement ? "<---" : "");
    }
    ImGui::End();
  5. If we apply an animated texture for shading the mesh, let’s also showcase it using ImGui::Image():
    if (!g_UseColoredMesh) {
    const ImVec2 size = ImGui::GetIO().DisplaySize;
    const float dim = std::max(size.x, size.y);
    const ImVec2 sizeImg(0.25f * dim, 0.25f * dim);
    ImGui::SetNextWindowPos(ImVec2(size.x - sizeImg.x - 25, 0),
    ImGuiCond_Appearing);
    ImGui::Begin("Texture", nullptr,
    ImGuiWindowFlags_AlwaysAutoResize);
    ImGui::Image(texture.index(), sizeImg);
    ImGui::End();
    }
    };

Now, let’s examine the C++ code that’s responsible for creating buffers and populating them with initial data:

  1. The indices are immutable and are generated using the previously mentioned generateIndices() function. The vertex buffer size is calculated based on 12 float elements per vertex. That is vec4 positions, vec4 texture coordinates, and vec4 normal vectors. This padding is used to simplify the compute shader that writes to the vertex buffer.
    std::vector<uint32_t> indicesGen((kNumU - 1) * (kNumV - 1) * 6);
    generateIndices(indicesGen.data());
    const uint32_t vertexBufferSize = 12 * sizeof(float) * kNumU * kNumV;
    const uint32_t indexBufferSize =
    sizeof(uint32_t) * (kNumU - 1) * (kNumV - 1) * 6;
    Holder<BufferHandle> bufferIndex = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Index,
    .storage = lvk::StorageType_Device,
    .size = indicesGen.size() * sizeof(uint32_t),
    .data = indicesGen.data(),
    .debugName = "Buffer: index" });
  2. Let’s create a texture that will be generated by a compute shader. This is similar to the previous recipe, Generating textures in Vulkan using compute shaders.
    Holder<TextureHandle> texture = ctx->createTexture({
    .type = lvk::TextureType_2D,
    .format = lvk::Format_RGBA_UN8,
    .dimensions = {1024, 1024},
    .usage = lvk::TextureUsageBits_Sampled |
    lvk::TextureUsageBits_Storage,
    .debugName = "Texture: compute" });
  3. The vertex buffer should be created with the BufferUsageBits_Storage flag to allow vertex shader usage:
    Holder<BufferHandle> bufferVertex = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Vertex |
    lvk::BufferUsageBits_Storage,
    .storage = lvk::StorageType_Device,
    .size = vertexBufferSize,
    .debugName = "Buffer: vertex" });
  4. We create two compute pipelines: one for mesh generation and another for texture generation.
    Holder<ShaderModuleHandle> compMesh = loadShaderModule(ctx,
    "Chapter05/09_ComputeMesh/src/main_mesh.comp");
    Holder<ShaderModuleHandle> compTexture =
    loadShaderModule(ctx,
    "Chapter05/09_ComputeMesh/src/main_texture.comp");
    Holder<ComputePipelineHandle> pipelineComputeMesh =
    ctx->createComputePipeline({ .smComp = compMesh });
    Holder<ComputePipelineHandle> pipelineComputeTexture =
    ctx->createComputePipeline({ .smComp = compTexture });
  5. Shader modules are loaded as usual. The geometry shader generates barycentric coordinates for wireframe outlines. Wireframe outline rendering will be enabled if you set kNumU and kNumV to 64 or lower values.
    Holder<ShaderModuleHandle> vert =
    loadShaderModule(ctx, "Chapter05/09_ComputeMesh/src/main.vert");
    Holder<ShaderModuleHandle> geom =
    loadShaderModule(ctx, "Chapter05/09_ComputeMesh/src/main.geom");
    Holder<ShaderModuleHandle> frag =
    loadShaderModule(ctx, "Chapter05/09_ComputeMesh/src/main.frag");
  6. For vertex input, we employ vec4 to simplify padding concerns—or, to be more precise, to eliminate them entirely:
    const lvk::VertexInput vdesc = {
    .attributes = { { .location = 0,
    .format = VertexFormat::Float4,
    .offset = 0 },
    { .location = 1,
    .format = VertexFormat::Float4,
    .offset = sizeof(vec4) },
    { .location = 2,
    .format = VertexFormat::Float4,
    .offset = sizeof(vec4)+sizeof(vec4) } },
    .inputBindings = { { .stride = 3 * sizeof(vec4) },
    };
  7. The same shader code is specialized for textures and colored shading using specialization constants:
    const uint32_t specColored = 1;
    const uint32_t specNotColored = 0;
    Holder<RenderPipelineHandle> pipelineMeshColored =
    ctx->createRenderPipeline({
    .vertexInput = vdesc,
    .smVert = vert,
    .smGeom = geom,
    .smFrag = frag,
    .specInfo = { .entries = { { .constantId = 0,
    .size = sizeof(uint32_t) } },
    .data = &specColored,
    .dataSize = sizeof(specColored) },
    .color = { { .format = ctx->getSwapchainFormat() } },
    .depthFormat = app.getDepthFormat() });
    Holder<RenderPipelineHandle> pipelineMeshTextured =
    ctx->createRenderPipeline({
    .vertexInput = vdesc,
    .smVert = vert,
    .smGeom = geom,
    .smFrag = frag,
    .specInfo = { .entries = { { .constantId = 0,
    .size = sizeof(uint32_t) } },
    .data = &specNotColored,
    .dataSize = sizeof(specNotColored) },
    .color = { { .format = ctx->getSwapchainFormat() } },
    .depthFormat = app.getDepthFormat() });

The final segment of the C++ code is the rendering loop. Let’s explore how to populate a command buffer:

  1. First, we need to access the current P - Q pair from the morph queue:
    lvk::ICommandBuffer& buf = ctx->acquireCommandBuffer();
    const mat4 m = glm::translate(mat4(1.0f), vec3(0.0f, 0.0f, -18.f));
    const mat4 p = glm::perspective(45.0f, aspectRatio, 0.1f, 1000.0f);
    auto iter = g_MorphQueue.begin();
  2. The number of parameters for the shaders is larger than usual, precisely 128 bytes. Push constants are shared across all shaders, compute, and graphics, for convenience purposes and to simplify the code.
    struct PerFrame {
    mat4 mvp;
    uint64_t buffer;
    uint32_t textureId;
    float time;
    uint32_t numU, numV;
    float minU, maxU;
    float minV, maxV;
    uint32_t p1, p2;
    uint32_t q1, q2;
    float morph;
    } pc = {
    .mvp = p * m,
    .buffer = ctx->gpuAddress(bufferVertex),
    .textureId = texture.index(),
    .time = (float)glfwGetTime(),
    .numU = kNumU,
    .numV = kNumU,
    .minU = -1.0f,
    .maxU = +1.0f,
    .minV = -1.0f,
    .maxV = +1.0f,
    .p1 = iter->first,
    .p2 = (iter + 1)->first,
    .q1 = iter->second,
    .q2 = (iter + 1)->second,
    .morph = easing(g_MorphCoef),
    };
    buf.cmdPushConstants(pc);
  3. When we dispatch the mesh generation compute shader, we need to specify proper memory barriers to make sure the previous frame has finished rendering:
    buf.cmdBindComputePipeline(pipelineComputeMesh);
    buf.cmdDispatchThreadGroups(
    { .width = (kNumU * kNumV) / 2 },
    { .buffers = { { BufferHandle(bufferVertex) } } });
  4. Do the same for the texture generation shader. We must ensure the texture regeneration is properly synchronized with rendering by issuing a Vulkan image layout transition with appropriate pipeline stages and masks. This is done by LightweightVK inside lvk::CommandBuffer::cmdDispatchThreadGroups() using a few empirical rules.
    if (!g_UseColoredMesh) {
    buf.cmdBindComputePipeline(pipelineComputeTexture);
    buf.cmdDispatchThreadGroups(
    { .width = 1024 / 16, .height = 1024 / 16 },
    { .textures = { { TextureHandle(texture) } } });
    }
  5. When we start rendering, it’s essential to specify both dependencies—the texture and the vertex buffer. The choice of the rendering pipeline depends on whether we aim to render a colored or textured mesh.
    buf.cmdBeginRendering(
    renderPass, framebuffer,
    { .textures = { { TextureHandle(texture) } },
    .buffers = { { BufferHandle(bufferVertex) } } });
    buf.cmdBindRenderPipeline(
    g_UseColoredMesh ? pipelineMeshColored : pipelineMeshTextured);
    buf.cmdBindDepthState({ .compareOp = lvk::CompareOp_Less,
    .isDepthWriteEnabled = true });
    buf.cmdBindVertexBuffer(0, bufferVertex);
    buf.cmdBindIndexBuffer(bufferIndex, lvk::IndexFormat_UI32);
    buf.cmdDrawIndexed(indicesGen.size());
    app.imgui_->beginFrame(framebuffer);
  6. The renderGUI() function renders the ImGui UI, as described earlier in this recipe. In this case, we pass our generated texture to it for presentation.
    renderGUI(texture);
    app.drawFPS();
    app.imgui_->endFrame(buf);
    buf.cmdEndRendering();

That covers the C++ part. Now, let’s dive into the GLSL shaders to understand how the whole demo works.

Let’s start with the compute shader, Chapter05/09_ComputeMesh/src/main_mesh.comp, which is responsible for generating vertex data:

  1. The push constants are declared in Chapter05/09_ComputeMesh/src/common.sp. They are shared between all shaders, and we paste them here for convenience:
    layout (local_size_x = 2, local_size_y = 1, local_size_z = 1) in;
    // included from <Chapter05/09_ComputeMesh/src/common.sp>
    layout(push_constant) uniform PerFrameData {
    mat4 MVP;
    uvec2 bufferId;
    uint textureId;
    float time;
    uint numU, numV;
    float minU, maxU, minV, maxV;
    uint P1, P2, Q1, Q2;
    float morph;
    } pc;
  2. This is the structure containing per-vertex data that we aim to generate and write into a buffer referenced by VertexBuffer, which is stored in pc.bufferId a few lines above the buffer.
    struct VertexData {
    vec4 pos;
    vec4 tc;
    vec4 norm;
    };
    layout (buffer_reference) buffer VertexBuffer {
    VertexData vertices[];
    } vbo;
  3. The heart of our mesh generation algorithm is the torusKnot() function, which uses the following parametrization to triangulate a torus knot https://en.wikipedia.org/wiki/Torus_knot:
    x = r * cos(u)
    y = r * sin(u)
    z = -sin(v)
  4. The torusKnot() function is rather long and is implemented directly from the previously mentioned parametrization. Feel free to play with the baseRadius, segmentRadius, and tubeRadius values:
    VertexData torusKnot(vec2 uv, float p, float q) {
    const float baseRadius = 5.0;
    const float segmentRadius = 3.0;
    const float tubeRadius = 0.5;
    float ct = cos( uv.x );
    float st = sin( uv.x );
    float qp = q / p;
    float qps = qp * segmentRadius;
    float arg = uv.x * qp;
    float sqp = sin( arg );
    float cqp = cos( arg );
    float BSQP = baseRadius + segmentRadius * cqp;
    float dxdt = -qps * sqp * ct - st * BSQP;
    float dydt = -qps * sqp * st + ct * BSQP;
    float dzdt = qps * cqp;
    vec3 r = vec3(BSQP * ct, BSQP * st, segmentRadius * sqp);
    vec3 drdt = vec3(dxdt, dydt, dzdt);
    vec3 v1 = normalize(cross(r, drdt));
    vec3 v2 = normalize(cross(v1, drdt));
    float cv = cos( uv.y );
    float sv = sin( uv.y );
    VertexData res;
    res.pos = vec4(r + tubeRadius * ( v1 * sv + v2 * cv ), 1);
    res.norm = vec4(cross(v1 * cv - v2 * sv, drdt ), 0);
    return res;
    }
  5. We are running this compute shader in each frame, so, instead of generating a static set of vertices, we can actually pre-transform them to make the mesh look like it is rotating. Here is a couple of helper functions to compute the appropriate rotation matrices:
    mat3 rotY(float angle) {
    float c = cos(angle), s = sin(angle);
    return mat3(c, 0, -s, 0, 1, 0, s, 0, c);
    }
    mat3 rotZ(float angle) {
    float c = cos(angle), s = sin(angle);
    return mat3(c, -s, 0, s, c, 0, 0, 0, 1);
    }
  6. Using the previously mentioned helpers, the main() function of our compute shader is now straightforward, and the only interesting thing worth mentioning here is the real-time morphing that blends two torus knots with different P and Q parameters. This is pretty easy because the total number of vertices always remains the same:
    void main() {
    uint index = gl_GlobalInvocationID.x;
    vec2 numUV = vec2(pc.numU, pc.numV);
    vec2 ij = vec2(float(index / pc.numV), float(index % pc.numV));
  7. Two sets of UV coordinates for parametrization need to be computed:
    const vec2 maxUV1 = 2.0 * 3.141592653 * vec2(pc.P1, 1.0);
    vec2 uv1 = ij * maxUV1 / (numUV - vec2(1));
    const vec2 maxUV2 = 2.0 * 3.141592653 * vec2(pc.P2, 1.0);
    vec2 uv2 = ij * maxUV2 / (numUV - vec2(1));
  8. Compute the model matrix for our mesh by combining two rotation matrices:
    mat3 modelMatrix = rotY(0.5 * pc.time) * rotZ(0.5 * pc.time);
  9. Compute two vertex positions for two different torus knots defined by the two sets of P - Q parameters: P1 - Q1 and P2 - Q2.
    VertexData v1 = torusKnot(uv1, pc.P1, pc.Q1);
    VertexData v2 = torusKnot(uv2, pc.P2, pc.Q2);
  10. Perform a linear blend between them using the pc.morph coefficient. We only need to blend the position and the normal vector. While normal vectors can be interpolated more gracefully, we leave that as another exercise for our readers:
    vec3 pos = mix(v1.pos.xyz, v2.pos.xyz, pc.morph);
    vec3 norm = mix(v1.norm.xyz, v2.norm.xyz, pc.morph);
  11. Fill in the resulting VertexData structure and store it in the output vertex buffer:
    VertexData vtx;
    vtx.pos = vec4(modelMatrix * pos, 1);
    vtx.tc = vec4(ij / numUV, 0, 0);
    vtx.norm = vec4(modelMatrix * norm, 0);
    VertexBuffer(pc.bufferId).vertices[index] = vtx;
    }

The vertex shader looks as follows. Just note that the vertex attributes have proper types here:

layout(push_constant) uniform PerFrameData {
mat4 MVP;
};
layout (location=0) in vec4 in_pos;
layout (location=1) in vec2 in_uv;
layout (location=2) in vec3 in_normal;
layout (location=0) out vec2 uv;
layout (location=1) out vec3 normal;
void main() {
gl_Position = MVP * in_pos;
uv = in_uv;
normal = in_normal;
}

The geometry shader is trivial because the only thing it does is generate barycentric coordinates as described in Integrating tessellation into the graphics pipeline. So, let’s jump straight to the fragment shader, Chapter05/09_ComputeMesh/src/main.frag:

  1. The specialization constant is used to switch between the colored and textured versions of the shader:
    #include <Chapter05/09_ComputeMesh/src/common.sp>
    layout (location=0) in vec2 uv;
    layout (location=1) in vec3 normal;
    layout (location=2) in vec3 barycoords;
    layout (location=0) out vec4 out_FragColor;
    layout (constant_id = 0) const bool isColored = false;
  2. Edge factor calculation for wireframe outlines as described in the Integrating tessellation into the graphics pipeline recipe:
    float edgeFactor(float thickness) {
    vec3 a3 = smoothstep( vec3( 0.0 ),
    fwidth(barycoords) * thickness, barycoords);
    return min( min( a3.x, a3.y ), a3.z );
    }
  3. A function to calculate an RGB color for our mesh based on a floating point “hue” value:
    vec3 hue2rgb(float hue) {
    float h = fract(hue);
    float r = abs(h * 6 - 3) - 1;
    float g = 2 - abs(h * 6 - 2);
    float b = 2 - abs(h * 6 - 4);
    return clamp(vec3(r,g,b), vec3(0), vec3(1));
    }
    void main() {
    float NdotL = dot(normalize(normal), normalize(vec3(0, 0, +1)));
    float intensity = 1.0 * clamp(NdotL, 0.75, 1);
    vec3 color = isColored ?
    intensity * hue2rgb(uv.x) :
    textureBindless2D(pc.textureId, 0, vec2(8,1) * uv).xyz;
    out_FragColor = vec4(color, 1.0);
  4. For high values of numU and numV, the tessellation level is so dense that no distinct wireframe edges are visible—everything collapses into a black Moiré mess. We disable wireframe overlays for values greater than 64.
    if (isColored && pc.numU <= 64 && pc.numV <= 64)
    out_FragColor =
    vec4( mix( vec3(0.0), color, edgeFactor(1.0) ), 1.0 );
    }

Last but not least, there’s a compute shader responsible for generating an animated texture. You can find it in Chapter05/09_ComputeMesh/src/main_texture.comp, and the idea is identical to the approach described in the previous recipe, Generating textures in Vulkan using compute shaders. We do not copy and paste that shader here.

The demo application will produce a variety of torus knots similar to the one in the following screenshot. Each time you select a new pair of P - Q parameters from the UI, the morphing animation will kick in and transform one knot into another. Checking the Use colored mesh box will apply colors to the mesh instead of a computed texture:

Figure 5.9: Computed mesh with real-time animation

Refer to the Wikipedia page https://en.wikipedia.org/wiki/Torus_knot for additional explanation of the math details. Try setting the values of kNumU and kNumV to 32 while checking “Use colored mesh”.

This recipe introduces an explicit synchronization process between two independent compute shaders and a rendering pass. The LightweightVK implementation is designed to make this synchronization as seamless as possible through the specification of explicit dependencies.

Since only one queue is being used, the device workload fully drains at each barrier, leaving no alternative tasks to mitigate this inefficiency. Here’s a concrete example of how timeline semaphores and asynchronous compute-only queues can be utilized to accelerate a heterogeneous compute/graphics Vulkan application: https://github.com/nvpro-samples/vk_timeline_semaphore.

In more complex, real-world 3D applications, finer-grained synchronization mechanisms are often necessary. For valuable insights on handling synchronization effectively, refer to the Vulkan synchronization guide by Khronos: https://github.com/KhronosGroup/Vulkan-Docs/wiki/Synchronization-Examples.