Drawing

PBR shading

Physically based rendering (PBR) gives each pixel the color that real light would give it. It splits what a surface does to light into a few small formulas, each based on physics: how much light bounces off the top, how much goes in and comes out again, and how a rough surface spreads it. This page explains each formula and why it is there. The last part shows how RASM does it.

In short

  • The color of a pixel is the light that leaves the surface toward the eye. The rendering equation adds up the light that arrives from every direction, weighted by the BRDF and by the angle.
  • The BRDF has two parts. Diffuse: light that goes into the surface and comes out in all directions (Lambert: color / π). Specular: light that bounces off the top.
  • Specular uses microfacets: the surface is many tiny mirrors. Cook–Torrance = D · G · F / (4 (n·l)(n·v)).
  • D (GGX): how many mirrors face the right way. G (Smith): how many are not hidden. F (Schlick Fresnel): how much each mirror reflects, more at grazing angles.
  • The metallic-roughness workflow needs 3 inputs. Non-metals reflect about 4% (F0 = 0.04) and have a colored diffuse. Metals reflect their base color and have no diffuse.
  • A surface never sends out more light than it gets: that is energy conservation.

1The question a shader answers

When a pixel is shaded, the shader knows one point p on a surface. It must answer one question: how much light leaves p toward the eye, and in which color? Four directions describe the situation. All of them are unit vectors that start at p.

surface n l light v eye h p
All vectors point away from the surface. n·l = 1 means the light is straight above; 0 means it grazes the surface.

h = normalize(l + v)

n
normal: the way the surface faces
l
toward the light
v
toward the eye (the view direction)
h
halfway between l and v

Most formulas use only their dot products: n·l, n·v, n·h and l·h. For unit vectors a dot product is the cosine of the angle between them.

Why "physically based"? Compare with the older shading models:

light A: looks right light B: looks wrong

Older models: made-up formulas

Phong and Blinn–Phong use formulas that look good but are made up. They have numbers like a "shininess exponent" that do not exist in the real world. A material that looks right under one light often looks wrong under another.

light A: looks right light B: looks right

PBR: formulas that follow light

The benefit is practical. A material made once looks right in every lighting. Artists set values they can measure, like "this is gold" or "this is 60% rough".

2The rendering equation, in plain words

James Kajiya wrote down the full answer in 1986. It is called the rendering equation:

Lo(p, v) = Le(p, v) + ∫ f(l, v) · Li(p, l) · (n·l) dl

∫ = over the hemisphere above p
PartNameIn plain words
Lo(p, v)outgoing radiancethe light that leaves p toward the eye: the pixel's color
Leemitted radiancelight the surface makes itself (a lamp, a screen, lava)
∫ … dlintegral over the hemisphereadd up the light from every direction l above the surface
Li(p, l)incoming radiancehow much light arrives from direction l
n·lthe cosine termlight that arrives at a slant is spread over more area, so it counts less
f(l, v)the BRDFthe material: what share of the light from l leaves toward v

The cosine term, drawn. The same beam of light, straight and at a slant:

Straight down: n·l = 1 1 the beam lights a strip of width 1 At 60°: n·l = 0.5 2 the same beam, a strip of width 2: half the light per point
The cosine term is pure geometry. It is why a surface gets darker as it turns away from the light, before any material is involved.

Making it small enough for a shader

The integral has no closed form in general. Real-time shaders make it simple with one assumption about where light comes from:

The integral

Light arrives from every direction of the hemisphere. Too much to add up for each pixel.

light 1 light 2

Punctual lights: a sum

Punctual lights are ideal points or directions with no size. Light from such a light arrives from exactly one direction, so the integral turns into a sum, one term per light.

Lo = Le + Σ f(li, v) · Ei · (n·li)      (Σ over the lights i)

Ei = the light's color × intensity × attenuation

The light from everything else (the sky, light bounced off walls) is added as a separate ambient term, see section 11. The rest of this page is about f, the BRDF.

3The BRDF and energy conservation

BRDF means bidirectional reflectance distribution function. It takes two directions, in (l) and out (v), and returns how much of the light from l leaves toward v. When light hits a surface, two things can happen:

light coming in specular: bounces off the top diffuse: goes in and comes out
Non-metal (plastic, wood, stone) light specular: not colored diffuse: scatters inside, comes out anywhere, colored Metal light specular only, colored the rest is absorbed: no diffuse
Every material has specular. Only non-metals have diffuse, because in a metal the free electrons absorb the light that goes in. A metal's specular is colored: gold is yellow.

So the BRDF is a sum of two parts:

f(l, v) = kd · f_diffuse  +  f_specular
Energy conservation

A surface that is not a light source can never send out more light than it receives. The weight kd keeps the sum honest: light that the top layer reflected as specular is not there any more to go in and come out as diffuse.

Old models broke this rule often: a shiny Phong highlight could add light on top of a full diffuse. In PBR the specular part takes its share first, and diffuse gets what is left.

Two common choices for kd:

in out spec diffuse the specular part is not taken out

kd = 1 − metallic

Metals have no diffuse. The specular part is not taken out.

in out F 1 − F diffuse gets what is left

kd = (1 − F) · (1 − metallic)

Also remove the light that Fresnel reflected (section 8). Closer to energy conservation; a little darker at grazing angles.

4Diffuse: Lambert

Light that goes into a non-metal bounces around many times before it comes out. By then it has "forgotten" where it came from, so it leaves equally in all directions. A surface that does this is called Lambertian, and its BRDF is a constant:

f_diffuse = c / π

c = the diffuse color (albedo), from 0 to 1 per channel
light eye A eye B: sees the same brightness the same radiance in every direction
That is why a matte wall looks the same from every side. The diffuse color c must be in linear values, not sRGB values. See Color spaces.

color = c / π · E · (n·l)

n·l
the result depends on the light, through this term
v
not in the formula at all: the result does not depend on the eye
Why divide by π?

Imagine light that arrives with the same strength from every direction of the hemisphere. A white surface (c = 1) should send all of it back out, no more and no less. Adding up the cosine term over the whole hemisphere gives ∫ cos θ dω = π. So the BRDF must be 1/π to send out exactly 1. Without the π, a white surface would send out π ≈ 3.14 times what it received.

Better models exist (Oren–Nayar, Disney/Burley diffuse) that add a little roughness and grazing effects. Most real-time engines keep Lambert.

5Specular: microfacets

A mirror reflects light in exactly one direction. Most real surfaces are not mirrors: their highlight is a soft blob, not a sharp point. Microfacet theory explains why. Under a microscope, the surface is made of many tiny flat mirrors, the microfacets, each facing a slightly different way. Each one is a perfect mirror. Together they spread the light.

A mirror

All facets face the same way. The light leaves in one direction: a sharp point.

A little rough

The facets tilt a little. The light spreads into a small, bright highlight.

Rough

More facets point away from the average normal n. The highlight is wider and dimmer.

Which facets send light from l into v? A mirror turns l into v only if it faces halfway between them:

facet normal = h light, nearly from above to the eye only the orange facets send light from l into v
The other facets reflect the light somewhere else. The facets are far smaller than a pixel, so a shader never sees them. It uses statistics: what share of them face h, and what share are hidden.

The facets that matter are the ones whose normal is the half vector h = normalize(l + v). Robert Cook and Kenneth Torrance (1982) turned this idea into the specular BRDF that almost every engine uses today:

                 D(h) · G(l, v) · F(v, h)
f_specular  =  ───────────────────────────
                   4 · (n·l) · (n·v)

Each letter answers one question:

these face h

D: distribution

What share of the facets face h?

GGX (Trowbridge–Reitz), section 6

hidden: does not count

G: geometry

What share of those are not hidden by other facets?

Smith with GGX, section 7

F 1 − F

F: Fresnel

How much does one facet reflect at this angle?

Schlick's Fresnel, section 8

The divisor 4 (n·l)(n·v) is a correction from the change between facet space and surface space.

The visibility term

Many engines merge G and the denominator into one visibility term V = G / (4 (n·l)(n·v)). Then the specular BRDF is just D · V · F, and the division by small numbers at grazing angles disappears into a formula that is safe to compute.

6D: the normal distribution (GGX)

The normal distribution function D says how the facet normals are spread around the surface normal n. The standard choice is GGX, also called Trowbridge–Reitz (Walter and others, 2007; Trowbridge and Reitz, 1975):

                     α²
D(h)  =  ─────────────────────────────
          π · ((n·h)² · (α² − 1) + 1)²

α is the roughness of the facets. A small α means almost all facets face n: D is a tall, thin spike, and the highlight is small and bright. A large α spreads them: D is low and wide, and the highlight is big and dim. At n·h = 1, the formula gives its peak, 1 / (π α²).

Width: each curve scaled to peak 1 angle between n and h 0° 20° 40° 60° peak 0 r = 0.4 r = 0.6 r = 0.8 Height: the real peak, 1 / (π α²), α = r² 12.4 2.46 0.78 r = 0.4 r = 0.6 r = 0.8 α = 0.16 α = 0.36 α = 0.64
A smooth surface puts its light into a tiny, very bright spot. A rough one spreads the same light out wide. Over the hemisphere, D(h) · (n·h) always adds up to 1, so a taller peak must be thinner: that is energy conservation built into D. GGX also has a long tail: a soft glow around the highlight, as real materials have.

Roughness: what artists set, and what the formula uses

Artists set a perceptual roughness r from 0 (mirror) to 1 (fully rough). If α = r directly, most of the visible change happens near 0, and the slider feels uneven. Squaring it fixes that: α = r² (Burley, 2012). The glTF format defines its roughness this way too.

Perceptual r0.00.20.40.60.81.0
α = r²00.040.160.360.641
Peak of D∞19912.42.460.780.32
Never use a roughness of 0

At r = 0 the peak is infinite. A real shader must avoid that: it clamps r to a small minimum, for example 0.045, so that the numbers stay inside a 32-bit float and the highlight of a tiny point light does not flicker from pixel to pixel.

7G: masking and shadowing (Smith)

Some facets face h but still do not count, because neighbouring facets block them. There are two ways to be blocked:

Shadowing: the light cannot reach it a low light hits the first slope; the facet behind it stays in shadow Masking: the eye cannot see it eye, low the facet is lit, but the next slope is between it and the eye
Both effects grow at grazing angles and on rough surfaces. They are why a rough surface does not get brighter and brighter at its edges.

The geometry term G is the share of facets that are neither shadowed nor masked: 1 means none are blocked. The usual model is Smith's. It looks at one direction at a time with a function G1, and combines the two directions. Two variants are common.

Separable Smith, with Schlick's form of G1

G = G1(n·l) · G1(n·v)

G1(x) = x / (x (1 − k) + k), k = α / 2

use
Cheap and common.
k
Brian Karis (2013) uses k = (r + 1)² / 8 for punctual lights, so rough surfaces do not get too bright.

Height-correlated Smith-GGX (Heitz, 2014)

V = 0.5 / (n·l · √((n·v)² (1 − α²) + α²)

          + n·v · √((n·l)² (1 − α²) + α²))

use
More exact: a facet high on the surface is less likely to be blocked in both directions.
V
Already divided by 4 (n·l)(n·v), so it gives V directly.

8F: Fresnel

Look at a lake. The share of light that it reflects depends on the angle you look at it:

about 2% reflected to the bottom

Straight down

You see the bottom: water reflects only about 2% of the light.

the sky, reflected a mirror

At a low angle

Look across it, and it is a mirror.

Every material does this. The share of light that a surface reflects grows toward 100% as the angle becomes grazing. This is the Fresnel effect, after Augustin-Jean Fresnel.

The exact Fresnel equations need the material's index of refraction and work with polarized light. Christophe Schlick (1994) found a cheap approximation that is close enough:

F(θ) = F0 + (1 − F0) · (1 − cos θ)⁵

cos θ = v·h  (the same as l·h)

F0 is the reflectance when you look straight at the facet (θ = 0). It is the one number that describes the material's specular color. The angle is measured to the facet normal h, not to n: that is the facet that does the reflecting.

0° 30° 60° 90° 1 0 F0 = 0.04 (plastic) F0 = 0.9 (a bright metal) angle θ between v and h Schlick, F0 = 0.04: the share reflected 0° 0.040 45° 0.042 60° 0.070 75° 0.255 85° 0.649 90° 1.000
The curve is flat for most angles and rises fast near 90°. That is why the edges of objects, which face away from the eye, catch a bright rim of reflected light.
θ0°45°60°75°85°90°
cos θ1.0000.7070.5000.2590.0870.000
F, with F0 = 0.040.0400.0420.0700.2550.6491.000

At 60°: 0.04 + 0.96 · 0.5⁵ = 0.04 + 0.96 · 0.03125 = 0.070.

Try it. The picture below runs Schlick's formula for one facet. Move the eye, and check the numbers against the table.

light coming in to the eye reflected: F goes into the surface: 1 − F
Drag the orange point down toward the surface: nothing changes for a long time, then the reflection grows fast. Then raise F0 to 0.9, a bright metal: the curve starts high and has little room to rise.

F is a color, not a single number: F0 has three channels.

0.04 0.04 0.04 R G B

Non-metal

The three channels are equal: the highlight is white.

1.00 0.71 0.29 R G B gold

Metal

The channels differ, and the highlight takes the metal's color.

At 90° every material reflects everything, so the color fades to white at the edges.

9The metallic-roughness workflow

A material needs a diffuse color, an F0 and a roughness. Real materials fall into two groups that use these very differently:

MaterialKindF0 (linear)Diffuse
Waternon-metalabout 0.02yes
Plastic, glass, wood, stone, skinnon-metalabout 0.03 to 0.05yes, the material's color
Diamondnon-metalabout 0.17yes
Ironmetal(0.56, 0.57, 0.58)none
Coppermetal(0.95, 0.64, 0.54)none
Goldmetal(1.00, 0.71, 0.29)none
Silvermetal(0.95, 0.93, 0.88)none

Non-metals almost all sit near 0.04, and metals have no diffuse at all. So one color and one switch are enough. The metallic-roughness workflow (used by glTF, Unreal and many others) stores three values per pixel:

stored per pixel computed in the shader
base color RGB, in linear values metallic 0 = non-metal, 1 = metal roughness r 0 = mirror, 1 = matte diffuse = base · (1 − metallic) a metal has none; a non-metal uses all of it F0 = mix(0.04, base, metallic) non-metal: 4% white · metal: the base color α = r · r into D and G
The same base color means "the diffuse color" for a non-metal and "the specular color" for a metal. Metallic is meant to be 0 or 1. Values in between are for the borders of a texture (rust on steel, dust on gold), where a pixel is part one, part the other.

Try it. The sphere below is shaded pixel by pixel with these three values and the formulas of sections 4 to 8. Its base color is the gold of the table above, (1.00, 0.71, 0.29).

Set metallic to 1: the diffuse light goes away and the highlight takes the base color. Then lower the roughness: the highlight gets smaller and brighter. Move the light past 90° to see the Fresnel rim. One light with E = 3 comes from the upper left; the result goes through c / (c + 1) to fit the screen (section 11).

Upside

Few inputs, hard to get wrong. A non-metal cannot get an F0 that does not exist in nature. Textures pack well: glTF puts roughness in the green channel and metallic in the blue channel of one texture.

Downside

All non-metals share F0 = 0.04. Water, gems or car paint need a different value. The specular-glossiness workflow stores F0 as its own color instead; glTF extensions such as KHR_materials_specular and KHR_materials_ior add it back.

10Lights

A punctual light gives two things to the sum in section 2: the direction l, and the light E that arrives at the surface.

l the same l everywhere

Directional

l: the same everywhere: minus the light's direction.

E: color × intensity, no falloff.

Models the sun: so far away that its rays are parallel

l p

Point

l: normalize(light position − p).

E: color × intensity × attenuation(distance).

Models a bulb: light goes out in every direction

outside

Spot

l: as point.

E: as point, × a cone factor.

Models a flashlight: a point light limited to a cone

Attenuation: the inverse-square law

A point light sends its light out over a sphere. At distance d the sphere has area 4πd², so the light per area falls as 1 / d².

0 d 2d area 1 1 area 4 1/4 each
Twice as far means a quarter of the light. That is physics, and PBR uses it as it is.

The problem: 1 / d² never reaches 0. Every light then touches every pixel in the scene, and a renderer that sorts lights into tiles or clusters cannot skip any of them. Engines add a range: a distance where the light ends. To end it smoothly, they multiply by a window that is 1 near the light and falls to 0 at the range (Karis, 2013):

attenuation(d) = 1 / d²  ·  clamp(1 − (d / range)⁴, 0, 1)²
2 4 6 8 10 0.25 0 distance d 1 / d² (dashed) windowed, range 10 0 5 10 1 0 the window alone almost 1 for the first half
The window hardly changes the light near the source (it is still 0.88 at half the range), and it brings the light to exactly 0 at the range. Without the square on the window, its slope at the range would not be 0, and a faint edge could show.
Distance d (range 10)1258910
1 / d²1.0000.2500.0400.01560.01230.0100
window1.0000.9970.8790.3490.1180
attenuation1.0000.2490.0350.00540.00150

The spot cone

A spot light is a point light times a cone factor. The factor depends on the angle θ between the spot's axis and the line to the pixel. Inside the inner angle it is 1, outside the outer angle it is 0, and between them it fades smoothly. glTF (KHR_lights_punctual) writes it with cosines, so the shader needs no angle at all, only a dot product:

scale  = 1 / max(cos(inner) − cos(outer), 0.001)
offset = −cos(outer) · scale
cone   = clamp(cos θ · scale + offset, 0, 1)²
cone = 1 inner 14°: full light 14° to 22°: fades outer 22°: no light inner outer θ 1 0
The square at the end makes the fade start and end softly. Inner 14°, outer 22°, as the spot lamp of examples/07_lights.
Light units

Physical light units are a separate choice. A physical engine gives a point light in lumens or candela and the sun in lux, and divides by 4π where needed. Many engines just use a unitless "intensity" that the artist tunes by eye.

11Ambient light, image-based lighting, emission

Punctual lights are only part of the light in a scene. The sky and every wall that bounces light also light the surface, from all directions at once. Several ways to add that light exist, from cheap to expensive:

the same everywhere

Constant ambient

A small fixed light × diffuse color. Keeps shadows from being pure black.

Cost: nothing

sky ground n

Hemisphere ambient

A sky color from above, a ground color from below, mixed by the normal.

Cost: almost nothing

environment image

Image-based lighting (IBL)

Light from an environment image. Diffuse: a blurred "irradiance" map or spherical harmonics. Specular: a map pre-blurred per roughness, plus a small lookup texture for the BRDF (the split-sum method, Karis 2013). See Image-based lighting.

Cost: a few texture reads

bounced wall

Global illumination

Real bounced light: light maps, probes, or ray tracing.

Cost: large

sees a lot of sky sees little: darker ambient

Ambient occlusion (AO)

A texture or pass that says how much of the sky each point can see. Cracks and corners see less. AO darkens the ambient light only. Direct light from a punctual light is not affected: that is the job of shadows.

Le not lit by it

Emission

The Le term. The emitted color is added to the result as it is, with no BRDF and no lights. A screen or a lamp shade glows even in a dark room. Emission does not light other objects unless something else (a light, GI, bloom) makes it.

The result is HDR

The sum can be far above 1: a highlight can be 50 times brighter than a wall. A screen shows 0 to 1.

  1. The lighting sumlinear, can be far above 1
  2. Tone mappinga curve that squeezes bright values into the range a screen can show
  3. Encodethe linear value is encoded for the display

The simplest tone map is Reinhard: c / (c + 1), which maps 1 to 0.5 and 3 to 0.75. Others (ACES, AgX) keep colors and contrast better; see Tone mapping. For the encode, see Color spaces.

12Worked example

One pixel, by hand. A grey plastic surface: base color 0.8, metallic 0, roughness r = 0.5. One directional light with E = 1. The light and the eye are both 30° from the normal, on opposite sides. So h = n: the eye sees the center of the highlight.

n = h l v 30° 30°

The inputs that the formulas need:

0.866n·l = n·vcos 30°
1n·hh = n
0.866l·hcos 30°
0.25α, and α² = 0.06250.5²
0.04F0mix(0.04, 0.8, 0)
0.8diffuse color0.8 · (1 − 0)
StepComputationResult
Dα² / (π · (1 · (α² − 1) + 1)²) = 1 / (π α²) = 1 / (π · 0.0625)5.093
F0.04 + 0.96 · (1 − 0.866)⁵ = 0.04 + 0.96 · 0.0000430.0400
V√(0.75 · 0.9375 + 0.0625) = 0.875 for both; 0.5 / (0.866 · 0.875 · 2)0.330
specularD · V · F = 5.093 · 0.330 · 0.04000.0673
diffuse(1 − F) · 0.8 / π = 0.96 · 0.25460.2445
BRDF0.0673 + 0.24450.3117
pixel (linear)BRDF · E · n·l = 0.3117 · 1 · 0.8660.270

Now change one thing at a time and compare the pixel:

0.270the setup above: grey plastic, light at 30°specular 0.067
0.185the light moved to 50°specular 0.043, n·l 0.643
1.31the first setup, but goldspecular 1.51, diffuse 0

Light at 50°, while the eye stays at 30° on the other side. Then h is 10° away from n: D falls from 5.09 to 2.41 and the specular from 0.067 to 0.043. The diffuse hardly changes, but n·l drops to 0.643, and the pixel becomes 0.185.

Gold (F0 = 0.9, metallic 1) in the first setup: the diffuse is 0, the specular is 5.093 · 0.330 · 0.900 = 1.51, and the pixel is 1.31. That is above 1, which is normal for a highlight on metal; tone mapping takes care of it.

13Pitfalls

Washed-out or too dark colors, wrong highlights
Textures not in linear values. Decode color textures from sRGB; read data textures (roughness, normals) as plain numbers.
Highlights that wobble across triangles
Interpolated vectors not normalized. Normalize n, v and l in the fragment shader.
No highlight, or one that sparkles and flickers
Roughness 0. Clamp r to a small minimum.
Black or white pixels at edges (NaN or ∞)
n·v or n·l of 0 in a divisor. Clamp to a small positive number, or use the V form.
The lit side is the dark one
Light direction sign. Decide once: does the stored direction point from the light, or toward it? l must point toward the light.
Diffuse 3 times too bright, lights must be dimmed to match
Forgetting the π in Lambert. Use c / π, or scale the light intensities by π once, on purpose.

14In RASM

RASM shades every non-unlit material with one function, shadePBR in shaders/lib/pbr.slang. The uber shader's fragMain (in shaders/passes/rasm.slang) fills a PBRInfo with the fragment's position, normal, tangent, UVs, the scene's lights and the material row, and calls it. The BRDF is the textbook one from sections 4 to 8, in the form Filament uses.

GPU tables from the vertex shader steps of shadePBR
MaterialData row factors + bindless texture indices (materialsPtr) SceneData lightsPtr, clustersPtr, the light counts, camera position vertMain outputs world position, normal, tangent, 3 UV sets, handedness shadePBR 1 textures × factors; roughness clamped to [0.045, 1] 2 normal: getNormalFromMap if there is a normal map; flip on back faces 3 f0 = lerp(0.04, base, metallic), diffuse = (1 − metallic) · base, α = r² 4 shadowed, global, cluster lights: D_GGX · V_SmithGGX · F_Schlick + (1 − F) · diffuse · Fd_Lambert, × color · intensity · att · N·L 5 + environment light (IBL), or 0.03 · diffuse without one; × ao; + emissive 6 return the sum, unbounded; alpha = base color alpha
The result goes to a 16-bit float target. After the MSAA resolve or the TAA pass, when the frame has one, a later pass multiplies it by the camera's exposure and tone maps it with AgX (Tone mapping), into the sRGB swapchain, which does the sRGB encoding. The shader works in linear values only.

Where RASM follows the textbook, and where it differs

PartThis pageRASM
DiffuseLambert, weighted by kdLambert (Fd_Lambert), weighted by (1 − F) and (1 − metallic): the second row of the table in section 3.
DGGXGGX (D_GGX), written as Filament does, with α = r².
GSmithHeight-correlated Smith-GGX as a visibility term (V_SmithGGXCorrelated). Its divisor is kept above 10⁻⁸.
FSchlickSchlick (F_Schlick) with l·h, fading to 1 at 90°.
Roughnessclamp to a minimumClamped to [0.045, 1] before squaring. Metallic is clamped to [0, 1].
F0 of non-metals0.04, or a value per materialAlways 0.04. No KHR_materials_specular or KHR_materials_ior.
Multiple scatteringnot covered hereNone, so very rough metals are a little too dark (single-scattering microfacet models lose energy).
Light typesdirectional, point, spotLightType has DIRECTIONAL, POINT and SPOT.
Spot conethe glTF cone factorThe same. writeLightRow turns innerConeAngle and outerConeAngle into spotScale and spotOffset (setSpotCone), so shadeLight needs one dot product per light.
Shadowsnot covered hereA view's shadowed lights (up to 4) are shaded first, each times its shadow, which is read only where the light reaches the surface (Shadow mapping, Spot and point light shadows).
Directional lminus the light's directionThe same: direction points from the light toward the surface, l = −direction. No falloff.
Point attenuation1 / d² × windowThe same formula. d² is clamped to at least 10⁻⁶. A range of 0 means no window: the light is global, shaded at every pixel. The default range is 10.
Light unitsphysical or unitlessUnitless: color × intensity, no 4π.
Number of lightsanyUp to EngineConfig::maxLights (16384). A pixel evaluates the global lights and the lights of its cluster only, at most MAX_CLUSTER_LIGHTS (Clustered lighting).
Ambientconstant, hemisphere, IBL or GIIBL when the scene has an environment (setSceneEnvironment): the split sum, diffuse and specular, in getEnvironmentLight (Image-based lighting). Without one, a constant: 0.03 × diffuse color × AO, with no specular, so a fully metallic surface is black on every side that no light faces. Neither is shadowed.
AOambient onlyAmbient only, mixed by the occlusion strength; with IBL it darkens its diffuse and specular alike.
Emissionadded as it isemissiveFactor × EMISSIVE_STRENGTH (glTF KHR_materials_emissive_strength, multiplied in when the row is written) × the emissive texture, added after the lights.
Tone mappinga separate step on the HDR imageThe same: shadePBR writes unbounded light into a SCENE_COLOR_FORMAT target, and the Tone Map pass applies the camera's exposure and AgX.
Texture readsone plain sample eachEvery material texture goes through sampleMaterial, which adds SceneData::textureLodBias to the mip level: −1 in a view that TAA jitters, so the textures stay sharp after the frames are blended (TAA), 0 otherwise. A pipeline with RASM_DEBUG_VIEW skips shadePBR and shows a value of the fragment instead (Debug views).
Shadowsneeded for real direct lightUp to MAX_VIEW_SHADOWS lights per view have a shadow, each named by ShadowDesc::light (Shadow mapping, Cascaded shadow maps). Every other light reaches every surface that faces it.

When a texture is missing

Each texture is used only when its bindless index is not INVALID_TEXTURE_INDEX (hasTexture). Otherwise the glTF defaults apply:

MissingThe shader uses
base colorbaseColorFactor (with its alpha) × the vertex color alone (sampleBaseColor). The vertex color is white for a mesh without one.
metallic-roughnessmetallicFactor and roughnessFactor. With a texture: G channel × roughness factor, B channel × metallic factor.
normalthe interpolated vertex normal (see Normal mapping)
occlusion1: no occlusion. With a texture: R channel, mixed with 1 by strength.
emissiveemissiveFactor alone, which is 0 for a material made with createMaterial

A hand-made material from createMaterial starts as a white, non-metallic, fully rough surface (base color 1, metallic 0, roughness 1). A glTF material with KHR_materials_unlit gets UNLIT, and fragMain sends it to shadeUnlit instead: base color only, no lights. The tone-map pass maps it like every other pixel.

Where it lives in code

WhatWhere
The BRDF termsD_GGX, F_Schlick, V_SmithGGXCorrelated, Fd_Lambert in shaders/lib/brdf.slang, which the environment bake shares
Textures, the light loops, ambientshadePBR, shadeLight and PBRInfo in shaders/lib/pbr.slang; sampleMaterial, sampleBaseColor in shaders/lib/core.slang; the environment light in shaders/lib/environment.slang
Material branch, UV sets, back facesfragMain in shaders/passes/rasm.slang
GPU light and material structsLight, LightType, Material, MaterialData in shaders/lib/core.slang and src/renderer/uberMaterialTypes.h
Public light typeLight, LightType, MAX_CLUSTER_LIGHTS in include/rasm/light.h; Renderer::createLight and updateLight in src/scene/light.cpp
Lights into the light table and the scene datawriteLightRow and writeSceneLights in src/renderer/lightClusters.cpp
Material factors and defaultsRenderer::createMaterial and loadMaterial in src/assets/material.cpp
Keep these true
  • Light, Material and SceneData are CPU↔GPU structs: a change to them follows the struct layout rules, on both sides.
  • Color and emissive textures are R8G8B8A8_SRGB; metallic-roughness, normal and occlusion textures are R8G8B8A8_UNORM. The shader expects linear values from all of them.
  • shadePBR outputs linear color with no upper limit. Do not tone map or apply the sRGB curve in the shader: the tone-map pass and the swapchain do.
  • A light's direction points from the light toward the surface; for a spot light it is the cone's axis.
Not done yet

Base color alpha counts only for cut-out and see-through materials (transparency).

Further reading