Skip to content
ImagineWorld

Physically Based Rendering Using the glTF 2.0 Shading Model

node_idnode-book_vulkan-3d-graphics-rendering-cookbook_chapter-06-physically-based-rendering-using-the-gltf-2-0-shading-model
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num6
chapter_titlePhysically Based Rendering Using the glTF 2.0 Shading Model
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 6 — Physically Based Rendering Using the glTF 2.0 Shading Model

Section titled “Chapter 6 — Physically Based Rendering Using the glTF 2.0 Shading Model”

This chapter will cover the integration of physically based rendering (PBR) into your graphics applications. We use the glTF 2.0 shading model as an example. PBR is not a single specific technique but rather a set of concepts, like using measured surface values and realistic shading models, to accurately represent real-world materials. Adding PBR to your graphics application or retrofitting an existing rendering engine with PBR might be challenging because it requires multiple big steps to be completed and work simultaneously before a correct image can be rendered.

Our goal here is to show how to implement all these steps from scratch. Some of these steps, like precomputing irradiance maps or Bidirectional Reflectance Distribution Function (BRDF) look-up tables, require additional tools to be written. We are not going to use any third-party tools here and will show how to implement the entire skeleton of a PBR pipeline from the ground up including creation of rudimental tools for the work. Some pre-calculations can be done using General-purpose Graphics Processing Unit (GPGPU) techniques and compute shaders, all of which will be covered here as well.

In this chapter, we will learn the following recipes:

  • An introduction to glTF 2.0 physically based shading model
  • Rendering unlit glTF 2.0 materials
  • Precomputing BRDF look-up tables
  • Precomputing irradiance maps and diffuse convolution
  • Implementing the glTF 2.0 core metallic-roughness shading model
  • Implementing the glTF 2.0 core specular-glossiness shading model Note In all future references to the glTF specification, we mean the glTF 2.0 Specification. glTF 1.0 is obsolete and deprecated and we do not cover it in this book.

An introduction to glTF 2.0 physically based shading model

Section titled “An introduction to glTF 2.0 physically based shading model”

In this section, we will learn the PBR Material basics and provide enough context for the actual implementation of some ratified glTF 2.0 PBR extensions. The actual code would be presented in the subsequent recipes and chapters. Since the topic of PBR rendering is vast, we focus on the minimalistic implementation just to guide you and get you started. In the book text right here, we focus on the GLSL shader code for the glTF 2.0 PBR shading model. Roughly speaking, rendering a physically-based image is nothing more than running a fancy pixel shader with a set of textures.

We assume readers already have some basic understanding of linear algebra and calculus. It is recommended to get yourself familiar with the glTF 2.0 specification, which can be found at https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html.

Physically-based rendering (PBR) is a set of techniques that aim to simulate how light interacts with real-world materials. By using realistic models for light scattering and reflection, PBR materials can create much more believable and immersive visuals compared to traditional methods.

The glTF PBR material model is a standardized way of representing physically-based materials in the glTF 2.0 format. This model allows for the creation of highly realistic 3D content across diverse platforms and applications, making it a crucial tool for modern 3D development.

Let’s step back and see what a ray of light is as a physical phenomenon - it’s a geometric line along which light energy travels, or a beam of light. It has a starting point and a direction of propagation. Two important interactions of light with surfaces are: reflection and diffusion (also known as “specular” and “diffuse” reflection, respectively). While we intuitively understand these concepts through everyday experience, their physical characteristics may be less familiar.

When light encounters a surface, part of it bounces back in the opposite direction of the surface’s normal, like how a ball rebounds at an angle off a wall. This type of reflection, occurring on smooth surfaces, creates a mirror-like effect called specular reflection (derived from speculum, a Latin word for “mirror”).

However, not all the light reflects. Some light penetrates the surface, where it can either be absorbed, converted into heat, or scattered in various directions. The scattered light that exits the surface again is known as diffuse light, photon diffusion, or subsurface scattering. These terms all refer to the same physical phenomenon of photons movement. However, diffusion and scattering are different in how they disperse photons. Scatter involves photons being redirected in various directions, while diffusion involves photons spreading out evenly.

The way materials absorb and scatter diffuse light varies for different wavelengths of light, giving objects their distinct colors. For example, an object that absorbs most colors but scatters blue light will appear blue. This scattering is often so chaotic that it appears the same from all directions, unlike a specular mirror-like reflection.

Figure 6.1: Diffuse and Specular Reflection

Simulating this behavior in computer graphics often requires only a single input: albedo, which represents the color defined by a mix of the fractions of various light wavelengths that scatter back out of a surface. The term diffuse color is often used interchangeably.

When materials have wider scattering angles, such as human skin or milk, simulating their lighting requires more complex approaches than simple light interaction with a surface. This is because the light scattering in these materials is not just limited to the surface, but also occurs within the material itself.

For thin objects, the light can even scatter out of their back side, making them translucent. As the scattering further decreases, like in glass, the material becomes transparent, allowing entire images to pass through it preserving their visible shape.

These unique light scattering behaviors are significantly different from the typical “close to the surface” diffusion, requiring special handling for accurate rendering.

The fundamental principle in PBR revolves around the law of conservation of energy. This law asserts that within an isolated system, the overall energy remains unchanged. In the context of rendering, it signifies that the quantity of incoming light at any given location in the scene equals the combined amount of light that is reflected, transmitted, and absorbed at that location.

Enforcing energy conservation is crucial for physically-based rendering. It allows assets to adjust reflectivity and albedo values for a material without inadvertently violating the laws of physics, which often leads to unnatural- looking results. Implementing these constraints in code prevents assets from deviating too far from the reality or becoming inconsistent under varying lighting conditions.

Implementing this principle in a shading system is straightforward. We simply subtract reflected light before computing the diffuse shading. This implies that highly reflective objects will exhibit minimal to no diffuse light, as most of the light is reflected instead of penetrating the surface. Conversely, materials with strong diffusion cannot be particularly reflective.

In any given environment, one can readily observe various complex surfaces that exhibit distinct light interactions. These unique surface properties find representation by considering general mathematical functions known as Bidirectional Scattering Distribution Functions (BSDFs).

Think of a BSDF as an equation that describes how light scatters upon encountering a surface. It considers the surface’s physical properties and predicts probabilities of incident light coming from one direction getting scattered in other directions.

Although the term BSDF might sound complex, let’s break it down:

  • Bidirectional: This refers to the two-way nature of light interaction with a surface. Incident light arrives at a surface from one direction and then scatters in various directions.
  • Scattering: This describes how incident light can be redirected into multiple outgoing directions. This can involve reflection, transmission, or a combination of both.
  • Distribution Function: This defines the probability of light scattering in a particular direction based on surface’s characteristics. The distribution can range from perfectly uniform scattering to a concentrated reflection in a single direction.

In practice, the BSDF is usually split into two parts which are treated separately:

  • Bidirectional Reflectance Distribution Functions (BRDFs): These functions specifically describe how incident light is reflected from a surface. They explain why a seemingly white light source illuminating a banana makes it appear yellow instead. The BRDF reveals that the banana primarily reflects light in the yellow part of the spectrum while absorbing or transmitting other wavelengths.
  • Bidirectional Transmittance Distribution Functions (BTDFs): These functions specifically describe how light is transmitted through a material. This is evident in materials such as glass and plastics, where we see how incident light passes through the material.

Additionally, other types of BSDFs exist to account for more complex light interaction phenomena, such as subsurface scattering. This occurs when light enters a material and bounces around before re-emerging in a new direction at points significantly distant from the points of incidence of the incident rays.

Figure 6.2: BRDF and BTDF

There are 4 primary surface types characterized by their reflection distribution functions (BRDFs), which define the likelihood of light scattering in various directions:

  • Diffuse surfaces scatter light uniformly in all directions, exemplified by the consistent color of a matte paint.
  • Glossy specular surfaces preferentially scatter light in specific reflected directions, exhibiting blurred reflections such as specular highlights on plastic.
  • Perfect specular surfaces scatter light precisely in a single outgoing direction, mirroring the incident light with respect to the surface normal—similar to flawless reflections seen in perfect mirrors.
  • Retro-reflective surfaces scatter light predominantly back along the incident direction back to the light source, akin to the specular highlights observed on velvet or road signs.

However, it’s improbable that a real-world surface strictly adheres to only one of these models. As a result, most materials can be modelled as intricate combinations of these surface types.

Moreover, each type of reflection— diffuse, glossy specular, perfect specular, and retro-reflective— can exhibit isotropic or anisotropic distributions:

  • Isotropic reflections maintain a consistent amount of reflected light at a point, irrespective of the object rotation angle. This characteristic aligns with the behavior of most surfaces encountered in daily life.
  • Anisotropic reflections vary in the amount of reflected light based on orientation of object to the light source. This occurs due to the alignment of small surface irregularities aligned predominantly in one direction, resulting in elongated and blurry reflections. Such behavior is noticeable in materials such as brushed metal and velvet.

Reflection distribution types can be used for transmission as well, except for retro-reflection. Conversely, when light passes through a material, its path is affected by the material’s properties. To illustrate this difference from reflection, consider a single light ray passing through a material, like perfect specular transmission. In perfect specular transmission, the medium’s refractive index determines the direction in which light travels. This behavior adheres to Snell’s Law, which is described using the equation,.

Figure 6.3: The index of refraction

Here, n represents the refractive index of the first and second media, while θ denotes the angle of the incoming light concerning the surface normal. Consequently, when both media share identical refractive indices, light proceeds in a perfectly straight path. Conversely, if the refractive indices differ, the light changes its direction upon transitioning into the next medium. A notable instance of this is when light shifts direction upon entering water from air, leading to distortions in our underwater observations. This contrasts with perfect specular reflection, where the incoming angle always equals the outgoing angle.

It is important for physically- based renderers to know how much light is reflected or transmitted on the surface. It is a combination of these effects that describes substances such as honey and stained glass that both have color and can be seen through.

These amounts are directly related to each other and described by the Fresnel equations.

These equations are tailored for two types of media: conductors (metals) and dielectrics (nonmetals). Metals do not transmit light, they only reflect it entirely, or practically entirely. Dielectrics possess the property of diffuse reflection — light rays pass beneath the surface of the material and some of them are absorbed, while some are returned in the form of reflection. This is particularly evident in the specular highlight of these materials — for metals, it will be colored, while for dielectrics it appears white or, more accurately, retains the color of the incident light.

Although both conductors and dielectrics are subject to the same set of Fresnel equations, glTF 2.0 opts to develop a distinct evaluation function for dielectrics. This choice is made to leverage the notably straightforward structure that these equations assume when the refractive indices are ensured to be real numbers.

  • Nonmetals (dielectrics): These are materials like glass, plastic, and ceramics, which lack distinctive metallic properties.
  • Metals (conductors): These materials could conduct both heat and electricity to a certain extent. Examples include many metals, such as copper, silver, and gold, though not all metals exhibit this property. Unlike dielectrics, conductors do not transmit light; rather, they absorb some of the incident light, converting it into heat.

According to the microfacet theory, a rough surface is composed of countless microfacets or tiny surface elements, each having its own orientation with respect to the surface normal. These microfacets scatter incoming light in different directions due to their orientations, resulting in a diffused reflection rather than a perfect mirror-like reflection.

  • Blinn-Phong Model: It was introduced by James F. Blinn in 1977 as an enhancement to the empirical Phong reflection model, devised by Bui Tuong Phong in 1973.

This model computes the intensity of the reflected light based on the angle between the viewer’s direction and the halfway vector h=(L+V)/length(L+V), which is halfway between the light direction L and the view direction V. The model includes a specular term that provides a highlight on the surface, simulating the effect of a shiny surface.

  • Cook-Torrance Model; In 1982, Robert Cook and Kenneth Torrance introduced a reflectance model that offered a more precise depiction of light reflectance in comparison to the Phong and Blinn-Phong models. The microfacet BRDF equation is as follows:

Where:

  • f r (ω i,ω o) is the microfacet BRDF,
  • F(ω i,h) is the Fresnel term,
  • D(h) is the microfacet distribution function,
  • G(ω i,ω o,h) is the geometry function,
  • ω i is the incident light direction,
  • ω o is the outgoing light direction,
  • h is the half vector,
  • n is the surface normal.

The proposed approach is versatile, featuring three interchangeable component functions F, D, G which can be substituted with equations of your preference. Additionally, it is highly effective at accurately representing a wide range of real-world materials.

This equation represents the amount of light reflected in a specific direction ω o given an incident light direction ω i and the surface properties. The initial component F represents the Fresnel effect, the subsequent component D is a normal distribution function (NDF), and the final component accounts for the shadowing factor G referred to as the G term.

Of all the factors in this formulation, the NDF term typically exerts the greatest importance. The specific form of the NDF is heavily influenced by the roughness of the BRDF. To sample the microfacet BRDF model efficiently, it is customary to first sample the NDF, obtaining a random microfacet normal that conforms to the NDF, and subsequently reflecting the incident radiance along this normal to determine the outgoing direction.

The normalization requirement for the Normal Distribution Function (NDF) in microfacet theory ensures that the total amount of energy reflected or transmitted by a surface remains consistent across different roughness levels.

In microfacet theory, the NDF describes the statistical distribution of microfacet normals on a surface. It specifies the probability density of finding a microfacet with a particular orientation. When integrating the BRDF over all possible directions, the integral should yield a value representing the total reflectance or transmittance of the surface.

Normalization of the NDF guarantees that the total amount of light reflected or transmitted by the surface remains constant, regardless of the surface roughness. This ensures energy conservation, a fundamental principle in physics stating that energy cannot be created or destroyed, only transformed, or transferred.

Several NDFs are commonly used to simulate the behavior of surfaces with microscale roughness. Here are some examples: GGX, Beckmann, Blinn. In the next recipes, we will learn how to implement some of them.

Materials serve as high-level descriptions utilized to represent surfaces, defined by combinations of BRDF s (Bidirectional Reflectance Distribution Functions) and BTDFs (Bidirectional Transmittance Distribution Functions). These BSDF s are articulated as parameters that govern the visual characteristics of the material. For instance, a matte material can be delineated by specifying a diffuse reflection value to elucidate how light interacts with the surface, along with a scalar roughness value to characterize its texture. Transitioning from a matte to a plastic material could be achieved by simply appending a glossy specular reflection value to the matte material, thus recreating the specular highlights typical of plastics.

The glTF PBR specification approaches material representation in a manner that emphasizes realism, efficiency, and consistency across different rendering engines and applications.

One key aspect of the glTF PBR specification is its adherence to physically based principles. This means that the materials defined in glTF accurately simulate real-world behavior, such as how light interacts with surfaces. Parameters like base color (albedo), roughness, metallic, and specular are used to describe materials, aligning with physical properties like surface color, smoothness, metallicity, and specular reflectivity.

Another notable feature of the glTF PBR approach is its simplicity and ease of implementation. By standardizing the parameters used to describe materials, glTF simplifies the process of creating and exporting 3D models with PBR materials. This consistency across different applications and rendering engines streamlines the workflow for artists and developers, enabling them to work more efficiently and interchangeably.

Furthermore, the glTF PBR specification is designed for real-time rendering applications, making it well-suited for use in interactive experiences, games, and other real-time graphics applications. Its efficient representation of materials and optimized file format contribute to faster loading times and better performance in real-time rendering scenarios.

Overall, the glTF PBR specification stands out for its commitment to physical accuracy, simplicity, and efficiency, making it a preferred choice for representing materials in 3D graphics applications. Its widespread adoption and support across various platforms further cement its status as a leading standard for PBR material representation.

More information

The Khronos 3D Formats Working Group is continually striving to enhance PBR material capabilities by introducing new extension specifications. You can always stay updated on the status of ratified extensions by visiting Khronos GitHub page: https://github.com/KhronosGroup/glTF/blob/main/extensions/README.md

For those looking to deepen their knowledge, be sure to check out the free book Physically Based Rendering: From Theory to Implementation by Matt Pharr, Wenzel Jakob, and Greg Humphreys available online at http://www.pbr-book.org. Another great reference is the book Real Time Rendering, 4th Edition by Tomas Akenine-Möller, Eric Haines, and Naty Hoffman.

Also, we recommend SIGGRAPH’s Physically Based Rendering courses. For example, you can find a comprehensive collection of links on GitHub https://github.com/neil3d/awesome-pbr.

Besides that, the Filament rendering engine provides a very comprehensive explanation of PBR materials: https://google.github.io/filament/Filament.md.html.

In this recipe, we begin developing a code framework that enables us to load and render glTF 2.0 assets.

We start with the unlit material because it’s the simplest glTF 2.0 PBR material extension, and its shader implementation is straightforward. The official name of the extension is KHR_materials_unlit, and you can find the specification here: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_unlit.

The unlit material is technically not PBR-based because it may violate energy conservation principles or create artistic representations that don’t follow the laws of physics. It was designed with the following motivation:

  • Mobile devices with limited resources, where unlit materials offer a more performant alternative to higher-quality shading models.
  • Photogrammetry, in which the lighting information is already prebaked into the texture data and no additional lighting should be applied.
  • Stylized materials (such as those resembling “anime” or hand-drawn art), where lighting is intentionally excluded for aesthetic reasons.

Let’s get started with the basic implementation.

The source code for this recipe is located in Chapter06/01_Unlit/main.cpp. The corresponding GLSL vertex and fragment shaders are located in main.vert and main.frag.

We will create a feature-rich glTF viewer in the following chapters. In this chapter, we start building a simple framework that allows us to load and render basic glTF models.

We use VulkanApp and the Assimp library from previous chapters. As usual, most of the error checking is omitted from the book text but is present in the actual source code files.

  1. Let’s load our .gltf file using Assimp. As you can see, the loading function is a single line of code. Assimp supports loading of .gltf and .glb files out of the box. We use the DamagedHelmet asset from the official Khronos repository https://github.com/KhronosGroup/glTF-Sample-Assets/tree/main/Models/DamagedHelmet. This model uses the Metallic-Roughness material, but for the demonstration purposes we apply the unlit shader to it
    const aiScene* scene = aiImportFile("deps/src/glTF-Sample-
    Assets/Models/DamagedHelmet/glTF/DamagedHelmet.gltf",
    aiProcess_Triangulate);
  2. The next step is to build the mesh geometry. The unlit material uses only the baseColor property of material in 3 different input forms: as a vertex attribute, as a static fragment shader color factor and as a base color texture input. For our vertex format, it means we need to provide the following 3 per-vertex attributes:
    struct Vertex {
    vec3 position;
    vec4 color;
    vec2 uv;
    };
  3. To fill in these attributes, we use following code. Empty colors are filled with the white color value (1, 1, 1, 1) and empty texture coords are filled with zeroes (0, 0, 0) according to the glTF specification:
    std::vector<Vertex> vertices;
    vertices.reserve(mesh->mNumVertices);
    for (unsigned int i = 0; i != mesh->mNumVertices; i++) {
    const aiVector3D v = mesh->mVertices[i];
    const aiColor4D c = mesh->mColors[0] ?
    mesh->mColors[0][i] : aiColor4D(1, 1, 1, 1);
    const aiVector3D t = mesh->mTextureCoords[0] ?
    mesh->mTextureCoords[0][i] : aiVector3D(0, 0, 0);
    vertices.push_back({ .position = vec3(v.x, v.y, v.z),
    .color = vec4(c.r, c.g, c.b, c.a),
    .uv = vec2(t.x, 1.0f - t.y) });
    }

If a vertex color is not presented in the mesh, then we replace it with the default white color. It is a convenient way to simplify the final shader permutation where we can just combine all 3 inputs in a simple manner. We will come back to it later in this recipe.

  1. We build the index buffer using the Assimp mesh faces information:
    std::vector<uint32_t> indices;
    indices.reserve(3 * mesh->mNumFaces);
    for (unsigned int i = 0; i != mesh->mNumFaces; i++) {
    for (int j = 0; j != 3; j++)
    indices.push_back(mesh->mFaces[i].mIndices[j]);
    }
  2. After that, we should load a diffuse, or albedo base color texture. For simplicity, we use the hardcoded file path here instead of obtaining it from the .gltf model:
    Holder<TextureHandle> baseColorTexture =
    loadTexture(ctx, "deps/src/glTF-Sample-
    Assets/Models/DamagedHelmet/glTF/Default_albedo.jpg");
  3. The vertex and index data are static and can be uploaded into corresponding Vulkan buffers:
    Holder<BufferHandle> vertexBuffer = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Vertex,
    .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" });
  4. To finish the mesh setup, we need to load GLSL shaders and create a render pipeline. The member fields of the VertexInput struct correspond to the Vertex struct mentioned above.
    const lvk::VertexInput vdesc = {
    .attributes = { { .location = 0,
    .format = lvk::VertexFormat::Float3,
    .offset = 0 },
    { .location = 1,
    .format = lvk::VertexFormat::Float4,
    .offset = sizeof(vec3) },
    { .location = 2,
    .format = lvk::VertexFormat::Float2,
    .offset = sizeof(vec3) + sizeof(vec4) }},
    .inputBindings = { { .stride = sizeof(Vertex) } }};
    Holder<ShaderModuleHandle> vert =
    loadShaderModule(ctx, "Chapter06/01_Unlit/src/main.vert");
    Holder<ShaderModuleHandle> frag =
    loadShaderModule(ctx, "Chapter06/01_Unlit/src/main.frag");
    Holder<RenderPipelineHandle> pipelineSolid =
    ctx->createRenderPipeline({
    .vertexInput = vdesc,
    .smVert = vert,
    .smFrag = frag,
    .color = {{ .format = ctx->getSwapchainFormat() }},
    .depthFormat = app.getDepthFormat(),
    .cullMode = lvk::CullMode_Back });

This was the preparation code. Let’s now look inside the application main loop.

  1. Within the rendering loop, we prepare the model-view-projection matrix mvp and pass it into GLSL shaders using push constants and the PerFrameData structure together with the base color value and the albedo texture id.
    const mat4 m1 = glm::rotate(
    mat4(1.0f), glm::radians(+90.0f), vec3(1, 0, 0));
    const mat4 m2 = glm::rotate(
    mat4(1.0f), (float)glfwGetTime(), vec3(0.0f, 1.0f, 0.0f));
    const mat4 v = app.camera_._.getViewMatrix();
    const mat4 p = glm::perspective(45.0f, aspectRatio, 0.1f, 1000.0f);
    struct PerFrameData {
    mat4 mvp;
    vec4 baseColor;
    uint32_t baseTextureId;
    } perFrameData = {
    .mvp = p * v * m2 * m1,
    .baseColor = vec4(1, 1, 1, 1),
    .baseTextureId = baseColorTexture.index(),
    };
  2. Now the actual 3D mesh rendering is simple, so we post the code here in its entirety:
    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() },
    };
    lvk::ICommandBuffer& buf = ctx->acquireCommandBuffer();
    buf.cmdBeginRendering(renderPass, framebuffer);
    buf.cmdBindVertexBuffer(0, vertexBuffer, 0);
    buf.cmdBindIndexBuffer(indexBuffer, lvk::IndexFormat_UI32);
    buf.cmdBindRenderPipeline(pipelineSolid);
    buf.cmdBindDepthState({ .compareOp = lvk::CompareOp_Less,
    .isDepthWriteEnabled = true });
    buf.cmdPushConstants(perFrameData);
    buf.cmdDrawIndexed(indices.size());
  3. A few nice touches at the end to render the infinite grid as described in the recipe Chapter 5 and the FPS counter as described in the recipe Chapter 4.
    app.drawGrid(buf, p, vec3(0, -1.0f, 0));
    app.imgui_->beginFrame(framebuffer);
    app.drawFPS();
    app.imgui_->endFrame(buf);
    buf.cmdEndRendering();
    ctx->submit(buf, ctx->getCurrentSwapchainTexture());

This was all the C++ code. Now, let’s dive into the GLSL shaders for this example. They’re straightforward and short.

  1. The vertex shader Chapter06/01_Unlit/src/main.vert does the vertex transformation and pre-multiplies the per-vertex color with the provided base color value from push constants.
    layout(push_constant) uniform PerFrameData {
    mat4 MVP;
    vec4 baseColor;
    uint textureId;
    };
    layout (location = 0) in vec3 pos;
    layout (location = 1) in vec4 color;
    layout (location = 2) in vec2 uv;
    layout (location = 0) out vec2 outUV;
    layout (location = 1) out vec4 outVertexColor;
    void main() {
    gl_Position = MVP * vec4(pos, 1.0);
    outUV = uv;
    outVertexColor = color * baseColor;
    }
  2. The fragment shader Chapter06/01_Unlit/src/main.frag is very simple as well. All it does is multiply the precomputed per-vertex base color value by the color value sampled from the albedo texture. The glTF 2.0 specification mandates to provide at least one baseColorFactor value for the Metallic-Roughness property and this guarantees the correctness of the result as long as we keep all the remaining parameters equal to 1.
    layout(push_constant) uniform PerFrameData {
    mat4 MVP;
    vec4 baseColor;
    uint textureId;
    };
    layout (location = 0) in vec2 uv;
    layout (location = 1) in vec4 vertexColor;
    layout (location=0) out vec4 out_FragColor;
    void main() {
    vec4 baseColorTexture = textureBindless2D(textureId, 0, uv);
    out_FragColor = textureBindless2D(textureId, 0, uv) * vertexColor;
    }

The running application Chapter06/01_Unlit/src/main.cpp should look as in the following screenshot.

Figure 6.4: Unlit glTF2 model

In this example, we enforced the use of the albedo texture for rendering to keep the code simple for easier understanding. In the subsequent chapters, we’ll fully support various combinations of material parameters as specified in the glTF 2.0 specification, providing a more accurate and complete glTF 2.0 viewer implementation.

In the previous recipes, we learned the basic theory behind glTF 2.0 PBR and implemented a simple unlit glTF 2.0 renderer. Let’s continue our PBR exploration and learn how to precompute the Smith GGX BRDF look-up table (LUT) for our upcoming glTF 2.0 viewer.

To render a PBR image, we have to evaluate the BRDF at each point on the surface being rendered, considering the surface properties and the viewing direction. This is computationally expensive and many real-time implementations, including the reference glTF-Sample-Viewer from Khronos, use precalculated tables of some sort to find the BRDF value based on surface roughness and the viewing direction. BRDF LUT can be stored as a two-dimensional texture.

The X-axis represents the dot product between the surface normal vector and the viewing direction, while the Y-axis represents the surface roughness values 0...1. Each texel holds three 16-bit floating point values. The first two values represent the scale and bias to F0, which is the specular reflectance at normal incidence. The third value is utilized for the sheen material extension, which will be covered in the following chapter.

We are going to use Vulkan to calculate this LUT texture on the GPU and implement a compute shader to do it.

It is helpful to revisit the Vulkan compute pipeline creation from the Generating textures in Vulkan using compute shaders in Chapter 5. Our implementation is based on a shader from https://github.com/KhronosGroup/glTF-Sample-Viewer, which runs very similar computations in a fragment shader. Our GLSL compute shader can be found in Chapter06/02_BRDF_LUT/src/main.comp.

Earlier in this chapter, we explained what BRDF is and introduced its components, such as the Fresnel term F, the Normal Distribution Function NDF, and the Geometry term G. As you may notice, the BRDF results depend on several factors, such as the incident and outgoing light directions, surface normal, and viewer’s direction.

Were the individual terms have the following meaning.

D is the GGX NDF microfacet distribution function:

G accounts for mutual shadowing of microfacets and looks as follows:

And the Fresnel F term determines how much light is reflected from the surface at a given angle of incidence:

If we examine any component of the BRDF, we’ll see that they are all quite complex for real-time per-pixel calculations. To simplify this, we can use an offline process to precompute certain parts of the BRDF equation.

As you can see, the G term and certain parts of the F term depend only on v, h and Roughness parameters. We can leverage this for precomputation. Additionally, note that we never need n and v separately, so we can always use their dot product instead.

One important question remains: how can we iterate through all possible v and n combinations? To do this, we need to integrate over all angles on a hemisphere, but we can use a simpler approximation. To keep it efficient, we make two assumptions. First, we must integrate using a limited number of samples. Second, we need to choose those samples wisely rather than randomly.

As described in the book GPU Gems 3, Chapter 20, GPU-Based Importance Sampling https://developer.nvidia.com/gpugems/gpugems3/part-iii-rendering/chapter-20-gpu-based-importance-sampling, the solution is to use Monte Carlo estimation with importance sampling. Monte Carlo estimation allows us to approximate an integral using a weighted sum of random samples. Importance sampling takes this further by prioritizing random points on the hemisphere that have a greater influence on the function being estimated.

The paper Real Shading in Unreal Engine 4 by Brian Karis offers a detailed explanation of the mathematical aspects. We highly recommend reading it for a deeper understanding of the math behind physically-based rendering https://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf.

Before we investigate the GLSL shader code, let’s implement all the necessary C++ code to process data arrays on the GPU.

To manipulate data buffers on the GPU and utilize the data effectively, we require four basic operations: loading a shader module, creating a compute pipeline, creating a buffer, and dispatching compute commands. After that, we need to transfer the data from the GPU buffer to the host memory and save it as a texture file. Let’s walk through these steps by examining the code in Chapter06/02_BRDF_LUT/src/main.cpp.

  1. The function calculateLUT() implements most of the described functionality. We start with the shader module loading and compute pipeline creation. The GLSL shader is specialized using the constant kNumSamples which defines the number of Monte Carlo trials for our LUT calculation. We store 16-bit float RGBA values in the buffer.
    const uint32_t kBrdfW = 256;
    const uint32_t kBrdfH = 256;
    const uint32_t kNumSamples = 1024;
    const uint32_t kBufferSize = 4u * sizeof(uint16_t) * kBrdfW * kBrdfH;
    void calculateLUT(const std::unique_ptr<lvk::IContext>& ctx,
    void* output, uint32_t size)
    {
    Holder<ShaderModuleHandle> comp = loadShaderModule(
    ctx, "Chapter06/02_BRDF_LUT/src/main.comp");
    Holder<ComputePipelineHandle> computePipelineHandle =
    ctx->createComputePipeline({
    .smComp = comp,
    .specInfo = {.entries = {{ .constantId = 0,
    .size = sizeof(kNumSamples) }},
    .data = &kNumSamples,
    .dataSize = sizeof(kNumSamples),},
    });
  2. The next step is to create a GPU storage buffer for our output data:
    Holder<BufferHandle> dstBuffer = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Storage,
    .storage = lvk::StorageType_HostVisible,
    .size = size,
    .debugName = "Compute: BRDF LUT" });
  3. And finally, we acquire a command buffer, update push constants, and dispatch the compute commands.
    lvk::ICommandBuffer& buf = ctx->acquireCommandBuffer();
    buf.cmdBindComputePipeline(computePipelineHandle);
    struct {
    uint32_t w = kBrdfW;
    uint32_t h = kBrdfH;
    uint64_t addr;
    } pc {
    .addr = ctx->gpuAddress(dstBuffer),
    };
    buf.cmdPushConstants(pc);
    buf.cmdDispatchThreadGroups({ kBrdfW / 16, kBrdfH / 16, 1 });
  4. Before reading the generated data back to the CPU memory, we must wait for the GPU to finish processing the buffer. It can be done using the wait() function which waits for a command buffer to finish. We discussed it in the recipe Chapter 2. Once the GPU has finished working, we can copy the memory-mapped buffer back to the CPU memory referenced by the pointer output.
    ctx->wait(ctx->submit(buf));
    memcpy(output, ctx->getMappedPtr(dstBuffer), kBufferSize);
    }

That was the C++ part. Now let’s investigate the GLSL shader compute code Chapter06/02_BRDF_LUT/src/main.comp:

  1. To break down our work into smaller pieces, we start from the shader preamble and the main() function of the BRDF LUT calculation shader. The preamble code sets the compute shader dispatching parameters. In our case, a 16x16 chunk of the LUT texture is calculated by one GPU work group. The number of Monte Carlo trials for numeric integration is declared as a specialization constant we can override from the C++ code:
    layout (local_size_x=16, local_size_y=16, local_size_z=1) in;
    layout (constant_id = 0) const uint NUM_SAMPLES = 1024u;
    layout (std430, buffer_reference) readonly buffer Data {
    float16_t floats[];
    };
  2. We use user-provided width and height to calculate our output buffer dimensions. Last but not least, PI is the global “physical” constant we use in the shader:
    layout (push_constant) uniform constants {
    uint BRDF_W;
    uint BRDF_H;
    Data data;
    };
    const float PI = 3.1415926536;
  3. The main() function wraps the BRDF() function call and stores the results. First, we recalculate the worker ID to output array indices:
    void main() {
    vec2 uv;
    uv.x = (float(gl_GlobalInvocationID.x) + 0.5) / float(BRDF_W);
    uv.y = (float(gl_GlobalInvocationID.y) + 0.5) / float(BRDF_H);
  4. The BRDF() function does all the actual work. The calculated value is put into the output array:
    vec3 v = BRDF(uv.x, 1.0 - uv.y);
    uint offset = gl_GlobalInvocationID.y * BRDF_W +
    gl_GlobalInvocationID.x;
    data.floats[offset * 4 + 0] = float16_t(v.x);
    data.floats[offset * 4 + 1] = float16_t(v.y);
    data.floats[offset * 4 + 2] = float16_t(v.z);
    }
  5. As you can see, we use 3 channels of the texture. The R and G channels are used for GGX BRDF LUT, the third channel is used for Charlie BRDF LUT which is required for the Sheen material extension and will be covered in the next Chapter 7.

Now that we have described the scaffolding parts of our compute shader, we can see how the BRDF LUT values are calculated. Let’s look at the steps:

  1. To generate random directions in a hemisphere, we use so-called Hammersley points calculated by the following function:
    vec2 hammersley2d(uint i, uint N) {
    uint bits = (i << 16u) | (i >> 16u);
    bits = ((bits & 0x55555555u)<<1u)|((bits & 0xAAAAAAAAu)>>1u);
    bits = ((bits & 0x33333333u)<<2u)|((bits & 0xCCCCCCCCu)>>2u);
    bits = ((bits & 0x0F0F0F0Fu)<<4u)|((bits & 0xF0F0F0F0u)>>4u);
    bits = ((bits & 0x00FF00FFu)<<8u)|((bits & 0xFF00FF00u)>>8u);
    float rdi = float(bits) * 2.3283064365386963e-10;
    return vec2(float(i) / float(N), rdi);
    }

Important note

The code is based on the following post: http://holger.dammertz.org:80/stuff/notes_HammersleyOnHemisphere.html. The bit-shifting magic for this and many other applications is thoroughly described in Henry J. Warren’s book called Hacker’s Delight. Interested readers may also look up the “van der Corput sequence” to see why this can be used as a series of random directions on a hemisphere.

  1. We also need some kind of a pseudorandom number generator. We use the output array indices as an input and pass them through another magic set of formulas:
    float random(vec2 co) {
    float a = 12.9898;
    float b = 78.233;
    float c = 43758.5453;
    float dt = dot( co.xy ,vec2(a,b) );
    float sn = mod(dt, 3.14);
    return fract(sin(sn) * c);
    }

Check out this link to find some useful details about this code: http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0.

  1. Let’s look at how importance sampling is implemented according to the paper Real Shading in Unreal Engine 4 by Brian Karis. Check out the fourth page of https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf. This function maps an i -th 2D point Xi to a hemisphere with spread based on surface roughness.:
    vec3 importanceSample_GGX(vec2 Xi, float roughness, vec3 normal)
    {
    float alpha = roughness * roughness;
    float phi = 2.0 * PI * Xi.x + random(normal.xz) * 0.1;
    float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (alpha * alpha - 1.0) * Xi.y));
    float sinTheta = sqrt(1.0 - cosTheta * cosTheta);
    vec3 H = vec3(sinTheta * cos(phi), sinTheta * sin(phi), cosTheta);
  2. Calculations are done in tangent space defined by the vectors up, tangentX, and tangentY and then converted to world space.
    vec3 up = abs(normal.z) < 0.999 ?
    vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
    vec3 tangentX = normalize(cross(up, normal));
    vec3 tangentY = normalize(cross(normal, tangentX));
    return normalize(tangentX * H.x +
    tangentY * H.y +
    normal * H.z);
    }
  3. Another utility function, G_SchlicksmithGGX(), calculates the GGX geometric shadowing factor:
    float G_SchlicksmithGGX(
    float dotNL, float dotNV, float roughness)
    {
    float k = (roughness * roughness) / 2.0;
    float GL = dotNL / (dotNL * (1.0 - k) + k);
    float GV = dotNV / (dotNV * (1.0 - k) + k);
    return GL * GV;
    }
  4. We also precalculate LUT for Sheen material, so there are two more helper functions V_Ashikhmin() and D_Charlie(). They are based on the code from the Filament engine https://github.com/google/filament/blob/master/shaders/src/brdf.fs#L136.
    float V_Ashikhmin(float NdotL, float NdotV) {
    return clamp(
    1.0 / (4.0 * (NdotL + NdotV - NdotL * NdotV)), 0.0, 1.0);
    }
    float D_Charlie(float sheenRoughness, float NdotH) {
    sheenRoughness = max(sheenRoughness, 0.000001);
    float invR = 1.0 / sheenRoughness;
    float cos2h = NdotH * NdotH;
    float sin2h = 1.0 - cos2h;
    return (2.0 + invR) * pow(sin2h, invR * 0.5) / (2.0 * PI);
    }
  5. Here is a corresponding sampling function importanceSample_Charlie() for the Sheen material which is very similar to importanceSample_GGX().
    vec3 importanceSample_Charlie(
    vec2 Xi, float roughness, vec3 normal)
    {
    float alpha = roughness * roughness;
    float phi = 2.0 * PI * Xi.x;
    float sinTheta = pow(Xi.y, alpha / (2.0 * alpha + 1.0));
    float cosTheta = sqrt(1.0 - sinTheta * sinTheta);
    vec3 H = vec3(sinTheta * cos(phi), sinTheta * sin(phi), cosTheta);
    vec3 up = abs(normal.z) < 0.999 ?
    vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
    vec3 tangentX = normalize(cross(up, normal));
    vec3 tangentY = normalize(cross(normal, tangentX));
    return normalize(tangentX * H.x +
    tangentY * H.y +
    normal * H.z);
    }
  6. The value of BRDF is calculated the following way, using all of the helper functions we declared above. The number of Monte Carlo trials NUM_SAMPLES is set earlier to be 1024. The normal vector N always points along the Z-axis for the 2D lookup.
    vec3 BRDF(float NoV, float roughness) {
    const vec3 N = vec3(0.0, 0.0, 1.0);
    vec3 V = vec3(sqrt(1.0 - NoV* NoV), 0.0, NoV);
    vec3 LUT = vec3(0.0);
  7. The first loop calculates the R and G components of our LUT which correspond to the scale and bias to F0.
    for (uint i = 0u; i < NUM_SAMPLES; i++) {
    vec2 Xi = hammersley2d(i, NUM_SAMPLES);
    vec3 H = importanceSample_GGX(Xi, roughness, N);
    vec3 L = 2.0 * dot(V, H) * H - V;
    float dotNL = max(dot(N, L), 0.0);
    float dotNV = max(dot(N, V), 0.0);
    float dotVH = max(dot(V, H), 0.0);
    float dotNH = max(dot(H, N), 0.0);
    if (dotNL > 0.0) {
    float G = G_SchlicksmithGGX(dotNL, dotNV, roughness);
    float G_Vis = (G * dotVH) / (dotNH * dotNV);
    float Fc = pow(1.0 - dotVH, 5.0);
    LUT.rg += vec2((1.0 - Fc) * G_Vis, Fc * G_Vis);
    }
    }
  8. The third component B used for the sheen material is calculated in another loop. We will revisit it in the next Chapter 6.
    for (uint i = 0u; i < NUM_SAMPLES; i++) {
    vec2 Xi = hammersley2d(i, NUM_SAMPLES);
    vec3 H = importanceSample_Charlie(Xi, roughness, N);
    vec3 L = 2.0 * dot(V, H) * H - V;
    float dotNL = max(dot(N, L), 0.0);
    float dotNV = max(dot(N, V), 0.0);
    float dotVH = max(dot(V, H), 0.0);
    float dotNH = max(dot(H, N), 0.0);
    if (dotNL > 0.0) {
    float sheenDistribution = D_Charlie(roughness, dotNH);
    float sheenVisibility = V_Ashikhmin(dotNL, dotNV);
    LUT.b += sheenVisibility * sheenDistribution * dotNL * dotVH;
    }
    }
    return LUT / float(NUM_SAMPLES);
    }

That is the entire GLSL compute shader used to precalculate the look-up table. Let’s now see how it works from the C++ main() function.

The main() function creates a KTX texture using the KTX-Software library so that our 16-bit RGBA LUT texture can be saved into the .ktx format preserving the data. Then it calls the function calculateLUT() we discussed above which outputs the generated LUT data into the KTX texture. The texture is saved into data/brdfLUT.ktx.

int main() {
std::unique_ptr<lvk::IContext> ctx =
lvk::createVulkanContextWithSwapchain(nullptr, 0, 0, {});
ktxTextureCreateInfo createInfo = {
.glInternalformat = GL_RGBA16F,
.vkFormat = VK_FORMAT_R16G16B16A16_SFLOAT,
.baseWidth = kBrdfW,
.baseHeight = kBrdfH,
.baseDepth = 1,
.numDimensions = 2,
.numLevels = 1,
.numLayers = 1,
.numFaces = 1,
.generateMipmaps = KTX_FALSE,
};
ktxTexture1* lutTexture = nullptr;
ktxTexture1_Create(
&createInfo, KTX_TEXTURE_CREATE_ALLOC_STORAGE, &lutTexture);
calculateLUT(ctx, lutTexture->pData, kBufferSize);
ktxTexture_WriteToNamedFile(ktxTexture(lutTexture), "data/brdfLUT.ktx");
ktxTexture_Destroy(ktxTexture(lutTexture));
return 0;
}

You can use Pico Pixel https://pixelandpolygon.com to view the generated image. It should resemble the screenshot below. The horizontal axis represents the dot product between the surface normal vector and the viewing direction, while the vertical axis represents the surface roughness values 0...1. Each texel holds three 16-bit floating point values. The first two values represent the scale and bias to F0, which is the specular reflectance at normal incidence. The third value is utilized for the sheen material extension, which will be covered in the next chapter:

Figure 6.5: BRDF lookup table

This concludes the BRDF lookup table tool description. We will need yet another tool to calculate an irradiance cube map from an environment cube map which we will cover in the next recipe.

The method described above can be used to precompute BRDF look-up tables using high -quality Monte Carlo integration and store them as textures. Dependent texture fetches can be expensive on some mobile platforms. There is an interesting run-time approximation used in Unreal Engine, which does not rely on any precomputation, as described in this post Physically Based Shading on Mobile by Brian Karis https://www.unrealengine.com/en-US/blog/physically-based-shading-on-mobile. Here is the GLSL source code:

vec3 EnvBRDFApprox(vec3 specularColor, float roughness, float NoV) {
const vec4 c0 = vec4(-1, -0.0275, -0.572, 0.022);
const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04 );
vec4 r = roughness * c0 + c1;
float a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;
vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;
return specularColor * AB.x + AB.y;
}

Precomputing irradiance maps and diffuse convolution

Section titled “Precomputing irradiance maps and diffuse convolution”

As we discussed earlier in the recipe Introduction to glTF 2.0 Physically Based Shading Model, the second part of the split sum approximation necessary to calculate the glTF 2.0 physically-based shading model comes from the irradiance cube map which is precalculated by convolving the input environment cube map with the GGX distribution of our shading model. Our implementation is based on https://github.com/KhronosGroup/glTF-Sample-Viewer/blob/main/source/shaders/ibl_filtering.frag.

Image based lighting (IBL) is a technique for illuminating a scene using captured light information. This information can be stored as panoramic photos images. It is very hard to simulate entire real world environments, so capturing the real world and using images is a very common technique nowadays to produce realistic renders. Using IBL allows us to precompute the part of diffuse and specular BRDF equations and make them more runtime friendly.

If you want to dive deep into the math theory behind these computations, make sure you read Brian Karis’s paper Real Shading in Unreal Engine 4 https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf.

Check out the source code for this recipe in Chapter06/03_FilterEnvmap.

We are doing Monte-Carlo integration inside a fragment shader which is located here: Chapter06/03_FilterEnvmap/src/main.frag.

The C++ source code can be found in the Chapter06/03_FilterEnvmap/src/main.cpp file. Let’s go through the function prefilterCubemap() to precompute the irradiance and diffuse maps:

  1. First, we need to create a cube map texture to store the results of prefiltering. We use the 32-bit RGBA floating point pixel format because most of our color-related calculations happen in linear space. Low-end mobile devices might be not performant enough and, in this case, the dynamic range can be clamped to 16-bit or even 8-bit, but that might significantly impact the visual fidelity. We use cubemap mip-levels to precompute multiple lookups for different values of material roughness 0…1. The function takes in the distribution parameter which is passed to the shader to select an appropriated distribution: Lambertian, GGX, or Charlie.
    void prefilterCubemap(
    const std::unique_ptr<lvk::IContext>& ctx,
    ktxTexture1* cube, const char* envPrefilteredCubemap,
    TextureHandle envMapCube,
    Distribution distribution,
    uint32_t sampler,
    uint32_t sampleCount)
    {
    Holder<TextureHandle> prefilteredMapCube =
    ctx->createTexture({
    .type = lvk::TextureType_Cube,
    .format = lvk::Format_RGBA_F32,
    .dimensions = {cube->baseWidth, cube->baseHeight, 1},
    .usage = lvk::TextureUsageBits_Sampled |
    lvk::TextureUsageBits_Attachment,
    .numMipLevels = (uint32_t)cube->numLevels,
    .debugName = envPrefilteredCubemap,
    }, envPrefilteredCubemap);
  2. We require GLSL shader modules and a rendering pipeline.
    Holder<ShaderModuleHandle> vert = loadShaderModule(
    ctx, "Chapter06/03_FilterEnvmap/src/main.vert");
    Holder<ShaderModuleHandle> frag = loadShaderModule(
    ctx, "Chapter06/03_FilterEnvmap/src/main.frag");
    Holder<RenderPipelineHandle> pipelineSolid =
    ctx->createRenderPipeline({
    .smVert = vert,
    .smFrag = frag,
    .color = { { .format = ctx->getFormat(prefilteredMapCube) } },
    .cullMode = lvk::CullMode_Back,
    });
  3. Now we can start doing the actual rendering into the cube map. One command buffer is filled with all the commands necessary to render into 6 cubemap faces with all required mip-levels.
    lvk::ICommandBuffer& buf = ctx->acquireCommandBuffer();
    for (uint32_t mip = 0; mip < cube->numLevels; mip++) {
    for (uint32_t face = 0; face < 6; face++) {
  4. We set the cube map face we want to render to and the specific mip-level we want to render.
    buf.cmdBeginRendering(
    { .color = { { .loadOp = lvk::LoadOp_Clear,
    .layer = (uint8_t)face,
    .level = (uint8_t)mip,
    .clearColor = { 1.0f, 1.0f, 1.0f, 1.0f },
    } } },
    { .color = {{ .texture = prefilteredMapCube }} });
    buf.cmdBindRenderPipeline(pipelineSolid);
    buf.cmdBindDepthState({});
  5. Push constants are used to pass all the data into the shaders.
    struct PerFrameData {
    uint32_t face;
    float roughness;
    uint32_t sampleCount;
    uint32_t width;
    uint32_t envMap;
    uint32_t distribution;
    uint32_t sampler;
    } perFrameData = {
    .face = face,
    .roughness = (float)(mip) / (cube->numLevels - 1),
    .sampleCount = sampleCount,
    .width = cube->baseWidth,
    .envMap = envMapCube.index(),
    .distribution = uint32_t(distribution),
    .sampler = sampler,
    };
    buf.cmdPushConstants(perFrameData);
  6. Then, a full screen triangle is rendered to cover the entire cube face and let the fragment shader do its work. After the command buffer is filled up, we can submit it.
    buf.cmdDraw(3);
    buf.cmdEndRendering();
    }
    }
    ctx->submit(buf);
    // ... save results to a .ktx file
    }

The remaining part of the prefilterCubemap() function retrieves the generated cubemap data from the GPU and saves it into a .ktx file. Let’s look into the GLSL fragment shader code which does all the heavy lifting in Chapter06/03_FilterEnvmap/src/main.frag.

  1. To unwind the shader logic, let’s start with the entry point main(). The code is trivial and invokes two functions. The function uvToXYZ() converts a cubemap face index and vec2 coordinates into vec3 cubemap sampling direction. The function filterColor() does the actual Monte Carlo sampling and we will come back to it in a moment.
    void main() {
    vec2 newUV = uv * 2.0 - vec2(1.0);
    vec3 scan = uvToXYZ(perFrameData.face, newUV);
    vec3 direction = normalize(scan);
    out_FragColor = vec4(filterColor(direction), 1.0);
    }
  2. Here’s the code of uvToXYZ() for your reference.
    vec3 uvToXYZ(uint face, vec2 uv) {
    if (face == 0) return vec3( 1., uv.y, uv.x);
    if (face == 1) return vec3( -1., uv.y, -uv.x);
    if (face == 2) return vec3(+uv.x, 1., uv.y);
    if (face == 3) return vec3(+uv.x, -1., -uv.y);
    if (face == 4) return vec3(+uv.x, uv.y, -1.);
    if (face == 5) return vec3(-uv.x, uv.y, 1.);
    }

The function filterColor() does the integration part for irradiance and Lambertian diffuse convolution. The argument N is the cubemap sampling direction vector. We iterate sampleCount samples and get the importance sampling information that includes the importance sample direction and probability distribution function (PDF) in this direction. The mathematical part is described in detail in this blog post: https://bruop.github.io/ibl. Here we focus on putting a minimalistic working implementation together.

vec3 filterColor(vec3 N) {
vec3 color = vec3(0.f);
float weight = 0.0f;
for(uint i = 0; i < perFrameData.sampleCount; i++) {
vec4 importanceSample = getImportanceSample(i, N, perFrameData.roughness);
vec3 H = vec3(importanceSample.xyz);
float pdf = importanceSample.w;
  1. Mipmap samples are filtered as described in GPU Gems 3 §20.4. Sample Lambertian at a lower resolution to avoid too bright or “fireflies” pixels.
    float lod = computeLod(pdf);
    if (perFrameData.distribution == cLambertian) {
    vec3 lambertian = textureBindlessCubeLod(
    perFrameData.envMap,
    perFrameData.samplerIdx, H, lod).xyz;
    color += lambertian;
    } else if (perFrameData.distribution == cGGX ||
    perFrameData.distribution == cCharlie) {
    vec3 V = N;
    vec3 L = normalize(reflect(-V, H));
    float NdotL = dot(N, L);
    if (NdotL > 0.0) {
    if (perFrameData.roughness == 0.0) lod = 0.0;
    vec3 sampleColor = textureBindlessCubeLod(
    perFrameData.envMap,
    perFrameData.samplerIdx, L, lod).xyz;
    color += sampleColor * NdotL;
    weight += NdotL;
    }
    }
    }
  2. The output color value is renormalized using the sum of all NdotL weights, or the number of samples for Lambertian case:
    color /= (weight != 0.0f) ?
    weight : float(perFrameData.sampleCount);
    return color.rgb;
    }

The importance sampling function getImportanceSample() returns a vec4 value with an importance sample direction in the .xyz components and the PDF scalar value in the .w component. We generate a Hammersley point as we described earlier in the previous recipe Precomputing BRDF look-up tables and then, based on the distribution type (Lambertian, GGX, or Charlie) we generate a sample and rotate it to the normal direction. This function uses a helper structure MicrofacetDistributionSample.

struct MicrofacetDistributionSample {
float pdf;
float cosTheta;
float sinTheta;
float phi;
};
vec4 getImportanceSample(
uint sampleIndex, vec3 N, float roughness)
{
vec2 xi = hammersley2d(sampleIndex, perFrameData.sampleCount);
MicrofacetDistributionSample importanceSample;
  1. Generate points on a hemisphere with a mapping corresponding to the desired distribution. For example, Lambertian distribution uses a cosine importance.
    if (perFrameData.distribution == cLambertian)
    importanceSample = Lambertian(xi, roughness);
    else if (perFrameData.distribution == cGGX)
    importanceSample = GGX(xi, roughness);
    else if (perFrameData.distribution == cCharlie)
    importanceSample = Charlie(xi, roughness);
  2. Transform the hemisphere sample point into the tangent coordinate frame. The helper function generateTBN() generates a tangent-bitangent-normal coordinate frame from the provided normal vector.
    vec3 localSpaceDirection = normalize(vec3(
    importanceSample.sinTheta * cos(importanceSample.phi),
    importanceSample.sinTheta * sin(importanceSample.phi),
    importanceSample.cosTheta));
    mat3 TBN = generateTBN(N);
    vec3 direction = TBN * localSpaceDirection;
    return vec4(direction, importanceSample.pdf);
    }
  3. We skip the details of individual distribution calculation functions Lambertian(), GGX(), and Charlie(). The actual GLSL shader Chapter06/03_FilterEnvmap/src/main.frag contains all the necessary code.

The process of importance sampling can introduce visual artifacts. One way to improve visual quality without compromising performance is by utilizing hardware-accelerated mip-mapping for swift filtering and sampling. This idea was proposed in the paper “Real-time Shading with Filtered Importance Sampling” by Mark Colbert and Jaroslav Křivánek https://cgg.mff.cuni.cz/~jaroslav/papers/2007-sketch-fis/Final_sap_0073.pdf. This link has a more detailed treatment of the subject: https://developer.nvidia.com/gpugems/gpugems3/part-iii-rendering/chapter-20-gpu-based-importance-sampling. Here we use a formula which takes a PDF value and calculates a proper mip-map LOD level for it:

float computeLod(float pdf) {
float w = float(perFrameData.width);
float h = float(perFrameData.height);
float sampleCount = float(perFrameData.sampleCount);
return 0.5 * log2( 6.0 * w * h / (sampleCount * pdf));
}

The rest of the code involves purely mechanical tasks, such as loading the cube map image from a file, calling the rendering functions for various distribution types (Lambertian, GGX, Charlie), and saving the result using the KTX library. Let’s check out the results of prefiltering for the following input image:

Figure 6.6: Environment cube map

The convolved image should look as in the following screenshot:

Figure 6.7: Prefiltered environment cube map using diffuse convolution

Now we have all supplementary parts in place to render a PBR image. In the next recipe Implementing the glTF 2.0 metallic-roughness shading model, we are going to put everything together into a simple application to render a physically based glTF 2.0 3D model.

Paul Bourke created a set of tools and a great resource explaining how to convert cube maps between different formats. Make sure to check it out: http://paulbourke.net/panorama/cubemaps/index.html.

Implementing the glTF 2.0 metallic-roughness shading model

Section titled “Implementing the glTF 2.0 metallic-roughness shading model”

This recipe will cover how to integrate physically based rendering (PBR) into your graphics pipeline. Since the topic of PBR rendering is vast, we focus on the minimalistic implementation just to guide you and get you started. In the book text right here, we focus on the metallic-roughness shading model and minimalistic C++ viewer implementation. In the following chapters we will create a more complex and feature-rich glTF viewer including advanced material extensions and geometry features.

It is recommended to revisit the recipe Introduction to glTF 2.0 Physically Based Material system before you proceed with this one. A lightweight introduction to the glTF 2.0 shading model can be found at https://github.com/KhronosGroup/glTF-Sample-Viewer/tree/glTF-WebGL-PBR.

The C++ source code for this recipe is in the Chapter06/04_MetallicRoughness folder. The GLSL shader code responsible for PBR calculations can be found in Chapter06/04_MetallicRoughness/src/PBR.sp.

Before we dive deep into the GLSL code, we’ll look at how the input data is set up from the C++ side. We are going to use the Damaged Helmet 3D model provided by Khronos. You can find the glTF file here deps/src/glTF-Sample-Models/2.0/DamagedHelmet/glTF/DamagedHelmet.gltf.

Let’s start with structures and helper functions first:

  1. The helper struct GLTFGlobalSamplers contains three samplers necessary to access glTF IBL textures. It is declared in shared/UtilsGLTF.h.
    struct GLTFGlobalSamplers {
    explicit GLTFGlobalSamplers(const std::unique_ptr<lvk::IContext>& ctx);
    Holder<SamplerHandle> clamp;
    Holder<SamplerHandle> wrap;
    Holder<SamplerHandle> mirror;
    };
  2. The GLTFGlobalSamplers constructor creates all 3 samplers the following way:
    GLTFGlobalSamplers(const std::unique_ptr<lvk::IContext>& ctx) {
    clamp = ctx->createSampler({
    .minFilter = lvk::SamplerFilter::SamplerFilter_Linear,
    .magFilter = lvk::SamplerFilter::SamplerFilter_Linear,
    .mipMap = lvk::SamplerMip::SamplerMip_Linear,
    .wrapU = lvk::SamplerWrap::SamplerWrap_Clamp,
    .wrapV = lvk::SamplerWrap::SamplerWrap_Clamp,
    .wrapW = lvk::SamplerWrap::SamplerWrap_Clamp,
    .debugName = "Clamp Sampler" });
    wrap = ctx->createSampler({
    .minFilter = lvk::SamplerFilter::SamplerFilter_Linear,
    .magFilter = lvk::SamplerFilter::SamplerFilter_Linear,
    .mipMap = lvk::SamplerMip::SamplerMip_Linear,
    .wrapU = lvk::SamplerWrap::SamplerWrap_Repeat,
    .wrapV = lvk::SamplerWrap::SamplerWrap_Repeat,
    .wrapW = lvk::SamplerWrap::SamplerWrap_Repeat,
    .debugName = "Wrap Sampler" });
    mirror = ctx->createSampler({
    .minFilter = lvk::SamplerFilter::SamplerFilter_Linear,
    .magFilter = lvk::SamplerFilter::SamplerFilter_Linear,
    .mipMap = lvk::SamplerMip::SamplerMip_Linear,
    .wrapU = lvk::SamplerWrap::SamplerWrap_MirrorRepeat,
    .wrapV = lvk::SamplerWrap::SamplerWrap_MirrorRepeat,
    .debugName = "Mirror Sampler" });
    }
  3. The helper struct EnvironmentMapTextures stores all IBL environment map textures and the BRDF look up table, and provides default textures for the sake of simplicity.
    struct EnvironmentMapTextures {
    Holder<TextureHandle> texBRDF_LUT;
    Holder<TextureHandle> envMapTexture;
    Holder<TextureHandle> envMapTextureCharlie;
    Holder<TextureHandle> envMapTextureIrradiance;
  4. Check the previous recipe Precomputing irradiance maps and diffuse convolution for details of how to precalculate the IBL textures. The BRDF look up table was precalculated in the recipe Precomputing BRDF look-up tables.
    explicit EnvironmentMapTextures(
    const std::unique_ptr<lvk::IContext>& ctx)
    : EnvironmentMapTextures(ctx,
    "data/brdfLUT.ktx",
    "data/piazza_bologni_1k_prefilter.ktx",
    "data/piazza_bologni_1k_irradiance.ktx",
    "data/piazza_bologni_1k_charlie.ktx") {}
    EnvironmentMapTextures(
    const std::unique_ptr<lvk::IContext>& ctx,
    const char* brdfLUT,
    const char* prefilter,
    const char* irradiance,
    const char* prefilterCharlie = nullptr)
    {
    texBRDF_LUT = loadTexture(ctx, brdfLUT, lvk::TextureType_2D);
    envMapTexture = loadTexture(
    ctx, prefilter, lvk::TextureType_Cube);
    envMapTextureIrradiance = loadTexture(
    ctx, irradiance, lvk::TextureType_Cube);
    }
    };
  5. The structure GLTFMaterialTextures contains all the textures necessary to render any glTF2 model we support in our demos. It is a container for many Holder<TextureHandle> objects as follows:
    struct GLTFMaterialTextures {
    // MetallicRoughness / SpecularGlossiness
    Holder<TextureHandle> baseColorTexture;
    Holder<TextureHandle> surfacePropertiesTexture;
    // Common properties
    Holder<TextureHandle> normalTexture;
    Holder<TextureHandle> occlusionTexture;
    Holder<TextureHandle> emissiveTexture;
    // Sheen
    Holder<TextureHandle> sheenColorTexture;
    Holder<TextureHandle> sheenRoughnessTexture;
    // … many other textures skipped here
    }
  6. The helper function loadMaterialTextures() is not shared and will be different in each app. This variant of the function loads a subset of necessary textures for our metallic-roughness demo.
    GLTFMaterialTextures loadMaterialTextures(
    const std::unique_ptr<lvk::IContext>& ctx,
    const char* texAOFile,
    const char* texEmissiveFile,
    const char* texAlbedoFile,
    const char* texMeRFile,
    const char* texNormalFile)
    {
    glTFMaterialTextures mat;
    mat.baseColorTexture = loadTexture(
    ctx, texAlbedoFile, lvk::TextureType_2D, true);
    if (mat.baseColorTexture.empty()) return {};
    mat.occlusionTexture = loadTexture(ctx, texAOFile);
    if (mat.occlusionTexture.empty()) return {};
    mat.normalTexture = loadTexture(ctx, texNormalFile);
    if (mat.normalTexture.empty()) return {};
    mat.emissiveTexture = loadTexture(
    ctx, texEmissiveFile, lvk::TextureType_2D, true);
    if (mat.emissiveTexture.empty()) return {};
    mat.surfacePropertiesTexture = loadTexture(ctx, texMeRFile);
    if (mat.surfacePropertiesTexture.empty()) return {};
    mat.wasLoaded = true;
    return mat;
    }}
  7. One important step is to load the material data and fill out the structure MetallicRoughnessDataGPU. We use the Assimp API to retrieve the material properties and fill the corresponding values out. The glTF specification requires well defined default values for non-optional and optional properties, so we fill them out in this snippet as well. For each texture, we read and set the data for a sampler state and a uv coordinates index:
    struct MetallicRoughnessData {
    vec4 baseColorFactor = vec4(1.0f, 1.0f, 1.0f, 1.0f);
  8. Here we pack metallicFactor, roughnessFactor, normalScale, occlusionStrength glTF properties into one vec4 member field metallicRoughnessNormalOcclusion. We do this packing as a very basic optimization. GPU stores this data in vector registers and reading it will be more efficient if we pack all the parameters into a single vec4 value. Another reason is avoiding any additional alignment requirements especially for vec3 types. Similar packing is done for a vec3 glTF property emissiveFactor and a float alphaCutoff, both of which are packed into a single vec4 value.
    vec4 metallicRoughnessNormalOcclusion = vec4(1.0f, 1.0f, 1.0f, 1.0f);
    vec4 emissiveFactorAlphaCutoff = vec4(0.0f, 0.0f, 0.0f, 0.5f);
  9. The other member fields hold texture and sampler ids for our bindless shaders. They have no default values other than 0.
    uint32_t occlusionTexture = 0;
    uint32_t occlusionTextureSampler = 0;
    uint32_t occlusionTextureUV = 0;
    uint32_t emissiveTexture = 0;
    uint32_t emissiveTextureSampler = 0;
    uint32_t emissiveTextureUV = 0;
    uint32_t baseColorTexture = 0;
    uint32_t baseColorTextureSampler = 0;
    uint32_t baseColorTextureUV = 0;
    uint32_t metallicRoughnessTexture = 0;
    uint32_t metallicRoughnessTextureSampler = 0;
    uint32_t metallicRoughnessTextureUV = 0;
    uint32_t normalTexture = 0;
    uint32_t normalTextureSampler = 0;
    uint32_t normalTextureUV = 0;
  10. The alphaMode property defines how the alpha value is interpreted. The alpha value itself should be taken from the 4 -th component of the base color for the metallic-roughness material model.
    uint32_t alphaMode = 0;
    enum AlphaMode {
    AlphaMode_Opaque = 0,
    AlphaMode_Mask = 1,
    AlphaMode_Blend = 2,
    };
    };
  11. The MetallicRoughnessDataGPU structure is filled out using a helper function setupMetallicRoughnessData(). The structure GLTFMaterialTextures was discussed above.
    MetallicRoughnessDataGPU setupMetallicRoughnessData(
    const GLTFGlobalSamplers& samplers,
    const GLTFMaterialTextures& mat,
    const aiMaterial* mtlDescriptor)
    {
    MetallicRoughnessDataGPU res = {
    .baseColorFactor = vec4(1.0f, 1.0f, 1.0f, 1.0f),
    .metallicRoughnessNormalOcclusion = vec4(1.0f, 1.0f, 1.0f, 1.0f),
    .emissiveFactorAlphaCutoff = vec4(0.0f, 0.0f, 0.0f, 0.5f),
    .occlusionTexture = mat.occlusionTexture.index(),
    .emissiveTexture = mat.emissiveTexture.index(),
    .baseColorTexture = mat.baseColorTexture.index(),
    .metallicRoughnessTexture = mat.surfacePropertiesTexture.index(),
    .normalTexture = mat.normalTexture.index(),
    };
  12. The rest of the function goes through reading various glTF material properties using the Assimp API. We paste just the beginning of its code here. All other material properties are loaded in a similarly repeating pattern.
    aiColor4D aiColor;
    if (mtlDescriptor->Get(AI_MATKEY_COLOR_DIFFUSE, aiColor) == AI_SUCCESS)
    {
    res.baseColorFactor = vec4(
    aiColor.r, aiColor.g, aiColor.b, aiColor.a);
    }
    assignUVandSampler(samplers,
    mtlDescriptor,
    aiTextureType_DIFFUSE,
    res.baseColorTextureUV,
    res.baseColorTextureSampler);
    // … many other glTF material properties are loaded here
  13. The helper function assignUVandSampler() looks as follows.
    bool assignUVandSampler(
    const GLTFGlobalSamplers& samplers,
    const aiMaterial* mtlDescriptor,
    aiTextureType textureType,
    uint32_t& uvIndex,
    uint32_t& textureSampler, int index)
    {
    aiString path;
    aiTextureMapMode mapmode[3] = {
    aiTextureMapMode_Clamp,
    aiTextureMapMode_Clamp,
    aiTextureMapMode_Clamp };
    const bool res = mtlDescriptor->GetTexture(textureType, index,
    &path, 0, &uvIndex, 0, 0, mapmode) == AI_SUCCESS;
    switch (mapmode[0]) {
    case aiTextureMapMode_Clamp:
    textureSampler = samplers.clamp.index();
    break;
    case aiTextureMapMode_Wrap:
    textureSampler = samplers.wrap.index();
    break;
    case aiTextureMapMode_Mirror:
    textureSampler = samplers.mirror.index();
    break;
    }
    return res;
    }

Now let’s examine the main() function:

  1. First, we load the glTF file using Assimp. We support only triangulated topology, hence the flag aiProcess_Triangulate is used to instruct Assimp to triangulate the mesh during the import.
    const aiScene* scene = aiImportFile("deps/src/glTF-Sample-
    Assets/Models/DamagedHelmet/glTF/DamagedHelmet.gltf",
    aiProcess_Triangulate);
    const aiMesh* mesh = scene->mMeshes[0];
    const vec4 white = vec4(1.0f, 1.0f, 1.0f, 1.0f);
  2. We populate the vertex data. The struct Vertex is shared across all glTF demos and is declared in shared/UtilsGLTF.h.
    struct Vertex {
    vec3 position;
    vec3 normal;
    vec4 color;
    vec2 uv0;
    vec2 uv1;
    };
    std::vector<Vertex> vertices;
    for (uint32_t i = 0; i != mesh->mNumVertices; i++) {
    const aiVector3D v = mesh->mVertices[i];
    const aiVector3D n = mesh->mNormals ?
    mesh->mNormals[i] : aiVector3D(0.0f, 1.0f, 0.0f);
    const aiColor4D c = mesh->mColors[0] ?
    mesh->mColors[0][i] : aiColor4D(1.0f, 1.0f, 1.0f, 1.0f);
  3. A glTF model commonly uses two sets of UV texture coordinates. The first set uv0 is used for the primary texture mapping, such as diffuse color, specular reflection, or normal mapping. These coordinates are typically used for surface details and color information. The second set uv1 is commonly used for lightmaps or reflection maps. These maps often need separate texture coordinates to be mapped correctly onto the model, distinct from the primary texture coordinates. The glTF specification says that a viewer app should support at least 2 texture coordinate sets.
    const aiVector3D uv0 = mesh->mTextureCoords[0] ?
    mesh->mTextureCoords[0][i] : aiVector3D(0.0f, 0.0f, 0.0f);
    const aiVector3D uv1 = mesh->mTextureCoords[1] ?
    mesh->mTextureCoords[1][i] : aiVector3D(0.0f, 0.0f, 0.0f);
    vertices.push_back({ .position = vec3(v.x, v.y, v.z),
    .normal = vec3(n.x, n.y, n.z),
    .color = vec4(c.r, c.g, c.b, c.a),
    .uv0 = vec2(uv0.x, 1.0f - uv0.y),
    .uv1 = vec2(uv1.x, 1.0f - uv1.y) });
    }
  4. Let’s set up indices which define our triangles and upload the resulting vertex and index data into corresponding buffers.
    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]);
    }
    Holder<BufferHandle> vertexBuffer = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Vertex,
    .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" });
  5. The next step is to load all the material textures. We use the same combination of textures for most of our glTF demos, so we store them in a structure GLTFMaterialTextures declared in shared/UtilsGLTF.h.
    std::unique_ptr<GLTFMaterialTextures> mat =
    loadMaterialTextures(ctx,
    "deps/src/glTF-Sample-Assets/Models/
    DamagedHelmet/glTF/Default_AO.jpg",
    "deps/src/glTF-Sample-Assets/Models/
    DamagedHelmet/glTF/Default_emissive.jpg",
    "deps/src/glTF-Sample-Assets/Models/
    DamagedHelmet/glTF/Default_albedo.jpg",
    "deps/src/glTF-Sample-Assets/Models/
    DamagedHelmet/glTF/Default_metalRoughness.jpg",
    "deps/src/glTF-Sample-Assets/Models/
    DamagedHelmet/glTF/Default_normal.jpg");
  6. Before we continue with the graphics pipeline creation and rendering, we have to set up IBL samplers, textures, and BRDF look up tables. This data is shared between all our demos, so we introduced a couple of helper structs to do all this work for us. Here are the definitions within the main() function.
    GLTFGlobalSamplers samplers(ctx);
    EnvironmentMapTextures envMapTextures(ctx);
  7. The next step is to create a render pipeline step for our glTF rendering. We must provide a vertex input description. Here’s how to create one for our model.
    const lvk::VertexInput vdesc = {
    .attributes = {
    { .location=0, .format=VertexFormat::Float3, .offset=0 },
    { .location=1, .format=VertexFormat::Float3, .offset=12 },
    { .location=2, .format=VertexFormat::Float4, .offset=24 },
    { .location=3, .format=VertexFormat::Float2, .offset=40 },
    { .location=4, .format=VertexFormat::Float2, .offset=48 }},
    .inputBindings = { { .stride = sizeof(Vertex) } },
    };
  8. A rendering pipeline should be created as follows. We will investigate the GLSL shaders in the How it works… section.
    Holder<ShaderModuleHandle> vert = loadShaderModule(
    ctx, "Chapter06/04_MetallicRoughness/src/main.vert");
    Holder<ShaderModuleHandle> frag = loadShaderModule(
    ctx, "Chapter06/04_MetallicRoughness/src/main.frag");
    Holder<RenderPipelineHandle> pipelineSolid =
    ctx->createRenderPipeline({
    .vertexInput = vdesc,
    .smVert = vert,
    .smFrag = frag,
    .color = { { .format = ctx->getSwapchainFormat() } },
    .depthFormat = app.getDepthFormat(),
    .cullMode = lvk::CullMode_Back,
    });
  9. We can call setupMetallicRoughnessData() to load all the material data from glTF and properly pack on the CPU side.
    const aiMaterial* mtlDescriptor =
    scene->mMaterials[mesh->mMaterialIndex];
    const MetallicRoughnessMaterialsPerFrame matPerFrame = {
    .materials = { setupMetallicRoughnessData(
    samplers, mat, mtlDescriptor) },
    };
  10. We store the material data inside a dedicated Vulkan buffer and access it in GLSL shaders using a buffer device address. This address is passed into shaders through Vulkan push constants.
    Holder<BufferHandle> matBuffer = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Uniform,
    .storage = lvk::StorageType_HostVisible,
    .size = sizeof(matPerFrame),
    .data = &matPerFrame,
    .debugName = "PerFrame materials" });
  11. The same treatment applies to our environment textures. They should be packed for the GPU, too.
    const EnvironmentsPerFrame envPerFrame = {
    .environments = { {
    .envMapTexture = envMapTextures.envMapTexture.index(),
    .envMapTextureSampler = samplers.clamp.index(),
    .envMapTextureIrradiance =
    envMapTextures.envMapTextureIrradiance.index(),
    .envMapTextureIrradianceSampler = samplers.clamp.index(),
    .lutBRDFTexture = envMapTextures.texBRDF_LUT.index(),
    .lutBRDFTextureSampler = samplers.clamp.index() } },
    };
    Holder<BufferHandle> envBuffer = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Uniform,
    .storage = lvk::StorageType_HostVisible,
    .size = sizeof(envPerFrame),
    .data = &envPerFrame,
    .debugName = "PerFrame materials" });
  12. The maximum allowed push constant size is 128 bytes. In order to handle data exceeding this size, we set up a storage buffer.
    struct PerDrawData {
    mat4 model;
    mat4 view;
    mat4 proj;
    vec4 cameraPos;
    uint32_t matId;
    uint32_t envId;
    };
    Holder<BufferHandle> perFrameBuffer = ctx->createBuffer({
    .usage = lvk::BufferUsageBits_Storage,
    .storage = lvk::StorageType_HostVisible,
    .size = sizeof(PerFrameData),
    .debugName = "perFrameBuffer",
    });
  13. Everything else is just mesh rendering similar to how it was done in the previous chapters. Here is how draw commands to render a glTF mesh are generated. Framebuffer and render pass declarations are skipped for the sake of brevity.
    const PerFrameData perFrameData = {
    .model = m2 * m1,
    .view = app.camera_.getViewMatrix(),
    .proj = p,
    .cameraPos = vec4(app.camera_.getPosition(), 1.0f),
    .matId = 0,
    .envId = 0,
    };
    lvk::ICommandBuffer& buf = ctx->acquireCommandBuffer();
    buf.cmdUpdateBuffer(perFrameBuffer, perFrameData);
    buf.cmdBeginRendering(renderPass, framebuffer);
    buf.cmdBindVertexBuffer(0, vertexBuffer, 0);
    buf.cmdBindIndexBuffer(indexBuffer, lvk::IndexFormat_UI32);
    buf.cmdBindRenderPipeline(pipelineSolid);
    buf.cmdBindDepthState({ .compareOp = lvk::CompareOp_Less,
    .isDepthWriteEnabled = true });
    struct PerFrameData {
    uint64_t draw;
    uint64_t materials;
    uint64_t environments;
    } perFrameData = {
    .draw = ctx->gpuAddress(perFrameBuffer),
    .materials = ctx->gpuAddress(matBuffer),
    .environments= ctx->gpuAddress(envBuffer),
    };
    buf.cmdPushConstants(perFrameData);
    buf.cmdDrawIndexed(indices.size());
    // …

Let’s skip the rest of the C++ code, which contains trivial command buffer submission and other scaffolding, and check how GLSL shaders work.

There are two GLSL shaders which are used to render our metallic-roughness PBR model, a vertex shader Chapter06/04_MetallicRoughness/src/main.vert and a fragment shader Chapter06/04_MetallicRoughness/src/main.frag, which include additional files for shared input declarations and our glTF PBR code GLSL library. The vertex shader uses programmable-vertex-pulling to read the vertex data from buffers. The one most important aspect of the vertex shader is that we define our own functions, such as getModel() or getTexCoord(), to hide the implementation details of vertex pulling. It allows us to be flexible when we want to change the structure of our input data. We use a similar approach for fragment shaders.

It is the fragment shader that does the actual work. Let’s take a look:

  1. First, we check our inputs. We use buffer references for materials and environments buffers which correspond to the C++ structures MetallicRoughnessDataGPU and EnvironmentMapDataGPU.
    layout(std430, buffer_reference) buffer Materials;
    layout(std430, buffer_reference) buffer Environments;
    layout(std430, buffer_reference) buffer PerDrawData {
    mat4 model;
    mat4 view;
    mat4 proj;
    vec4 cameraPos;
    uint matId;
    uint envId;
    };
  2. We use four helper functions, getMaterialId(), getMaterial(), getEnvironmentId(), and getEnvironment() as shortcuts to access the buffer references provided in the push constants.
    layout(push_constant) uniform PerFrameData {
    PerDrawData drawable;
    Materials materials;
    Environments environments;
    } perFrame;
    uint getMaterialId() {
    return perFrame.drawable.matId;
    }
    uint getEnvironmentId() {
    return perFrame.drawable.envId;
    }
    MetallicRoughnessDataGPU getMaterial(uint idx) {
    return perFrame.materials.material[idx];
    }
    EnvironmentMapDataGPU getEnvironment(uint idx) {
    return perFrame.environments.environment[idx];
    }
  3. Inside the file Chapter06/04_MetallicRoughness/src/inputs.frag, there’s a bunch of helper functions – such as sampleAO(), samplerEmissive(), sampleAlbedo() and many others – to sample from various glTF PBR texture maps based on the material mat. All of them use bindless textures and samplers.
    vec4 sampleAO(InputAttributes tc, MetallicRoughnessDataGPU mat) {
    return textureBindless2D(
    mat.occlusionTexture,
    mat.occlusionTextureSampler,
    tc.uv[mat.occlusionTextureUV]);
    }
    vec4 sampleEmissive(
    InputAttributes tc, MetallicRoughnessDataGPU mat) {
    return textureBindless2D(
    mat.emissiveTexture,
    mat.emissiveTextureSampler,
    tc.uv[mat.emissiveTextureUV]
    ) * vec4(mat.emissiveFactorAlphaCutoff.xyz, 1.0f);
    }
    vec4 sampleAlbedo(
    InputAttributes tc, MetallicRoughnessDataGPU mat) {
    return textureBindless2D(
    mat.baseColorTexture,
    mat.baseColorTextureSampler,
    tc.uv[mat.baseColorTextureUV]) * mat.baseColorFactor;
    }
  4. Within the fragment shader’s main() function, we use these helper functions to sample the texture maps based on the material id value returned by getMaterialId():
    layout (location=0) in vec4 uv0uv1;
    layout (location=1) in vec3 normal;
    layout (location=2) in vec3 worldPos;
    layout (location=3) in vec4 color;
    layout (location=0) out vec4 out_FragColor;
    void main() {
    InputAttributes tc;
    tc.uv[0] = uv0uv1.xy;
    tc.uv[1] = uv0uv1.zw;
    MetallicRoughnessDataGPU mat = getMaterial(getMaterialId());
    vec4 Kao = sampleAO(tc, mat);
    vec4 Ke = sampleEmissive(tc, mat);
    vec4 Kd = sampleAlbedo(tc, mat) * color;
    vec4 mrSample = sampleMetallicRoughness(tc, mat);
  5. To calculate the proper normal mapping effect based on a provided normal map, we evaluate the normal vector per pixel. We do it in world space. The normal map is in tangent space. Hence, the function perturbNormal() calculates the tangent space per pixel using the derivatives of texture coordinates, which is implemented in data/shaders/UtilsPBR.sp, and transforms the perturbed normal to world space. Make sure you check it out. The last step here is to negate the normal for double-sided materials. We use the gl_FrontFacing intrinsic variable to do the check.
    vec3 n = normalize(normal); // world-space normal
    vec3 normalSample = sampleNormal(tc, getMaterialId()).xyz;
    n = perturbNormal(n, worldPos, normalSample, getNormalUV(tc, mat));
    if (!gl_FrontFacing) n *= -1.0f;
  6. Now, we are ready to fill out the PBRInfo structure, which holds multiple inputs utilized later by the various functions in the PBR shading equation:
    PBRInfo pbrInputs = calculatePBRInputsMetallicRoughness(
    Kd, n, perFrame.drawable.cameraPos.xyz, worldPos, mrSample);
  7. The next step is to calculate the specular and diffuse color contributions from the IBL environment lighting. We can directly add diffuse_color and specular_color because our precalculated BRDF LUT already takes care of energy conservation:
    vec3 specular_color = getIBLRadianceContributionGGX(pbrInputs, 1.0);
    vec3 diffuse_color = getIBLRadianceLambertian(
    pbrInputs.NdotV, n, pbrInputs.perceptualRoughness,
    pbrInputs.diffuseColor, pbrInputs.reflectance0, 1.0);
    vec3 color = specular_color + diffuse_color;
  8. For this demo application, we use only one hardcoded directional light source (0, 0, -5). Let’s calculate its lighting contribution:
    vec3 lightPos = vec3(0, 0, -5);
    color += calculatePBRLightContribution(
    pbrInputs, normalize(lightPos - worldPos), vec3(1.0) );
  9. Now we should multiply the color by the ambient occlusion factor. Use 1.0 in case there is no ambient occlusion texture available:
    color = color * ( Kao.r < 0.01 ? 1.0 : Kao.r );
  10. Finally, we apply the emissive color contribution. Before writing the framebuffer output, we convert the resulting color back into the sRGB color space using a hardcoded gamma value of 2.2:
    color = pow( Ke.rgb + color, vec3(1.0/2.2) );
    out_FragColor = vec4(color, 1.0);
    }

We mentioned a bunch of helper functions that use the PBRInfo structure, such as getIBLRadianceContributionGGX(), getIBLRadianceLambertian(), and calculatePBRLightContribution(). Let’s look inside Chapter06/04_MetallicRoughness/src/PBR.sp to see how they work. Our implementation is based on the reference implementation of glTF 2.0 Sample Viewer from Khronos: https://github.com/KhronosGroup/glTF-Sample-Viewer/tree/glTF-WebGL-PBR.

  1. First of all, here is the PBRInfo structure which holds various input parameters for our metallic-roughness glTF PBR shading model. The first values represent geometric properties of the surface at the current point.
    struct PBRInfo {
    float NdotL; // cos angle between normal and light direction
    float NdotV; // cos angle between normal and view direction
    float NdotH; // cos angle between normal and half vector
    float LdotH; // cos angle between light dir and half vector
    float VdotH; // cos angle between view dir and half vector
    vec3 n; // normal at surface point
    vec3 v; // vector from surface point to camera
  2. The following values represent material properties.
    float perceptualRoughness; // roughness value (input to shader)
    vec3 reflectance0; // full reflectance color
    vec3 reflectance90; // reflectance color at grazing angle
    float alphaRoughness; // remapped linear roughness
    vec3 diffuseColor; // contribution from diffuse lighting
    vec3 specularColor; // contribution from specular lighting
    };
  3. The sRGB to linear color space conversion routine is implemented this way. It is a popular rough approximation done for simplicity:
    vec4 SRGBtoLINEAR(vec4 srgbIn) {
    vec3 linOut = pow( srgbIn.xyz,vec3(2.2) );
    return vec4(linOut, srgbIn.a);
    }
  4. Calculation of the lighting contribution from an Image-Based Light source is split into two parts – diffuse irradiance and specular radiance. First, let’s start with the radiance part. We use the Lambertian diffuse term. Khronos implementation is quite complex, here we skip some of its details. For those looking into the underlying math theory, check https://bruop.github.io/ibl/#single_scattering_results:
    vec3 getIBLRadianceLambertian(float NdotV, vec3 n,
    float roughness, vec3 diffuseColor, vec3 F0,
    float specularWeight)
    {
    vec2 brdfSamplePoint =
    clamp(vec2(NdotV, roughness), vec2(0., 0.), vec2(1., 1.));
    EnvironmentMapDataGPU envMap =
    getEnvironment(getEnvironmentId());
    vec2 f_ab = sampleBRDF_LUT(brdfSamplePoint, envMap).rg;
    vec3 irradiance = sampleEnvMapIrradiance(n.xyz, envMap).rgb;
    vec3 Fr = max(vec3(1.0 - roughness), F0) - F0;
    vec3 k_S = F0 + Fr * pow(1.0 - NdotV, 5.0);
    vec3 FssEss = specularWeight * k_S * f_ab.x + f_ab.y;
    float Ems = (1.0 - (f_ab.x + f_ab.y));
    vec3 F_avg = specularWeight * (F0 + (1.0 - F0) / 21.0);
    vec3 FmsEms = Ems * FssEss * F_avg / (1.0 - F_avg * Ems);
    vec3 k_D = diffuseColor * (1.0 - FssEss + FmsEms);
    return (FmsEms + k_D) * irradiance;
    }
  5. contribution uses the GGX model. Please note that we use roughness as a LOD level for the precomputed mip lookup. This trick allows us to save performance to avoid excessive texture lookups and integration over them.
    vec3 getIBLRadianceContributionGGX(
    PBRInfo pbrInputs, float specularWeight)
    {
    vec3 n = pbrInputs.n;
    vec3 v = pbrInputs.v;
    vec3 reflection = -normalize(reflect(v, n));
    EnvironmentMapDataGPU envMap = getEnvironment(getEnvironmentId());
    float mipCount = float(sampleEnvMapQueryLevels(envMap));
    float lod = pbrInputs.perceptualRoughness * (mipCount - 1);
  6. Retrieve a scale and bias to F0 from the BRDF lookup table:
    vec2 brdfSamplePoint = clamp(
    vec2(pbrInputs.NdotV, pbrInputs.perceptualRoughness),
    vec2(0.0, 0.0),
    vec2(1.0, 1.0));
    vec3 brdf = sampleBRDF_LUT(brdfSamplePoint, envMap).rgb;
  7. Fetch values from the cube map. No conversion to the linear color space is required since HDR cube maps are already linear.
    vec3 specularLight =
    sampleEnvMapLod(reflection.xyz, lod, envMap).rgb;
    vec3 Fr = max(vec3(1.0 - pbrInputs.perceptualRoughness),
    pbrInputs.reflectance0) - pbrInputs.reflectance0;
    vec3 k_S = pbrInputs.reflectance0 + Fr * pow(1.0-pbrInputs.NdotV, 5.0);
    vec3 FssEss = k_S * brdf.x + brdf.y;
    return specularWeight * specularLight * FssEss;
    }

Now let’s go through all the helper functions which are necessary to calculate different parts of the rendering equation:

  1. The diffuseBurley() function implements the diffuse term from the paper Physically-Based Shading at Disney by Brent Burley http://blog.selfshadow.com/publications/s2012-shading-course/burley/s2012_pbs_disney_brdf_notes_v3.pdfhttp://blog.selfshadow.com/publications/s2012-shading-course/burley/s2012_pbs_disney_brdf_notes_v3.pdf.
    vec3 diffuseBurley(PBRInfo pbrInputs) {
    float f90 = 2.0 * pbrInputs.LdotH * pbrInputs.LdotH *
    pbrInputs.alphaRoughness - 0.5;
    return (pbrInputs.diffuseColor / M_PI) *
    (1.0 + f90 * pow((1.0 - pbrInputs.NdotL), 5.0)) *
    (1.0 + f90 * pow((1.0 - pbrInputs.NdotV), 5.0));
    }
  2. The next function models the Fresnel specular reflectance term of the rendering equation, also known as the F term:
    vec3 specularReflection(PBRInfo pbrInputs) {
    return pbrInputs.reflectance0 +
    (pbrInputs.reflectance90 - pbrInputs.reflectance0) *
    pow(clamp(1.0 - pbrInputs.VdotH, 0.0, 1.0), 5.0);
    }
  3. The function geometricOcclusion() calculates the specular geometric attenuation G, where materials with a higher roughness will reflect less light back to the viewer:
    float geometricOcclusion(PBRInfo pbrInputs) {
    float NdotL = pbrInputs.NdotL;
    float NdotV = pbrInputs.NdotV;
    float rSqr = pbrInputs.alphaRoughness * pbrInputs.alphaRoughness;
    float attenuationL = 2.0 * NdotL /
    (NdotL + sqrt(rSqr + (1.0 - rSqr) * (NdotL * NdotL)));
    float attenuationV = 2.0 * NdotV /
    (NdotV + sqrt(rSqr + (1.0 - rSqr) * (NdotV * NdotV)));
    return attenuationL * attenuationV;
    }
  4. The function microfacetDistribution() models the distribution D of microfacet normals across the area being drawn:
    float microfacetDistribution(PBRInfo pbrInputs) {
    float roughnessSq = pbrInputs.alphaRoughness * pbrInputs.alphaRoughness;
    float f = (pbrInputs.NdotH * roughnessSq - pbrInputs.NdotH) *
    pbrInputs.NdotH + 1.0;
    return roughnessSq / (M_PI * f * f);
    }

This implementation is based on Average Irregularity Representation of a Roughened Surface for Ray Reflection by T. S. Trowbridge, and K. P. Reitz.

  1. The utility function perturbNormal() provides a normal in world space based on inputs. It expects a sample from the normal map normalSample sampled at texture coordinates uv, a vertex normal n, and a vertex position v.
    vec3 perturbNormal(vec3 n, vec3 v, vec3 normalSample, vec2 uv) {
    vec3 map = normalize( 2.0 * normalSample - vec3(1.0) );
    mat3 TBN = cotangentFrame(n, v, uv);
    return normalize(TBN * map);
    }
  2. The function cotangentFrame() creates tangent space based on the vertex position p, the per-vertex normal vector N, and uv texture coordinates. This is not the best way to get the tangent basis, as it suffers from uv mapping discontinuities, but it’s acceptable to use it in cases where per-vertex precalculated tangent basis is not provided.
    mat3 cotangentFrame( vec3 N, vec3 p, vec2 uv ) {
    vec3 dp1 = dFdx( p );
    vec3 dp2 = dFdy( p );
    vec2 duv1 = dFdx( uv );
    vec2 duv2 = dFdy( uv );
    vec3 dp2perp = cross( dp2, N );
    vec3 dp1perp = cross( N, dp1 );
    vec3 T = dp2perp * duv1.x + dp1perp * duv2.x;
    vec3 B = dp2perp * duv1.y + dp1perp * duv2.y;
    float invmax = inversesqrt( max( dot(T,T), dot(B,B)));
  3. Calculate handedness of the resulting cotangent frame and adjust the tangent vector if needed.
    float w = dot(cross(N, T), B) < 0.0 ? -1.0 : 1.0;
    T = T * w;
    return mat3( T * invmax, B * invmax, N );
    }

There’s a lot of scaffolding machinery necessary to implement the glTF PBR shading model. Before we can calculate light contribution from a light source, we should fill in the PBRInfo structure fields. Let’s take a look at the code of calculatePBRInputsMetallicRoughness() to understand how this is done.

  1. As it is supposed to be in glTF 2.0, roughness is stored in the green channel, and metallicity is stored in the blue channel. This layout intentionally reserves the red channel for optional occlusion map data. We clamp the minimal roughness value to 0.04. It is a widely used constant for many PBR implementations. It comes from the assumption that even dielectrics have at least 4% of specular reflection:
    PBRInfo calculatePBRInputsMetallicRoughness( vec4 albedo,
    vec3 normal, vec3 cameraPos, vec3 worldPos, vec4 mrSample)
    {
    PBRInfo pbrInputs;
    MetallicRoughnessDataGPU mat = getMaterial(getMaterialId());
    float perceptualRoughness = getRoughnessFactor(mat) * mrSample.g;
    float metallic = getMetallicFactor(mat) * mrSample.b;
    const float c_MinRoughness = 0.04;
    perceptualRoughness =
    clamp(perceptualRoughness, c_MinRoughness, 1.0);
  2. Roughness is authored as perceptual roughness; by convention, we convert to material roughness by squaring the perceptual roughness. Perceptual roughness was introduced by Burley https://disneyanimation.com/publications/physically-based-shading-at-disney to make the roughness distribution more linear. The albedo value may be defined from a base texture or a flat color. Let’s compute specular reflectance the following way:
    float alphaRoughness = perceptualRoughness *
    perceptualRoughness;
    vec4 baseColor = albedo;
    vec3 f0 = vec3(0.04);
    vec3 diffuseColor = mix(baseColor.rgb, vec3(0), metallic);
    vec3 specularColor = mix(f0, baseColor.rgb, metallic);
    float reflectance =
    max(max(specularColor.r, specularColor.g), specularColor.b);
  3. For a typical incident reflectance range between 4% to 100%, we should set the grazing reflectance to 100% for the typical Fresnel effect. For a very low reflectance range on highly diffuse objects, below 4%, incrementally reduce grazing reflectance to 0%:
    float reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0);
    vec3 specularEnvironmentR0 = specularColor.rgb;
    vec3 specularEnvironmentR90 =
    vec3(1.0, 1.0, 1.0) * reflectance90;
    vec3 n = normalize(normal);
    vec3 v = normalize(cameraPos - worldPos);
  4. Finally, we should fill in the PBRInfo structure with these values. It is used to calculate contributions of each individual light in the scene:
    pbrInputs.NdotV = clamp(abs(dot(n, v)), 0.001, 1.0);
    pbrInputs.perceptualRoughness = perceptualRoughness;
    pbrInputs.reflectance0 = specularEnvironmentR0;
    pbrInputs.reflectance90 = specularEnvironmentR90;
    pbrInputs.alphaRoughness = alphaRoughness;
    pbrInputs.diffuseColor = diffuseColor;
    pbrInputs.specularColor = specularColor;
    pbrInputs.n = n;
    pbrInputs.v = v;
    return pbrInputs;
    }

The lighting contribution from a single light source can be calculated in the following way using the precalculated values from PBRInfo:

  1. Here ld is the vector from the surface point to the light source and h is the half vector between ld and v:
    vec3 calculatePBRLightContribution(
    inout PBRInfo pbrInputs, vec3 lightDirection, vec3 lightColor)
    {
    vec3 n = pbrInputs.n;
    vec3 v = pbrInputs.v;
    vec3 ld = normalize(lightDirection);
    vec3 h = normalize(ld + v);
    float NdotV = pbrInputs.NdotV;
    float NdotL = clamp(dot(n, ld), 0.001, 1.0);
    float NdotH = clamp(dot(n, h), 0.0, 1.0);
    float LdotH = clamp(dot(ld, h), 0.0, 1.0);
    float VdotH = clamp(dot(v, h), 0.0, 1.0);
    vec3 color = vec3(0);
  2. Check if the light direction is correct and calculate the shading terms F, G, D for the microfacet specular shading model using the helper functions described earlier in this recipe.
    if (NdotL > 0.0 || NdotV > 0.0) {
    pbrInputs.NdotL = NdotL;
    pbrInputs.NdotH = NdotH;
    pbrInputs.LdotH = LdotH;
    pbrInputs.VdotH = VdotH;
    vec3 F = specularReflection(pbrInputs);
    float G = geometricOcclusion(pbrInputs);
    float D = microfacetDistribution(pbrInputs);
  3. Calculate the analytical lighting contribution. We obtain the final intensity as reflectance (BRDF) scaled by the energy of the light (cosine law).
    vec3 diffuseContrib = (1.0 - F) * diffuseBurley(pbrInputs);
    vec3 specContrib = F * G * D / (4.0 * NdotL * NdotV);
    color = NdotL * lightColor * (diffuseContrib + specContrib);
    }
    return color;
    }

That is all and should be sufficient to implement the glTF metallic-roughness PBR shading model. The resulting demo application should render the following image. Also try using different glTF 2.0 files:

Figure 6.8: Physically based rendering of the Damaged Helmet glTF 2.0 model

The whole area of physically based rendering is vast and given the book volume constraints, it is possible to only scratch its surface. In real life, much more complicated PBR implementations can be created, which are normally based on the requirements of content production pipelines. For an endless source of inspiration to know what can be done, we recommend looking into the Unreal Engine source code, which is available for free on GitHub: https://github.com/EpicGames/UnrealEngine/tree/release/Engine/Shaders/Private.

In the next recipe, we will explore one more important PBR shading model, the glTF 2.0 specular-glossiness model, and implement a demo application for it.

Implementing the glTF 2.0 specular-glossiness shading model

Section titled “Implementing the glTF 2.0 specular-glossiness shading model”

The specular-glossiness extension is a deprecated and archived in the official Khronos repository. However, we will demonstrate how to use it, as it remains available in many existing 3D assets. In the next chapter, we will introduce a new glTF specular extension, KHR_materials_specular, that replaces this older specular-glossiness shading model and show how to convert from the old model to the new extension. Originally, the specular-glossiness model was added to glTF PBR as an extension to support an artist-driven approach. For example, game development often requires greater flexibility in controlling specular effects, and the ability to adjust glossiness is essential in such scenarios.

Over time, more advanced glTF PBR extensions were introduced, making the original specular-glossiness model obsolete. To provide similar functionality within the standard metallic-roughness workflow, a new specular extension was developed. As a result, Khronos recommended discontinuing the specular-glossiness extension and archived it. Despite its deprecation, many existing 3D models were created using this shading model, so we will explore its functionality before transitioning to the newer specular extension.

As you may have noticed from this chapter, PBR does not enforce a specific method for defining material models. The metallic-roughness model uses a simplified and intuitive approach, describing surfaces in terms of non-metal vs. metal and smooth vs. rough. While these parameters are not fully physically accurate, they effectively represent a wide range of real-world materials. However, in some cases, the metallic-roughness model is not sufficient to capture all variations in material appearance. The specular-glossiness model provides additional flexibility to address these limitations.

The specular-glossiness workflow is a method for defining materials based on their specular properties. This approach uses three maps: albedo, specular, and glossiness. The albedo map determines the material’s base color, the specular map defines its reflectivity or specular color, and the glossiness map controls its smoothness or glossiness.

A key difference between the metallic-roughness and specular-glossiness workflows is the specular property, which defines material reflectivity using RGB channels. Each channel—red, green, and blue—represents reflectivity at different angles, allowing for a broader range of material appearances compared to the metallic-roughness model. However, this property has a significant flaw that prevents its use within the glTF PBR model. Because it does not distinguish between dielectrics and metals, most glTF PBR extensions are incompatible with the specular-glossiness model. To address this, the Khronos Group introduced the KHR_materials_specular extension, which adds spectral specular color support to the metallic-roughness model.

The C++ source code for this recipe is in the Chapter06/05_SpecularGlossiness folder. The GLSL shader code responsible for PBR calculations can be found in Chapter06/05_SpecularGlossiness /src/PBR.sp.

This recipe is very similar to the previous one. In fact, much of the model loading and rendering code remains unchanged, except for retrieving values for different material properties. We extend the metallic-roughness data to include specular-glossiness parameters, then apply these parameters in the shader based on the material type.

We are going to use the 3D model SpecGlossVsMetalRough provided by Khronos. It provides a side-by-side comparison of the same model rendered with the metallic-roughness shading and specular-glossiness shading. You can find the glTF file here: deps/src/glTF-Sample-Assets/Models/SpecGlossVsMetalRough/glTF/.

Let’s get started. Here are C++ code changes necessary to accommodate specular-glossiness parameters:

  1. We modify our material data structure SpecularGlossinessDataGPU by adding two new data members, vec4 specularGlossiness and uint32_t materialType. The first one will provide the necessary parameters for the specular-glossiness material and the second one will specify the exact material type. Please notice the padding member at the end of the structure. We need it to keep the binary representation of this structure aligned with GLSL shader inputs. The GLSL st430 layout and alignment rules are not complex but might not be correctly implemented by different hardware vendors, especially on mobile devices. In this case, manual padding is just an easy and good enough way to fix compatibility between all GPUs. For further reading, we can recommend official Khronos Vulkan Guide doc: https://github.com/KhronosGroup/Vulkan-Guide/blob/main/chapters/shader_memory_layout.adoc.
    struct SpecularGlossinessDataGPU {
    vec4 baseColorFactor = vec4(1.0f, 1.0f, 1.0f, 1.0f);
    vec4 metallicRoughnessNormalOcclusion = vec4(1.0f, 1.0f, 1.0f, 1.0f);
    vec4 specularGlossiness = vec4(1.0f, 1.0f, 1.0f, 1.0f);
    // … everything else remains the same
    // as in the structure MetallicRoughnessDataGPU …
    uint32_t materialType = 0;
    uint32_t padding[3] = {};
    enum AlphaMode : uint32_t {
    AlphaMode_Opaque = 0,
    AlphaMode_Mask = 1,
    AlphaMode_Blend = 2,
    };
    };
  2. This is how we identify a glTF material type. We implemented a helper function detectMaterialType() in shared/UtilsGLTF.cpp.
    MaterialType detectMaterialType(const aiMaterial* mtl) {
    aiShadingMode shadingMode = aiShadingMode_NoShading;
    if (mtl->Get(AI_MATKEY_SHADING_MODEL, shadingMode) == AI_SUCCESS) {
    if (shadingMode == aiShadingMode_Unlit)
    return MaterialType_Unlit;
    }
    if (shadingMode == aiShadingMode_PBR_BRDF) {
    ai_real factor = 0;
    if (mtl->Get(AI_MATKEY_GLOSSINESS_FACTOR, factor) == AI_SUCCESS) {
    return MaterialType_SpecularGlossiness;
    } else if (mtl->Get(AI_MATKEY_METALLIC_FACTOR, factor) == AI_SUCCESS) {
    return MaterialType_MetallicRoughness;
    }
    }
    LLOGW("Unknown material type\n");
    return MaterialType_Invalid;
    }
  3. The next difference is how we load extra material properties. Nothing interesting here, just load and assign the values using the Assimp API.
    SpecularGlossinessDataGPU res;
    // …
    if (materialType == MaterialType_SpecularGlossiness) {
    ai_real specularFactor[3];
    if (mtlDescriptor->Get(AI_MATKEY_SPECULAR_FACTOR,
    specularFactor) == AI_SUCCESS) {
    res.specularGlossiness.x = specularFactor[0];
    res.specularGlossiness.y = specularFactor[1];
    res.specularGlossiness.z = specularFactor[2];
    }
    assignUVandSampler(samplers, mtlDescriptor,
    aiTextureType_SPECULAR, res.surfacePropertiesTextureUV,
    res.surfacePropertiesTextureSampler);
    ai_real glossinessFactor;
    if (mtlDescriptor->Get(AI_MATKEY_GLOSSINESS_FACTOR,
    glossinessFactor) == AI_SUCCESS) {
    res.specularGlossiness.w = glossinessFactor;
    }
    }

The rest of the C++ code is mostly identical to the previous recipe Implementing the glTF 2.0 metallic-roughness shading model. The uncovered differences related to adjusting to the different material properties and providing necessary data. Let’s now look at the corresponding GLSL shaders.

The differences are introduced in the code of the fragment shader 05_SpecularGlossinesss/src/main.frag where we calculate and apply PBRInfo parameters:

  1. First, we identify the specular-glossiness material type:
    PBRInfo calculatePBRInputsMetallicRoughness( vec4 albedo,
    vec3 normal, vec3 cameraPos, vec3 worldPos, vec4 mrSample)
    {
    PBRInfo pbrInputs;
    SpecularGlossinessDataGPU mat = getMaterial(getMaterialId());
    bool isSpecularGlossiness =
    getMaterialType(mat) == MaterialType_SpecularGlossiness;
  2. Based on the material type, we calculate perceptualRoughness and f0, as well as the diffuse and specular color contributions. We follow the official Khronos recommendations https://kcoley.github.io/glTF/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness to convert values from specular-glossiness to metallic-roughness.
    float perceptualRoughness = isSpecularGlossiness ?
    getGlossinessFactor(mat):
    getRoughnessFactor(mat);
    float metallic = getMetallicFactor(mat) * mrSample.b;
    metallic = clamp(metallic, 0.0, 1.0);
    vec3 f0 = isSpecularGlossiness ?
    getSpecularFactor(mat) * mrSample.rgb :
    vec3(0.04);
    const float c_MinRoughness = 0.04;
    perceptualRoughness = isSpecularGlossiness ?
    1.0 - mrSample.a * perceptualRoughness :
    clamp(mrSample.g * perceptualRoughness, c_MinRoughness, 1.0);
    float alphaRoughness = perceptualRoughness * perceptualRoughness;
    vec4 baseColor = albedo;
    vec3 diffuseColor = isSpecularGlossiness ?
    baseColor.rgb * (1.0 - max(max(f0.r, f0.g), f0.b)) :
    mix(baseColor.rgb, vec3(0), metallic);
    vec3 specularColor = isSpecularGlossiness ?
    f0 : mix(f0, baseColor.rgb, metallic);
    // …
    }

The remaining fragment shader code remains the same. The result image produced by this example should look as in the following screenshot:

Figure 6.9: Specular-glossiness versus metallic-roughness materials

One bottle has a metallic-roughness material and the other uses a specular-glossiness one. As you can see, the objects appear identical, and by adjusting the specular and glossiness values within a compatible range, you can achieve the exact same result with two different shading models.

Here is an article by Don McCurdy explaining the reasons to switching over from the specular-glossiness shading model to the metallic-roughness one: https://www.donmccurdy.com/2022/11/28/converting-gltf-pbr-materials-from-specgloss-to-metalrough.