Drawing
Uber shaders and shader permutations
Materials differ: one has a normal map, one does not; one is lit, one is unlit. A renderer can compile a separate shader for every combination, or write one big shader, an uber shader, that handles all of them with branches at run time. This page explains both ways, what a branch really costs on a GPU, and why GPU-driven renderers lean towards one shader. The last part shows how RASM does it.
In short
- Every on/off feature doubles the number of shader combinations, the permutations. A few features give hundreds of shaders.
- Compile-time variants (#if) give the fastest code per combination, but cost compile time, memory, pipeline-creation stalls and draw-call splits.
- An uber shader branches at run time on material data. One shader, one pipeline, slightly slower code.
- A branch that is the same for all threads of a wave is cheap. A branch that differs inside a wave (divergence) runs both sides.
- The real cost of an uber shader is often registers: the worst path decides how many waves fit on the GPU.
- Specialization constants sit in between: one compiled shader, with constants fixed when the pipeline is made.
1The permutation explosion
Take a typical material model, like glTF's. A texture can be there or not. The surface can be opaque, cut out, or blended. It can be lit or unlit, single- or double-sided. Each choice changes the shader code, so each combination of choices is, in the simplest design, its own shader.
Try it. Build the material model one feature at a time and watch the count. The single orange cell is the other answer, an uber shader (section 3).
Not every combination is used by a real scene, so engines only compile the ones they meet. But they do not know which ones until the content is loaded, and the set changes with every new asset.
2Way 1: compile-time variants
The classic answer writes the shader once, with preprocessor switches, and compiles it once per combination with different #defines:
float3 n = input.normal;
#if HAS_NORMAL_MAP
n = sampleNormalMap(material.normalTexture, input.uv, n);
#endif
// compiled twice: with HAS_NORMAL_MAP = 1, and with HAS_NORMAL_MAP = 0
Good
- The fastest code for each combination. Unused features cost nothing.
- Each binary uses only the registers its own path needs.
- Simple to reason about: one shader does one thing.
Bad
- Compile time grows with the number of combinations.
- Each binary needs a pipeline. Creating a pipeline the first time it is needed causes a visible stall: the well-known shader stutter.
- More pipelines mean more state changes, and more splits of a GPU-driven draw list.
3Way 2: one uber shader with runtime branches
The other answer compiles one shader that contains every feature, and decides at run time, from the material's data, which parts to run. The material stores flags, or uses a special value such as "no texture" for a missing texture index:
float3 n = input.normal;
if (material.normalTexture != NO_TEXTURE)
n = sampleNormalMap(material.normalTexture, input.uv, n);
// compiled once; the branch is decided per material, at run time
Whether this is fast depends on how GPUs run branches. That is the next section.
4How a GPU runs a branch
A GPU does not run each pixel's shader on its own. It runs them in groups of 32 or 64 threads, called a wave (or warp). All threads of a wave share one instruction stream: at each step, they all run the same instruction, each on its own data. Each thread is a lane of the wave.
So what happens at an if? If all lanes agree, the wave simply runs the side they chose. If they disagree, the wave runs both sides, one after the other, and switches off the lanes that did not choose the side being run. This is called divergence.
Try it with the same wave: side A costs 100 steps, side B 300.
So the question is not "does the shader branch?" but "is the branch the same for all lanes of a wave?". There are three kinds of values a branch can test:
Known when compiling
A #define, a specialization constant.
Cost: none: the compiler removes the side not taken
The same for the whole draw (uniform)
A material flag, when the draw has one material.
Cost: small: every wave takes one side; only the test itself costs
Different per pixel or vertex (varying)
A texture value, the light's distance.
Cost: can be both sides, when neighbouring pixels disagree
A material branch is the good, middle case: all pixels of one draw share one material. Whether one wave can hold pixels of two draws depends on the GPU. When it can, the branch may diverge in that wave, at draw edges only. In Vulkan, the specification treats each draw of a multi-draw as its own group for this purpose, so a value that is the same for the whole draw still counts as uniform.
5The hidden cost: registers
Divergence is easy to see. A bigger cost of uber shaders is easy to miss. A GPU keeps many waves in flight on each compute unit at once. When one wave waits for memory, for example for a texture, the unit switches to another one. More waves in flight hide more waiting. The number of waves that fit is called occupancy.
Waves share the unit's register file. A shader that needs more registers per thread leaves room for fewer waves. And the compiler must give the shader enough registers for its worst path, even if most materials never take it. One rare, heavy feature in an uber shader can lower the occupancy of every material.
A branch that raises the count from 40 to 64 turns 6 waves into 4, for every pixel the shader runs, taken or not.
Do not copy big structs or arrays into local variables at the top of an uber shader "just in case": the compiler may keep them in registers for the whole shader. Read data when a path needs it, through a pointer or an index.
6Way 3: specialization constants
Vulkan offers a middle way. A specialization constant is a constant in the compiled shader (SPIR-V) whose value is given only when a pipeline is created. The driver then compiles the pipeline with that value, and removes the branches it decides. Metal has the same idea as function constants.
// Slang
[SpecializationConstant] const bool hasNormalMap = false;
// GLSL
layout(constant_id = 0) const bool HAS_NORMAL_MAP = false;
| Compile-time variants | Uber shader | Specialization constants | |
|---|---|---|---|
| Source compiles | one per combination | one | one |
| Pipelines | one per combination | one | one per combination |
| Code speed | best | branch tests, worst-case registers | best |
| Draw-list splits | one per combination | none | one per combination |
| Can change per draw for free | no | yes: it is data | no |
| Available on | every API | every API | Vulkan (and Metal's function constants); not in Direct3D 12 |
7The material type switch
Some differences are not small features but whole shading models: lit and unlit, skin, hair, cloth, clear coat. An uber shader handles them with a small integer per material, the material type (or shading model id), and a switch at the top of the pixel shader:
switch (material.type)
{
case UNLIT: return shadeUnlit(material, input);
case CLEAR_COAT: return shadeClearCoat(material, input);
default: return shadeStandard(material, input);
}
The type is uniform per material, so this is the cheap kind of branch. The register cost from section 5 still applies: the heaviest model sets the register count for all.
Deferred renderers use the same idea one step later: they write the shading model id into the G-buffer, and the lighting pass switches on it per pixel.
Switch per draw
All lanes of a wave agree. The switch costs only its test.
Switch per pixel (deferred)
Neighbouring pixels can have different ids, so divergence is real at the edges between materials.
8Why GPU-driven renderers want one pipeline
In a GPU-driven renderer, one indirect call draws many objects, but with one pipeline. Every extra pipeline splits the draw list into another run: another range to cull and pack, another count, another call.
This is why GPU-driven renderers usually combine three ideas:
An uber shader
For the shading.
Bindless textures
Picked by index from the material row.
Vertex pulling
From one mega-buffer.
Together they remove every reason to bind anything between draws.
9Choosing: what goes where
Real engines mix the three ways. A common split:
| Difference | Usually handled by | Why |
|---|---|---|
| Blending, depth writes, the render pass | separate pipelines | It is fixed-function state, and transparent objects need their own sorted pass anyway. |
| Face culling, viewport | dynamic state | Set in the command buffer; it splits runs but not pipelines. |
| Vertex format | vertex pulling | The format becomes shader code reading a buffer. |
| Which textures a material has | runtime branches | Cheap, uniform per draw, and changes nothing else. |
| Shading model | material type switch | Uniform per draw; one pipeline. |
| A rare, very heavy feature | a variant or a specialization constant | Keeps its registers out of every other material. |
| Debug views, quality levels | specialization constants or variants | Set for the whole frame, not per draw. |
10In RASM
RASM draws every scene object with one uber shader, shaders/passes/rasm.slang: one vertMain, one fragMain. Materials are rows in the material table, and fragMain branches on them at run time. Variants, each a #define, exist only for what changes the pipeline or the shader's outputs, never for a material feature: the alpha mode, which changes fixed state (blending, depth writes) and whether the shader may discard, so fragMain is compiled once per mode (transparency); alpha-to-coverage for cut-outs on a multisampled target (MSAA); a second output for motion vectors (TAA); and the debug views (debug views).
Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Variants | #defines, specialization constants | For the alpha mode: fragMain plain, with RASM_ALPHA_MASK and with RASM_ALPHA_BLEND, which Renderer::createScenePipeline puts before the source. Then for the target and the view, not the material: RASM_ALPHA_TO_COVERAGE with RASM_ALPHA_MASK on a multisampled target, RASM_MOTION_VECTORS on a target with a MOTION_FORMAT color (getMotionDefine), and RASM_DEBUG_VIEW for a debug view, made the first time one is chosen. Everything else is a runtime branch. No specialization constants. |
| Texture transforms | a branch, or a variant | A runtime branch on MATERIAL_TEXTURE_TRANSFORM in the row's flags, one for all five textures. A branch per texture made the opaque draws of 05_city about 6% slower, though no material there has a transform: the transform code raised the register count of the whole shader. |
| Texture features | runtime branches | Runtime. Each of the 5 textures is used only when its index is not INVALID_TEXTURE_INDEX (hasTexture). selectUV picks the UV set per texture at run time too. |
| Shading models | a type switch | Six: MaterialId PBR, UNLIT, TERRAIN, VECTOR, POINTS and GLYPHS, stored in MaterialData. POINTS draws in a pipeline of its own (Point clouds), and GLYPHS in rasm.slang compiled with RASM_GLYPHS, whose vertex stage places each glyph (Instanced glyphs). The vertex stage tests TERRAIN (it lifts the vertex by the tile's heights, Terrain from height maps) and VECTOR (it spreads the vertex by the style's width, Vector lines, polygons and points), uniform per draw. fragMain tests VECTOR and UNLIT, each with one if, and shades TERRAIN and GLYPHS as PBR. getGfxMaterialId maps the public MaterialType to it; glTF's KHR_materials_unlit gives UNLIT. The PBR model itself is in PBR shading. |
| Uniformity | uniform per draw | Yes: instanceCount is always 1, so each draw has one material. The texture index is used without a non-uniform marker, which relies on this. |
| Double-sided, mirrored | often a variant | Not variants. The cull mode is dynamic state, so double-sided and mirrored draws only change the run (see face culling). The shader works out the mirroring sign from the world matrix's determinant, per vertex. |
| Pipelines | as few as possible | One graphics pipeline per alpha mode for the scene draws, each made only once a scene has such draws; the alpha mode is part of the run, so it costs a run, not a draw. A view's set of them (ShadedPipelines) depends on its target: one set per sample count, and one for a target with motion vectors, so views of each kind can share a frame. The debug views have sets of their own. The others are the depth-only pipelines of shadow maps, the sky, the tone map, the UI, the stats overlay, the compute pipelines of animation, culling, Hi-Z, the blend sort, the light clusters, the MSAA resolve, TAA and bloom, and any pipeline an application makes with Renderer::createPipeline. |
| Alpha modes | a pipeline per blend mode | Yes: the opaque variant never discards and keeps the early depth test; the mask variant discards (compiled as a demote to a helper, so the texture samples after it keep their derivatives, B33); the blend variant has premultiplied blending and no depth write. |
| Shared shading code | a function | The variants share fragMain itself, not a function that takes the varyings: such a function made Slang read every varying up front, about 5% slower on the opaque draws of 05_city. |
| Registers | read data when needed | The unlit path reads its part of the row through a pointer. The PBR path copies the whole material into PBRInfo first (P9), and reads each light through lightsPtr when it shades it. |
| Compile cost | cache pipelines | Made the first time a scene is drawn (Renderer::prepareSceneView), from shaders the shader workers compiled at startup (Shader warm-up). Each variant is compiled once and then read from the shader cache on later starts; the driver's compile goes through the pipeline cache. A failed compile is retried every frame, so a shader fixed on disk is picked up while the application runs. |
How to add a shading path
- The public type. Add a value to
MaterialTypeininclude/rasm/material.h, beforeCOUNT, and acasefor it in the switch inRenderer::createMaterial(src/assets/material.cpp). - The GPU id. Add the same value to
gfx::MaterialIdinsrc/renderer/uberMaterialTypes.hand toMaterialIdinshaders/lib/core.slang, in the same order. - The mapping. Return it from
getGfxMaterialIdinsrc/renderer/gpuScene.cpp. - The shading. Write a shade function in a new file in
shaders/lib/, include it inrasm.slang, and branch to it infragMainbefore the PBR path, like the unlit path. Read only the fields you need through theMaterialDatapointer. - New material data. If the path needs any: new fields in
Materialon both sides, filled inconvertToGfxMaterial. That is a CPU↔GPU struct change: follow the struct rules. - Check. Run the examples with
enableValidationon. A shader-only change needs no rebuild; the enum changes do.
Where it lives in code
| What | Where |
|---|---|
| The uber shader | vertMain, fragMain, VSOutput in shaders/passes/rasm.slang |
| Shading paths | shadePBR, PBRInfo in shaders/lib/pbr.slang; shadeUnlit in shaders/lib/unlit.slang |
| Shared helpers | hasTexture, selectUV, applyTextureTransform, getTextureUV, sampleBaseColor, getBaseAlpha, MaterialId in shaders/lib/core.slang |
| The material row | gfx::MaterialData, gfx::MaterialId in src/renderer/uberMaterialTypes.h; convertToGfxMaterial, toMaterialData, getGfxMaterialId, Renderer::writeMaterialRow in src/renderer/gpuScene.cpp |
| Making the pipelines | Renderer::createScenePipeline in src/renderer/renderer.cpp; called from Renderer::prepareSceneView, with getMotionDefine; the sets in ShadedPipelines (src/renderer/gpuScene.h) |
| Fixed and dynamic state | VulkanDevice::createGraphicsPipeline in src/rhi/vulkan/vulkanDevice.cpp |
| The public material types | MaterialType in include/rasm/material.h |
- Every scene draw goes through the pipeline of its alpha mode, from its view's set. A material feature is a field and a branch, not a new pipeline: a new pipeline would split every draw list.
- A branch on a material flag that guards several reads goes around all of them at once, so the code it guards does not add registers in every place.
MaterialIdhas the same values in the same order in C++ and Slang.- The material branch must stay uniform per draw. If one draw ever covers several materials (real instancing), the texture indices need a non-uniform marker.
- Shaders output linear color; the swapchain encodes it (see color spaces).
P9: the PBR path copies the material and all lights into registers up front.D12: the shader uses pointers andspirv_asm, so it is Vulkan-only today.
Further reading
- Tomas Akenine-Möller and others, Real-Time Rendering, 4th edition: the chapters on shading basics (shader variants) and on graphics hardware.
- The Vulkan specification, "Specialization Constants".
- AMD's GCN architecture documents: waves, vector registers and occupancy.