Establishing a Build Environment
local graph
Chapter 1 — Establishing a Build Environment
Section titled “Chapter 1 — Establishing a Build Environment”In this chapter, you will learn how to set up a 3D graphics development environment on your computer for Windows and Linux operating systems. You will learn which software tools are needed to run the demos from this book’s source code bundle: https://github.com/PacktPublishing/3D-Graphics-Rendering-Cookbook-Second-Edition.
We will cover the following topics:
- Setting up our development environment on Microsoft Windows
- Setting up our development environment on Linux
- Installing the Vulkan SDK for Microsoft Windows and Linux
- Managing dependencies
- Getting the demo data
- Creating utilities for CMake projects
- Using the
GLFWlibrary - Multithreading with
Taskflow - Compiling Vulkan shaders at runtime
- Compressing textures into the
BC7format
Setting up our development environment on Microsoft Windows
Section titled “Setting up our development environment on Microsoft Windows”In this recipe, we will get started by setting up our development environment on Windows. We will go through the installation of each of the required tools individually and in detail.
Getting ready
Section titled “Getting ready”In order to start working with the examples from this book in a Microsoft Windows environment, you will need some essential tools to be installed in your system.
The most important one is Microsoft Visual Studio 2022. Additional tools include the Git version control system, the CMake build tool, and the Python programming language. Throughout this book, we use these tools on the command line only, so no GUI add-ons will be required.
How to do it…
Section titled “How to do it…”Let’s install each of the required tools individually.
Microsoft Visual Studio 2022
Section titled “Microsoft Visual Studio 2022”Follow the given steps to install Microsoft Visual Studio 2022:
- Open https://visualstudio.microsoft.com and download the Visual Studio 2022 Community Edition installer.
- Start the installer and follow the on-screen instructions. For the purposes of this book, you need to have a native C++ compiler for the 64-bit Intel platform. Other components of the Visual Studio development environment are not required to run this book’s bundled sample code.
Follow the given steps to install Git:
- Download the latest Git installer from https://git-scm.com/downloads, run it, and follow the on-screen instructions. We assume that Git is added to the system
PATHvariable. Enable the option shown in the following image during installation:
Figure 1.4: Git from the command line and also from third-party software
- Select Use Windows’ default console window, as shown in the next screenshot. This option will allow you to build the scripts in this book from any directory on your computer:

A screenshot of a computer Description automatically generated
Figure 1.5: Use Windows’ default console window
Read more
Git is complex software and a huge topic in itself. We recommend the book Mastering Git, 2nd edition written by Jakub Narębski and published by Packt Publishing, along with Git Essentials: Developer’s Guide to Git by François Dupire and the downloadable ebook ProGit, Second Edition, by Scott Chacon and Ben Straub, https://git-scm.com/book/en/v2.
To install CMake, please follow the given steps:
- Download the latest 64-bit CMake installer from https://cmake.org/download/.
- Run it and follow the on-screen instructions. If you already have an earlier version of CMake installed, it is recommended to uninstall it first.
- Select the Add CMake to the system PATH for all users option, as shown here:

A screenshot of a computer program Description automatically generated
Figure 1.6: Add CMake to the system PATH for all users
Python
Section titled “Python”To install Python, please follow the given steps:
- Download the latest Python 3 installer for 64-bit systems from https://www.python.org/downloads/.
- Run it and follow the on-screen instructions.
- During the installation, you also need to install the
pipfeature. Choose Custom Installation and make sure that the pip checkbox is checked, as shown:
A screenshot of a computer Description automatically generated
Figure 1.7: Custom installation
- Once the installation has completed, make sure to add the folder containing
python.exeto thePATHenvironment variable.
There’s more…
Section titled “There’s more…”Besides Git, there are other popular version control systems, like SVN and Mercurial. While developing large software systems, you will inevitably face the need to download some libraries from a non-Git repository. We recommend getting familiar with Mercurial.
While working in the command-line environment, it is useful to have some tools from the Unix environment, like wget, grep, find, etc. The GnuWin32 project provides precompiled binaries of these tools, which can be downloaded from http://gnuwin32.sourceforge.net.
Furthermore, in the Windows environment, orthodox file managers make file manipulation a lot easier. We definitely recommend giving the open-source Far Manager a try. You can download it from https://farmanager.com. It looks like this:

Figure 1.8: The look and feel of Far Manager
Setting up our development environment on Linux
Section titled “Setting up our development environment on Linux”Linux is becoming more and more attractive for 3D graphics development, including gaming technology. Let’s go through a list of tools necessary to start working with this book on Linux.
Getting ready
Section titled “Getting ready”We assume you have a desktop computer with a Debian-based GNU/Linux operating system installed. We also assume you are familiar with the apt package manager.
To start developing modern graphics programs on Linux, you need to have up-to-date video card drivers installed that support Vulkan 1.3. To build examples from this book, a C++ compiler with C++20 support is required. We tested our code with Clang and the GNU Compiler Collection.
How to do it…
Section titled “How to do it…”On a Debian-based system, the installation process is straightforward; however, before installing any of the required packages, we recommend running the following command to ensure your system is up to date:
sudo apt-get updateLet us go through the list of essential software and install whatever is missing.
-
GCC Compiler: Assuming you have a properly configured
aptpackage manager, run the following command to install the GCC compiler and related tools. We tested GCC 12:sudo apt-get install build-essential -
CMake: The CMake build tool is also available in the standard repositories. To install CMake, type the following command:
sudo apt-get install cmake
Note
CMake 3.19 or above is sufficient for the code samples in this book.
- Git: To install the Git version control system, run the following command:
sudo apt-get install git
- Python 3: To install the Python 3 package, run the following command:
sudo apt-get install python3.7
The exact version of Python may vary between Linux distributions. Any version of Python 3 will suffice for the scripts in this book.
Now we are done with the basic packages and can install graphics-related software. Let us move on to the next recipe to learn how to set up the Vulkan SDK.
Installing the Vulkan SDK for Windows and Linux
Section titled “Installing the Vulkan SDK for Windows and Linux”In this recipe, you will learn how to get started with the Vulkan SDK. We will describe the requirements and procedure for installing the LunarG Vulkan SDK for Windows and Linux.
In principle, it is possible to write Vulkan applications without the Vulkan SDK, using only C/C++ header files provided by Khronos. You can get these header files by cloning the Git repository: https://github.com/KhronosGroup/Vulkan-Headers. However, it is advised to install the complete Vulkan SDK to be able to use Vulkan validation layers and a standalone GLSL compiler.
Getting ready
Section titled “Getting ready”Make sure you have the latest up-to-date video card drivers for your operating system. On Windows, you can download video drivers from your GPU vendor’s website. For Ubuntu, refer to the documentation: https://ubuntu.com/server/docs/nvidia-drivers-installation.
How to do it…
Section titled “How to do it…”To install Vulkan 1.3 on Linux, follow these steps:
- Open the https://www.lunarg.com/vulkan-sdk/ page in a browser and download the latest Vulkan SDK for Windows or Linux.
- After the download has finished, run the Windows installer file and follow the on-screen instructions. If you have Ubuntu 22.04 installed, use the following commands provided on LunarG’s website:
wget -qO- https://packages.lunarg.com/lunarg-signing-key-pub.asc | sudo tee /etc/apt/trusted.gpg.d/lunarg.ascsudo wget -qO /etc/apt/sources.list.d/lunarg-vulkan-1.3.296-jammy.list https://packages.lunarg.com/vulkan/1.3.296/lunarg-vulkan-1.3.296-jammy.listsudo apt updatesudo apt install vulkan-sdk
- For other Linux distributions, you may need to download the
.tar.gzSDK archive from https://vulkan.lunarg.com/sdk/home#linux and unpack it manually. You need to set environment variables to locate the Vulkan SDK components. Use thesourcecommand to run a config script that will do it for you:source ~/vulkan/1.3.296.1/setup-env.sh
There’s more…
Section titled “There’s more…”When developing cross-platform applications, it is good to use similar tools for each platform. Since Linux supports GCC and Clang compilers, using GCC or Clang on Windows ensures that you avoid the most common portability issues. A complete package of C and C++ compilers can be downloaded from http://www.equation.com/servlet/equation.cmd?fa=fortran.
An alternative way to use GCC on Windows is to install the MSYS2 environment from https://www.msys2.org. It features the package management system used in Arch Linux, Pacman.
Managing dependencies
Section titled “Managing dependencies”This book’s examples use multiple open-source libraries. To manage these dependencies, we use a free and open-source tool called Bootstrap. The tool is similar to Google’s repo tool and works on both Windows and Linux, as well as on macOS for that matter.
In this recipe, we will learn how to use Bootstrap to download libraries using the Vulkan Headers repository as an example.
Getting ready
Section titled “Getting ready”Make sure you have Git and Python installed as described in the previous recipes. After that, clone the Bootstrap repository from GitHub:
git clone https://github.com/corporateshark/bootstrappingHow to do it…
Section titled “How to do it…”Let’s look into the source code bundle and run the bootstrap.py script:
bootstrap.pyThe script will start downloading all the third-party libraries required to compile and run the source code bundle for this book. On Windows, the tail of the output should look as follows.
Cloning into 'M:\Projects.CPP\Book_Rendering2\Sources\deps\src\assimp'...remote: Enumerating objects: 25, done.remote: Counting objects: 100% (25/25), done.remote: Compressing objects: 100% (24/24), done.remote: Total 51414 (delta 2), reused 10 (delta 1), pack-reused 51389Receiving objects: 100% (51414/51414), 148.46 MiB | 3.95 MiB/s, done.Resolving deltas: 100% (36665/36665), done.Checking out files: 100% (2163/2163), done.Once the download process is complete, we are ready to build the project.
How it works…
Section titled “How it works…”Bootstrap takes a JSON file as input, opening bootstrap.json from the current directory by default. It contains metadata of libraries we want to download; for example, their names, where to retrieve them from, a specific version to download, and so on. Besides that, each used library can have some additional instructions on how to build it. Those can be patches applied to the original library, unpacking instructions, SHA hashes to check archive integrity, and many others.
The source code for each library can be represented by either a URL of a version control system repository or by an archive file with the library source files.
A typical JSON file entry corresponding to one library looks like this snippet:
[{ "name": "vulkan", "source": { "type": "git", "url" : "https://github.com/KhronosGroup/Vulkan-Headers.git", "revision": "v1.3.296" }}]The field type can have one of these values: archive, git, hg, or svn. The first value corresponds to an archive file, such as .zip, .tar.gz, or .tar.bz2, while the last three types describe different version control system repositories. The url field contains a URL of the archive file to be downloaded or a URL of the repository. The revision field can specify a particular revision, tag, or branch to check out.
The complete JSON file is a comma-separated list of such entries. For this recipe, we have only one library to download. We will add more libraries in the next chapters. The accompanying source code bundle contains a JSON file with all the libraries used in this book.
There’s more…
Section titled “There’s more…”There is comprehensive documentation for this tool that describes other command-line options and JSON fields in great detail. It can be downloaded from https://github.com/corporateshark/bootstrapping.
The Bootstrap tool does not differentiate between source code and binary assets. All the textures, 3D models, and other resources for your application can also be downloaded and kept up to date and organized in an automated way.
Getting the demo data
Section titled “Getting the demo data”This book makes use of free 3D graphics datasets as much as possible. The comprehensive list of large 3D datasets is maintained by Morgan McGuire – Computer Graphics Archive, July 2017 (https://casual-effects.com/data). We will use some large 3D models from his archive for demonstration purposes in this book. Let us download one of them.
How to do it…
Section titled “How to do it…”The bundled source code contains a Python script, deploy_deps.py, which will download all the required 3D models automatically. To download the entire Bistro dataset manually, which is not recommended, follow these simple steps:
- Open the https://casual-effects.com/data/ page in a browser and find the Amazon Lumberyard Bistro dataset.
- Click on the Download link and allow the browser to download all the data files. Below is a screenshot of Morgan McGuire’s site with the download link.

Figure 1.9: Amazon Lumberyard Bistro as pictured on casualeffects.com as a 2.4 GB download
Creating utilities for CMake projects
Section titled “Creating utilities for CMake projects”In this recipe, we will see how CMake is used to configure all the code examples in this book and learn some small tricks along the way.
Read more
For those who are just starting with CMake, we recommend reading the books CMake Cookbook (Radovan Bast and Roberto Di Remigio) by Packt Publishing and Mastering CMake (Ken Martin and Bill Hoffman) by Kitware.
Getting ready
Section titled “Getting ready”For a start, let’s create a minimalistic C++ application with a trivial main() function and build it using CMake:
int main() { printf("Hello World!\n"); return 0;}How to do it…
Section titled “How to do it…”Let’s introduce two helper macros for CMake. You can find them in the CMake/CommonMacros.txt file of our source code bundle at https://github.com/PacktPublishing/3D-Graphics-Rendering-Cookbook-Second-Edition.
- The
SETUP_GROUPSmacro iterates over a space-delimited list of C and C++ files, whether it is a header or a source file, and assigns each of them to a separate group. The group name is constructed based on the path of each individual file. This way, we end up with a nice structure similar to a filesystem within a directory in the Visual Studio Solution Explorer window, as we can see on the right in the following figure:
Figure 1.10: Without groups (left) and with groups (right)
- The macro starts by iterating over a list of files passed in the
src_filesparameter:macro(SETUP_GROUPS src_files)foreach(FILE ${src_files})get_filename_component(PARENT_DIR "${FILE}" PATH) - We store the parent directory name as a default group name. Regardless of the operating system, replace all forward slashes with backslashes:
set(GROUP "${PARENT_DIR}")string(REPLACE "/" "\\" GROUP "${GROUP}")
- Then, we can tell CMake to assign the current file to a source group with this name.
source_group("${GROUP}" FILES "${FILE}")endforeach()endmacro()
- The second macro,
SETUP_APP, is used as a shortcut to create a new CMake project with all the standard properties we want it to have. It is very convenient when having to deal with a number of very similar subprojects, for example, like in this book.macro(SETUP_APP projname chapter)set(FOLDER_NAME ${chapter})set(PROJECT_NAME ${projname})project(${PROJECT_NAME} CXX) - After setting the project name, this macro uses the
GLOB_RECURSEfunction to collect all source and header files into theSRC_FILESandHEADER_FILESvariables.file(GLOB_RECURSE SRC_FILES LIST_DIRECTORIES falseRELATIVE ${CMAKE_CURRENT_SOURCE_DIR} src/*.c??)file(GLOB_RECURSE HEADER_FILES LIST_DIRECTORIES falseRELATIVE ${CMAKE_CURRENT_SOURCE_DIR} src/*.h) - In all our code samples, we use the directory
srccontaining the source files as anincludedirectory, too.include_directories(src) - All enumerated source and header files are added to an executable inside the current project.
add_executable(${PROJ_NAME} ${SRC_FILES} ${HEADER_FILES})
- We use the
SETUP_GROUPmacro from Step 1 to place each source and header file into an appropriate group inside the project.SETUP_GROUPS("${SRC_FILES}")SETUP_GROUPS("${HEADER_FILES}") - The next three properties set different executable file names for each supported build configuration. These lines are optional, yet they are really useful when using CMake with the Visual Studio IDE. The reason is that Visual Studio can change build configurations (or “build types”, as they are called in CMake) dynamically directly from the IDE, and each build configuration can have its own output file name. We add suffixes to these file names so that they can co-exist in a single output folder.
set_target_properties(${PROJ_NAME}PROPERTIES OUTPUT_NAME_DEBUG ${PROJ_NAME}_Debug)set_target_properties(${PROJ_NAME}PROPERTIES OUTPUT_NAME_RELEASE ${PROJ_NAME}_Release)set_target_properties(${PROJ_NAME}PROPERTIES OUTPUT_NAME_RELWITHDEBINFO ${PROJ_NAME}_ReleaseDebInfo)
- Since we use C++20 throughout this book, we require CMake to enable it.
set_property(TARGET ${PROJ_NAME} PROPERTY CXX_STANDARD 20)set_property(TARGET ${PROJ_NAME} PROPERTY CXX_STANDARD_REQUIRED ON)
- To ease the debugging with Visual Studio, we enable console output by changing the application type to
Console. We also set the local debugger working directory toCMAKE_SOURCE_DIR, which will make finding assets a lot more straightforward and consistent. There are some Apple-specific properties to allow building the source code on Mac machines.if(MSVC)add_definitions(-D_CONSOLE)set_property(TARGET ${PROJ_NAME} PROPERTYVS_DEBUGGER_WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")endif()if(APPLE)set_target_properties(${PROJECT_NAME} PROPERTIESXCODE_GENERATE_SCHEME TRUEXCODE_SCHEME_WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")endif()endmacro() - Finally, the top-level
CMakeLists.txtfile of our first project will look like this:cmake_minimum_required(VERSION 3.19)project(Chapter01)include(../../CMake/CommonMacros.txt)SETUP_APP(Ch01_Sample01_CMake "Chapter 01")
Note
You may notice that the line project(Chapter01) above is overridden by a call to project() inside the SETUP_APP macro. This is due to the following CMake warning, which will be emitted if we do not declare a new project right from the get-go.
CMake Warning (dev) in CMakeLists.txt:No project() command is present. The top-level CMakeLists.txt file must contain a literal, direct call to the project() command. Add a line of project(ProjectName) near the top of the file, but after cmake_minimum_required().- To build and test the executable, create the
buildsubfolder, change the working directory tobuild, and run CMake as follows:- For Windows and Visual Studio 2022, run the following command to configure our project for the 64-bit target platform architecture.
cmake .. -G "Visual Studio 17 2022" -A x64
- For Linux, we can use the
Unix MakefilesCMake generator as follows:
cmake .. -G "Unix Makefiles" - For Linux, we can use the
- For Windows and Visual Studio 2022, run the following command to configure our project for the 64-bit target platform architecture.
- To build an executable for the
releasebuild type, you can use the following command on any platform. To build a debug version, use--config Debugor skip that parameter entirely.cmake --build . --config Release
All the demo applications from the source code bundle should be run from the folder where the data/ subfolder is located.
There’s more…
Section titled “There’s more…”Alternatively, you can use the cross-platform build system Ninja along with CMake. It is possible to do so simply by changing the CMake project generator name.
cmake .. -G "Ninja"Invoke Ninja from the command line to compile the project.
ninja[2/2] Linking CXX executable Ch01_Sample01_CMake.exeNotice how fast everything gets built now, compared to the classic cmake --build command. See https://ninja-build.org for more details.
Now let’s take a look at how to work with some basic open source libraries.
Using the GLFW library
Section titled “Using the GLFW library”The GLFW library hides all the complexity of creating windows, graphics contexts, and surfaces and getting input events from the operating system. In this recipe, we build a minimalistic application with GLFW to get an empty window onto the screen.
Getting ready
Section titled “Getting ready”We build our examples with GLFW 3.4. Here is a JSON snippet for the Bootstrap script so that you can download the proper library version:
{ "name": "glfw", "source": { "type": "git", "url": "https://github.com/glfw/glfw.git", "revision": "3.4" }}The complete source code for this recipe can be found in the source code bundle under the name of Chapter01/02_GLFW.
How to do it…
Section titled “How to do it…”Let’s write a minimalistic application that creates a window and waits for an exit command from the user – pressing the Esc key. This functionality will be used in all of our subsequent demos, so we have wrapped it into a helper function initWindow() declared in shared/HelpersGLFW.h. Let’s take a look at how to use it to create an empty GLFW window:
- Include all necessary headers and decide on the initial window dimensions:
#include <shared/HelpersGLFW.h>int main() {uint32_t width = 1280;uint32_t height = 800;
- Invoke the
initWindow()function to create a window. Thewidthandheightparameters are passed by reference and, after the call, will contain the actual working area of the created window. If we pass the initial values of0, the window will be created to span the entire desktop working area without overlapping the system taskbar.GLFWwindow* window =initWindow("GLFW example", width, height); - For this application, the main loop and cleanup are trivial:
while (!glfwWindowShouldClose(window)) {glfwPollEvents();}glfwDestroyWindow(window);glfwTerminate();return 0;}
Now we will take a look at the internals of initWindow() for some interesting details.
How it works…
Section titled “How it works…”Let’s use this library to create an application that opens an empty window:
- First, we set the GLFW error callback via a lambda to catch potential errors and then initialize GLFW:
GLFWwindow* initWindow(const char* windowTitle,uint32_t& outWidth, uint32_t& outHeight) {glfwSetErrorCallback( {printf("GLFW Error (%i): %s\n", error, description);});if (!glfwInit()) return nullptr;
- Let’s decide if we want to make a desktop full-screen window. Set the resizable flag for windows that aren’t full-screen and retrieve the desired window dimensions. We are going to initialize Vulkan manually, so no graphics API initialization is required to be done by GLFW. The flag
wantsWholeAreadetermines if we want a true full-screen window or a window that does not overlap the system taskbar.const bool wantsWholeArea = !outWidth || !outHeight;glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);glfwWindowHint(GLFW_RESIZABLE,wantsWholeArea ? GLFW_FALSE : GLFW_TRUE);GLFWmonitor* monitor = glfwGetPrimaryMonitor();const GLFWvidmode* mode = glfwGetVideoMode(monitor);int x = 0;int y = 0;int w = mode->width;int h = mode->height;if (wantsWholeArea) {glfwGetMonitorWorkarea(monitor, &x, &y, &w, &h);} else {w = outWidth;h = outHeight;} - Create a window and retrieve the actual window dimensions:
GLFWwindow* window = glfwCreateWindow(w, h, windowTitle, nullptr, nullptr);if (!window) {glfwTerminate();return nullptr;}if (wantsWholeArea) glfwSetWindowPos(window, x, y);glfwGetWindowSize(window, &w, &h);outWidth = (uint32_t)w;outHeight = (uint32_t)h;
- Set a default keyboard callback to handle the Esc key. A simple lambda will do this job for us.
glfwSetKeyCallback(window, {if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {glfwSetWindowShouldClose(window, GLFW_TRUE);}});return window;}
If you run this tiny application, it will create an empty window, as in the following screenshot:

Figure 1.11: Our first application
There’s more…
Section titled “There’s more…”Further details about how to use GLFW can be found at https://www.glfw.org/documentation.html.
Multithreading with Taskflow
Section titled “Multithreading with Taskflow”Modern graphical applications require us to harness the power of multiple CPUs to be performant. Taskflow is a fast C++ header-only library that can help you write parallel programs with complex task dependencies quickly. This library is extremely useful as it allows you to jump into the development of multithreaded graphical applications that make use of advanced rendering concepts, such as frame graphs and multithreaded command buffer generation.
Getting ready
Section titled “Getting ready”Here, we use Taskflow version 3.8.0. You can download it using the following Bootstrap snippet:
{ "name": "taskflow", "source": { "type": "git", "url" : "https://github.com/taskflow/taskflow.git", "revision": "v3.8.0" }}To debug dependency graphs produced by Taskflow, it is recommended that you install the GraphViz tool from https://www.graphviz.org.
The complete source code for this recipe can be found in Chapter01/03_Taskflow.
How to do it…
Section titled “How to do it…”Let’s create and run a set of concurrent dependent tasks via the for_each_index() algorithm. Each task will print a single value from an array in a concurrent fashion. The processing order can vary between different runs of the program:
- Include the
taskflow.hppheader file. Thetf::Taskflowclass is the main place to create a task dependency graph. Declare an instance and a data vector to process.#include <taskflow/taskflow.hpp>int main() {tf::Taskflow taskflow;std::vector<int> items{ 1, 2, 3, 4, 5, 6, 7, 8 }; - The
for_each_index()member function returns a task that implements a parallel for loop algorithm. We specify the range0..items.size()and the step1. The returnedtaskcan be used for synchronization purposes:auto task = taskflow.for_each_index(0u, uint32_t(items.size()), 1u, [&](int i) {printf("%i", items[i]);}).name("for_each_index"); - Let’s attach some work before and after the parallel for task so that we can view
StartandEndmessages in the output. Let’s call the newSandTtasks accordingly:taskflow.emplace([]() {printf("\nS - Start\n"); }).name("S").precede(task);taskflow.emplace([]() {printf("\nT - End\n"); }).name("T").succeed(task); - Save the generated tasks dependency graph in
.dotformat so that we can process it later with the GraphVizdottool:std::ofstream os(".cache/taskflow.dot");taskflow.dump(os); - Now we can create a
tf::executorobject and run the constructed Taskflow graph:tf::Executor executor;executor.run(taskflow).wait();return 0;}
An important point to note is that the Taskflow dependency graph is built only once. After that, it can be reused in every frame to efficiently execute concurrent tasks.
The output from the preceding program should look similar to the following listing:
S – Start18345672T - EndHere, we can see our S and T tasks. Between them, there are multiple threads with different IDs processing different elements of the items[] vector in parallel. Your output may vary due to concurrency.
There’s more…
Section titled “There’s more…”The application saved the dependency graph inside the .cache/taskflow.dot file. It can be converted into a visual representation by GraphViz, https://graphviz.org, using the following command:
dot -Tpng taskflow.dot > output.pngThe resulting .png image should look similar to the following screenshot:

Figure 1.12: The Taskflow dependency graph for for_each_index()
This functionality is extremely useful when you are debugging complex dependency graphs (and producing complex-looking images for your books and papers).
The Taskflow library functionality is vast and provides implementations for numerous parallel algorithms and profiling capabilities. Please refer to the official documentation for in-depth coverage at https://taskflow.github.io/taskflow/index.html.
Compiling Vulkan shaders at runtime
Section titled “Compiling Vulkan shaders at runtime”Before we can start working with Vulkan, it’s important to speed up the iterative process of writing shaders. Vulkan uses shaders in the binary form called Standard Portable Intermediate Representation, known as SPIR-V, and typically relies on a standalone shader compiler to precompile shaders offline. While this is ideal for a released product, it can slow down early stages of development and rapid prototyping, where shaders are frequently changed and need to be recompiled with every run. In this recipe, we’ll show you how to compile Vulkan shaders at runtime using Khronos’ reference shader compiler glslang.
Getting ready
Section titled “Getting ready”Our application is using LightweightVK which is statically linked to the glslang shader compiler. The compiler version used in this recipe was downloaded using the following Bootstrap snippet.
{ "name": "glslang", "source": { "type": "git", "url" : "https://github.com/KhronosGroup/glslang.git", "revision": "15.1.0" }}The complete source code for this recipe can be found in the source code bundle under the name Chapter01/04_GLSLang. The implementation of shader compilation in LightweightVK is located in deps/src/lightweightvk/lvk/vulkan/VulkanUtils.cpp in the function lvk::compileShader().
How to do it…
Section titled “How to do it…”Let us go through the steps necessary to compile GLSL shaders to SPIR-V using glslang. In this book text, we’ve omitted most error checking for clarity, though it is included in the actual source code.
- We should use this helper function to compile a GLSL shader from its source code for a specific Vulkan pipeline stage and return the resulting SPIR-V binary as a vector bytes. Initializing the compiler input structure can be a bit verbose. We specify the shader’s source language as
GLSLANG_SOURCE_GLSLand set the correct targets to generate SPIR-V 1.6 for Vulkan 1.3. With C++20’s designated initializers, this task becomes much simpler. This feature is also helpful in general Vulkan development, where a common task for developers is to populate structure members with specific values.lvk::Result compileShader(glslang_stage_t stage,const char* code,std::vector<uint8_t>* outSPIRV,const glslang_resource_t* glslLangResource){const glslang_input_t input = {.language = GLSLANG_SOURCE_GLSL,.stage = stage,.client = GLSLANG_CLIENT_VULKAN,.client_version = GLSLANG_TARGET_VULKAN_1_3,.target_language = GLSLANG_TARGET_SPV,.target_language_version = GLSLANG_TARGET_SPV_1_6,.code = code,.default_version = 100,.default_profile = GLSLANG_NO_PROFILE,.force_default_version_and_profile = false,.forward_compatible = false,.messages = GLSLANG_MSG_DEFAULT_BIT,.resource = glslLangResource,}; - Let`s create a glslang shader object using the abovementioned input. The
SCOPE_EXITmacro ensures the shader object is properly deallocated whenever we exit the current scope. Its implementation is beyond the scope of this book. However, we recommend watching the CppCon 2015 presentation Declarative Control Flow by Andrei Alexandrescu which dives deep into the implementation details. The implementation we use is located indeps/src/lightweightvk/third-party/deps/src/ldrutils/lutils/ScopeExit.h.glslang_shader_t* shader = glslang_shader_create(&input);SCOPE_EXIT {glslang_shader_delete(shader);}; - The shader needs to be preprocessed by the compiler. The following function returns
trueif all extensions, pragmas and version strings mentioned in the shader source code are valid. ThelogShaderSource()function prints to the console the source code of the shader together with line numbers and is very handy for debugging.if (!glslang_shader_preprocess(shader, &input)) {LLOGW("Shader preprocessing failed:\n");LLOGW(" %s\n", glslang_shader_get_info_log(shader));LLOGW(" %s\n",glslang_shader_get_info_debug_log(shader));lvk::logShaderSource(code);return Result(Result::Code::RuntimeError);} - Then the shader gets parsed into an internal representation inside the compiler.
if (!glslang_shader_parse(shader, &input)) {LLOGW("Shader parsing failed:\n");LLOGW(" %s\n", glslang_shader_get_info_log(shader));LLOGW(" %s\n",glslang_shader_get_info_debug_log(shader));lvk::logShaderSource(glslang_shader_get_preprocessed_code(shader));return Result(Result::Code::RuntimeError);}
- If everything went fine during the previous stages, now we can link the shader into a program and proceed with the binary code generation stage. The same
SCOPE_EXITis applied toprogramto prevent memory leaks.glslang_program_t* program = glslang_program_create();glslang_program_add_shader(program, shader);SCOPE_EXIT {glslang_program_delete(program);};if (!glslang_program_link(program,GLSLANG_MSG_SPV_RULES_BIT |GLSLANG_MSG_VULKAN_RULES_BIT)) {LLOGW("Shader linking failed:\n");LLOGW(" %s\n", glslang_program_get_info_log(program));LLOGW(" %s\n",glslang_program_get_info_debug_log(program));return Result(Result::Code::RuntimeError);} - Now we are ready to generate some binary SPIR-V code. The glslang compiler supports multiple code generation flags to control debug info generation. This is useful if you want to inspect your shaders at run-time with a tool such as RenderDoc.
glslang_spv_options_t options = {.generate_debug_info = true,.strip_debug_info = false,.disable_optimizer = false,.optimize_size = true,.disassemble = false,.validate = true,.emit_nonsemantic_shader_debug_info = false,.emit_nonsemantic_shader_debug_source = false,};glslang_program_SPIRV_generate_with_options(program, input.stage, &options);
- There might be some messages produced by the code generator. Check and print them if there are any. The resulting SPIR-V code can be retrieved in the following way. We return it as a binary blob of
uint8_tvalues.if (glslang_program_SPIRV_get_messages(program)) {LLOGW("%s\n",glslang_program_SPIRV_get_messages(program));}const uint8_t* spirv = reinterpret_cast<const uint8_t*>(glslang_program_SPIRV_get_ptr(program));const size_t numBytes =glslang_program_SPIRV_get_size(program) *sizeof(uint32_t);*outSPIRV = std::vector(spirv, spirv + numBytes);return Result();}
Let’s inspect the demo application which loads GLSL shader code from files, compiles it using the abovementioned function, and then saves SPIR-V binaries into files.
How it works…
Section titled “How it works…”The application is straightforward. It loads the shader source code from a text file and uses the compileShader() function we have just written to compile it into SPIR-V.
void testShaderCompilation( const char* sourceFilename, const char* destFilename){ std::string shaderSource = readShaderFile(sourceFilename); std::vector<uint8_t> spirv; lvk::Result res = lvk::compileShader( vkShaderStageFromFileName(sourceFilename), shaderSource.c_str(), &spirv, glslang_default_resource()); saveSPIRVBinaryFile(destFilename, spirv.data(), spirv.size());}Each generated SPIR-V binary blob is saved to a file for further inspection.
void saveSPIRVBinaryFile( const char* filename, const uint8_t* code, size_t size){ FILE* f = fopen(filename, "wb"); fwrite(code, sizeof(uint8_t), size, f); fclose(f);}The main() function, which drives the demo application, initializes the glslang compiler and runs the tests.
int main(){ glslang_initialize_process(); testShaderCompilation("Chapter01/04_GLSLang/src/main.vert", ".cache/04_GLSLang.vert.bin"); testShaderCompilation("Chapter01/04_GLSLang/src/main.frag", ".cache/04_GLSLang.frag.bin"); glslang_finalize_process(); return 0;}The abovementioned program produces the same SPIR-V output as the following console commands:
glslangValidator -g -Os --target-env vulkan1.3 main.vert -o main.vert.binglslangValidator -g -Os --target-env vulkan1.3 main.frag -o main.frag.binBinary SPIR-V modules can be used to create Vulkan shader modules as follows. One key detail to note in this example is how to determine the size of the push constants used by the shader. This information will be important in later chapters when we build Vulkan pipelines:
ShaderModuleState VulkanContext::createShaderModuleFromSPIRV( const void* spirv, size_t numBytes, const char* debugName, Result* outResult) const{ VkShaderModule vkShaderModule = VK_NULL_HANDLE; const VkShaderModuleCreateInfo ci = { .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = numBytes, .pCode = (const uint32_t*)spirv, }; const VkResult result = vkCreateShaderModule(vkDevice_, &ci, nullptr, &vkShaderModule); lvk::setResultFrom(outResult, result); if (result != VK_SUCCESS) return {.sm = VK_NULL_HANDLE}; VK_ASSERT(lvk::setDebugObjectName( vkDevice_, VK_OBJECT_TYPE_SHADER_MODULE, (uint64_t)vkShaderModule, debugName));After creating the Vulkan shader module, we can determine the size of the push constants used by the shader. To do this, we use the SPIRV-Reflect library, which makes it easy to extract this information:
SpvReflectShaderModule mdl; SpvReflectResult result = spvReflectCreateShaderModule( numBytes, spirv, &mdl); SCOPE_EXIT { spvReflectDestroyShaderModule(&mdl); }; uint32_t pushConstantsSize = 0; for (uint32_t i = 0; i < mdl.push_constant_block_count; ++i) { const SpvReflectBlockVariable& block = mdl.push_constant_blocks[i]; pushConstantsSize = std::max(pushConstantsSize, block.offset + block.size); } return { .sm = vkShaderModule, .pushConstantsSize = pushConstantsSize };}This function is used throughout the LightweightVK library to create all Vulkan shader modules. It is located in deps/src/lightweightvk/lvk/vulkan/VulkanClasses.cpp.
There’s more…
Section titled “There’s more…”While it may be convenient to include a full compiler during the development phase, shipping a large compiler with the release version of your application is generally not recommended. Unless your application specifically needs to compile shaders at runtime, it’s better to include precompiled SPIR-V shader binaries in the release version. One way to handle this is by implementing a shader caching mechanism. When a shader is needed, the application can first check if a compiled version already exists. If it doesn’t, the app can load the glslang compiler from a .dll or .so file at runtime to compile the shader. Once all shaders are cached, the cached shaders can be shipped with the app without any GLSL source code. This approach ensures that compiled shaders are always available in the release version without bundling the compiler’s shared libraries.
Compressing textures into the BC7 format
Section titled “Compressing textures into the BC7 format”A major downside of high-resolution texture data is that it uses a lot of GPU memory for storage. To address this, all modern real-time rendering APIs offer texture compression, which lets us store textures in compressed formats on the GPU. One common format is BC7, a standard texture compression format for Vulkan that is supported on many devices.
bc7enc is an open-source library that can compress RGBA bitmaps into the BC7 format. In this recipe, you will learn how to integrate this library into your own applications to create tools for your custom graphics pre-processing pipelines.
The BC7 format is described in great detail in https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc7-format and we will use it in our book to store textures for the large Lumberyard Bistro dataset.
Let’s learn how to compress 2D .jpg or .png images into BC7.
Getting ready
Section titled “Getting ready”The source code for this recipe is located at Chapter01/05_BC7Compression. We use an the STB_Image library by Sean Barrett https://github.com/nothings/stb to load .jpg and .png files, and an open-source library KTX-Software from Khronos https://github.com/KhronosGroup/KTX-Software to compress images and save the compressed BC7 images in the .ktx file format, making them suitable for runtime use.
How to do it…
Section titled “How to do it…”Let’s check the code in Chapter01/05_BC7Compression/src/main.cpp to load a .jpg file data/wood.jpg, compress it and save into .cache/image.ktx:
- First, we load the file using the
STB_Imagelibrary.int main(){const int numChannels = 4;int origW, origH;const uint8_t* pixels = stbi_load("data/Chapter02/03_STB.jpg",&origW, &origH, nullptr, numChannels); - Next, we create a KTX texture object to store the compressed image. We calculate the number of mip-levels to generate the full
BC7-compressed mip-pyramid for this image.const uint32_t numMipLevels =lvk::calcNumMipLevels(origW, origH);ktxTextureCreateInfo createInfo = {.glInternalformat = GL_COMPRESSED_RGBA_BPTC_UNORM,.vkFormat = VK_FORMAT_BC7_UNORM_BLOCK,.baseWidth = (uint32_t)origW,.baseHeight = (uint32_t)origH,.baseDepth = 1u,.numDimensions = 2u,.numLevels = numMipLevels,.numLayers = 1u,.numFaces = 1u,.generateMipmaps = KTX_FALSE,};ktxTexture1* texture = nullptr;ktxTexture1_Create(&createInfo,KTX_TEXTURE_CREATE_ALLOC_STORAGE, &texture); - Let’s go through each mip-level, generate a down-sampled version of the image for each one, and store it in the KTX texture.
int w = origW;int h = origH;for (uint32_t i = 0; i != numMipLevels; ++i) {size_t offset = 0;ktxTexture_GetImageOffset(ktxTexture(textureKTX2), i, 0, 0, &offset);stbir_resize_uint8_linear((const unsigned char*)pixels, origW, origH, 0,ktxTexture_GetData(ktxTexture(textureKTX2)) + offset,w, h, 0, STBIR_RGBA);h = h > 1 ? h >> 1 : 1;w = w > 1 ? w >> 1 : 1;}
- Use KTX-Software to compress the image, including its entire mip-pyramid, into the
Basisformat. Then, transcode theBasisformat toBC7.ktxTexture2_CompressBasis(textureKTX2, 255);ktxTexture2_TranscodeBasis(textureKTX2, KTX_TTF_BC7_RGBA, 0); - Use KTX-Software to save the image in the
KTX1file format. We choose the olderKTX1format because viewing tools for it are more widely available than those forKTX2. For instance, you can use PicoPixel to view the resulting files.ktxTextureCreateInfo createInfoKTX1 = {.glInternalformat = GL_COMPRESSED_RGBA_BPTC_UNORM,.vkFormat = VK_FORMAT_BC7_UNORM_BLOCK,.baseWidth = (uint32_t)origW,.baseHeight = (uint32_t)origH,.baseDepth = 1u,.numDimensions = 2u,.numLevels = numMipLevels,.numLayers = 1u,.numFaces = 1u,.generateMipmaps = KTX_FALSE,};ktxTexture1* textureKTX1 = nullptr;ktxTexture1_Create(&createInfoKTX1,KTX_TEXTURE_CREATE_ALLOC_STORAGE, &textureKTX1);for (uint32_t i = 0; i != numMipLevels; ++i) {size_t offset1 = 0;ktxTexture_GetImageOffset(ktxTexture(textureKTX1), i, 0, 0, &offset1);size_t offset2 = 0;ktxTexture_GetImageOffset(ktxTexture(textureKTX2), i, 0, 0, &offset2);memcpy(ktxTexture_GetData(ktxTexture(textureKTX1)) + offset1,ktxTexture_GetData(ktxTexture(textureKTX2)) + offset2,ktxTexture_GetImageSize(ktxTexture(textureKTX1), i));}ktxTexture_WriteToNamedFile(ktxTexture(textureKTX1), ".cache/image.ktx");ktxTexture_Destroy(ktxTexture(textureKTX1));ktxTexture_Destroy(ktxTexture(textureKTX2));stbi_image_free(pixels);return 0;}
The image is now saved in the cache/image.ktx file. In the following chapters, we’ll load it into a Vulkan texture.
There’s more…
Section titled “There’s more…”The KTX File Format Specification is maintained by Khronos and is located at https://registry.khronos.org/KTX/specs/1.0/ktxspec.v1.html. We use KTX Version 1.0 throughout this book for compatibility with PicoPixel.
PicoPixel is a great tool that you can use to view .ktx files and other texture formats https://pixelandpolygon.com. It is freeware but not open source. There is a publicly available issues tracker on GitHub. You can find it at https://github.com/inalogic/pico-pixel-public/issues.
For those who want to jump into the latest state-of-the-art texture compression techniques, check out please refer to the Basis project from Binomial at https://github.com/BinomialLLC/basis_universal.
Let’s move on to the next chapter and learn how to start working with Vulkan.