Drawing

Image-based lighting

A lamp lights a surface from one point. Outdoors, light comes from every direction: the whole sky, the clouds, the ground, the buildings. Image-based lighting (IBL) takes a photo of all that light, an environment map, and lights the scene with it. Shiny surfaces reflect the photo, rough ones show a blur of it, and every surface gets the soft light of the sky. This page shows how to store the photo, how to filter it once so that a pixel needs only three texture reads, and the math that makes that possible (the split sum). The last part shows how RASM does it.

In short

  • An environment map stores the light that arrives from each direction, as an HDR image: a 2:1 equirectangular panorama, or a cube map of six square faces.
  • Lighting a pixel with it is an integral over the hemisphere. It is far too slow per pixel, so the map is filtered once ahead of time.
  • Diffuse light depends only on the normal: one small irradiance map, read at the normal.
  • Specular light depends on roughness too: a prefiltered map with one roughness per mip, read in the reflected direction, times a 2D BRDF table read at (n·v, roughness). This is the split sum.
  • The filters use importance sampling. A small bright light (the sun) makes sparkles unless each sample reads a blurrier mip: filtered importance sampling.

1The problem: light from everywhere

A point light is one arrow. To light a point outdoors, you would add up the light from every direction above the surface, each weighted by the BRDF (see PBR shading). That is an integral, not a sum of a few lights.

one light + a flat gray "ambient"

Punctual lights only

Only the side toward the lamp is lit. A constant gray fills the rest, the same on every side. Metal has nothing to reflect and looks black.

sun light from the whole sky

An environment map

Light from every direction, each with its own color and strength. The bottom is lit by the ground, the top by the sky, one side by the sun.

The integral has two parts, one per term of the BRDF. The rest of the page computes both ahead of time.

Lout(v) = ∫ Lin(l) · f(l, v) · (n·l) dl

Lin(l)
the light arriving from direction l: what the environment map stores
f(l, v)
the BRDF: a diffuse (Lambert) term plus a specular (GGX) term
n·l
the cosine: light at a grazing angle spreads over more surface
∫ … dl
over every direction of the hemisphere above the surface

2Storing light by direction

An environment map answers one question: how much light comes from direction d? It is an HDR image, since the sun can be a thousand times brighter than the sky. Two shapes are common.

equirectangular (2:1) top rows: the zenith, stretched d u: turn around up, 0 … 360° v: from up (0) to down (1) cube map (6 faces) +Y −X −Z +X +Z −Y the face of the biggest axis of d, then where d crosses it
The panorama is how HDR photos are shared: one image, easy to make with a 360° camera. A cube has no stretched rows, is sampled with plain bilinear filtering and mips, and the GPU blends across its edges. So renderers load the panorama and turn it into a cube once.

u = 0.5 + atan2(d.x, −d.z) / 2π

v = acos(d.y) / π

d
a unit direction, y up; −z is the middle of the image
u
the turn around the vertical axis, 0 to 1 across the image; it wraps around at the edges
v
0 at the top row (straight up), 1 at the bottom row (straight down)

To fill a cube face, each texel takes the direction through its center and reads the panorama there. Move the direction below and see where it lands in both.

Turn the direction around (azimuth) at 0° elevation: it walks through the four side faces, a quarter of the image each. Then raise it above 45°: it moves to the top face, where the panorama's rows get very narrow.

The four side faces share the image's width, so a face a quarter of the panorama's width wide keeps all its detail at the horizon: 512² faces for a 2048 × 1024 panorama. Each face has a full chain of mipmaps; the filters below need them.

3Diffuse and specular: what each needs

The two terms of the BRDF ask different questions of the map. That decides what to precompute.

n

Diffuse

Light from the whole hemisphere, weighted by n·l. Depends on the normal only: a 2D table of directions.

One small cube, read at n

v r

Specular

A lobe around the mirror direction r. Its width depends on roughness, its strength on Fresnel, n·v and f0: too many inputs for one table.

Split into two tables: the split sum

irradiance prefiltered BRDF table at n at r, a mip n·v, rough 3 reads per pixel

Per pixel

After the precompute, a pixel does no integral: three texture reads and a few multiplies.

The filtering is done once per map

4Diffuse: the irradiance map

The Lambert BRDF is a constant, albedo / π. So the diffuse integral is the albedo times the map's light averaged over the hemisphere around n, with the cosine weight. Each texel of the irradiance map stores that average for its direction taken as the normal.

diffuse(n) = albedo · E(n) / π

E(n) / π = mean of Lin(l), l drawn with pdf (n·l) / π

E(n)
the irradiance: all the light arriving at a surface facing n
pdf (n·l) / π
cosine-weighted sampling: more directions near the normal, where n·l is large

Drawn with that density, the cosine cancels and the estimate is the plain mean of the samples. The result is very smooth, so a 32² cube is enough; a texel of it covers about 3°.

Spherical harmonics, the other common answer

Irradiance is so smooth that 9 numbers per color (spherical harmonics of order 2) describe it within about 3%. That suits many small light probes. With a strong sun the 9 numbers ring and can go negative; a small cube does not.

5Specular: one roughness per mip

The specular integral depends on the direction, the roughness, Fresnel and the view angle. The split sum approximation (Karis 2013) splits it into two factors that can each be stored:

specular ≈ prefiltered(r, roughness) · (f0 · A + B)

A, B = table(n·v, roughness)

prefiltered
the map blurred by the GGX lobe of this roughness, assuming n = v = r: a cube per roughness
A, B
the BRDF's own integral, with the light set to 1: a scale and a bias of f0, in a 2D table (section 7)
r
the mirror direction, reflect(−v, n)

A rougher surface has a wider lobe, so its blurred map has less detail and needs fewer texels. That fits a mip chain: mip m holds roughness m / (mips − 1). A shader picks the mip from its roughness, and trilinear filtering blends between two.

Raise the roughness from 0: the lobe of reflected light widens and the mip moves down the chain. Then set 16 samples and a low roughness, and watch which source mip a sample reads.

Assuming n = v loses the stretched shape of the reflection at grazing angles, where real highlights get long. It is the price of a 3D table instead of a 5D one. Mip 0 is roughness 0, a mirror: it is a plain copy of the map.

6Filtering by sampling

Each texel of the prefiltered map is an integral too. It is estimated with N samples drawn with the GGX distribution (importance sampling): the samples crowd where the lobe is strong, so few of them do the work of many. A Hammersley set gives evenly spread, repeatable sample points.

sun: one texel each sample reads mip 0: hit or miss

Plain importance sampling

The sun covers a few texels. A sample hits it or not, so the blurred map gets bright speckles, fireflies, unless thousands of samples are taken.

sun, from a coarse mip each sample reads the mip of its size

Filtered importance sampling

A sample stands for 1/N of the lobe. It reads the mip whose texels are that big, so the sun is already spread out and every sample sees part of it.

mip = ½ · log2(Ωsample / Ωtexel) + 1

Ωsample = 1 / (N · pdf) Ωtexel = 4π / (6 · size²)

pdf
the sample's probability density; for GGX with n = v it is D / 4
Ω
a solid angle: the part of the sphere a sample, or a texel of mip 0, covers
½ · log2
a mip halves the side of a texel, so it quarters its solid angle
+ 1
one mip coarser than needed, to smooth what N samples leave

The irradiance map is filtered the same way, with cosine-distributed samples: pdf = (n·l) / π.

7The BRDF table

The second factor of the split sum is the specular BRDF integrated against a white environment. Fresnel (Schlick) is linear in f0, so the integral splits into a part times f0 and a part added to it. Both depend only on n·v and roughness: one 2D table, the same for every environment.

A = mean of (1 − Fc) · G B = mean of Fc · G

G = V · 4 (n·l)(v·h) / (n·h) Fc = (1 − v·h)5

V
the visibility term (height-correlated Smith GGX), as in direct lighting
G
the BRDF times n·l, divided by the pdf of the sample's half vector h
mean
over half vectors h drawn with the GGX distribution
Drag the handle to the left edge at the top (grazing, smooth): the bias grows and even plastic reflects most of the light. Then go to the bottom (rough): scale plus bias falls below 1.

The table is computed once (per engine, not per environment), 128² is plenty, and it needs two channels.

8The sky behind the scene

Where nothing is drawn, the environment itself should show. One triangle covers the screen at the far plane, and the depth test keeps it only where the depth is still the clear value. Each pixel turns its screen position into a view ray and reads the cube there, at mip 0.

  1. draw the scenedepth written where there is geometry
  2. one triangle at the far planedepth test: only where nothing was drawn
  3. pixel → view ray → worldthe inverse of the camera's rotation
  4. read the cubealong the ray

Drawing the sky last costs only the pixels it shows. Drawing it first and the scene over it costs the whole screen.

9Pitfalls

White sparkles on rough reflections
Fireflies from a small bright light: each sample read mip 0. Read the mip from the sample's pdf (section 6), or take far more samples.
The sun turns into infinity or black
A 16-bit float stores at most 65504. Clamp the photo's brightest texels when converting it, or one bad texel spreads over the whole blurred map.
Ground color in the sky straight up
The sampler repeats in v as well as in u, so bilinear filtering at the top row blends in the bottom row. Repeat only in u (the seam), or keep v half a texel inside the image.
Visible seams on the cube's edges
Faces sampled as six 2D textures. Sample the cube as a cube, so the GPU filters across faces.
Blocky or shimmering sky near the top and bottom
The panorama's rows near the poles are squeezed into few cube texels. Take several reads per cube texel, then build the mips by averaging.
Rough metal looks too bright or too dark compared to direct light
Roughness mapped to mips differently in the filter and in the shader, or the table read with α (roughness²) instead of roughness. Use the same rule in both places.
Objects glow in a dark corner
The environment light is not shadowed: it reaches every point. Ambient occlusion, light probes or reflection probes are what block it.
The sky is mirrored left to right
atan2 arguments swapped, or the panorama read from inside out. Looking along −z, turning right must move right in the image.

10Worked example

A 2048 × 1024 panorama of a sunset, in 16-bit floats:

512²cube face2048 / 4, a power of two
10mips of the cube512 down to 1
16 MiBthe cube with its mips512² × 6 × 8 B × 4/3
256² × 6prefiltered mips, roughness 0 … 1about 4 MiB
32²irradiance cube48 KiB
0.056reflectance of plastic at n·v 0.5, roughness 0.50.04 · 0.835 + 0.023

At n·v = 0.1 and roughness 0.2, the same plastic reflects 0.04 · 0.456 + 0.470 = 0.489: almost half the light, at a grazing angle. At roughness 1 and n·v = 0.5 it reflects 0.021: rough surfaces lose energy in this model.

11In RASM

An application loads an environment and gives it to a scene. The engine bakes it on the GPU in one frame, before that frame's passes, then every scene view that uses it reads three textures per pixel and draws the sky in its last draw pass.

const rasm::EnvironmentHandle sunset = engine.loadEnvironment("environments/venice_sunset_2k.hdr");
engine.setSceneEnvironment(scene, rasm::SceneEnvironment{.environment = sunset, .intensity = 1.0f, .rotation = 1.15f});
main thread GPU, compute textures shading
loadEnvironment worker: stbi_loadf, half finishLoads 4 textures, WAITING beginFrame → recordEnvironmentBakes before any pass, first graphics batch image 2048 × 1024 cube cube, 512² 10 mips (downsample) specular irradiance what shading reads specular, 256², 6 mips irradiance, 32² BRDF LUT, 128² once, first frame drawSky (sky.slang) the cube, where depth is still 0 shadePBR → getEnvironmentLight specular × (f0 · LUT.x + LUT.y) + irradiance × color All textures R16G16B16A16_SFLOAT. The cubes and the LUT are written by compute as storage images, then sampled. The image is destroyed once the frame that baked it is done.
The bake is about 1 ms on an RTX 3060 for this panorama, plus 0.14 ms for the LUT, once (the table below). A scene uses the environment from the frame that bakes it; until then it has the constant ambient.

What the bake costs

GPU time of each step for venice_sunset_2k.hdr (a 512 cube), Release, RTX 3060:

StepGPU time
Cube from the image0.12 ms
Cube mips0.07 ms
Specular mips 0 to 50.02, 0.44, 0.13, 0.07, 0.06, 0.05 ms
Irradiance0.06 ms
Whole bakeabout 1.0 ms, in one frame
BRDF table0.14 ms, once per renderer

So the bake runs in one frame and is not spread over several. A weak integrated GPU takes longer, once, when the environment loads. A long first frame you measure is more likely new video memory being cleared (GPU memory, P35) than the bake.

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Inputan equirectangular panorama or a cubeA Radiance .hdr panorama only (AssetLoader::loadEnvironment), decoded with stbi_loadf, clamped to 65504 and packed to half floats on a worker.
Cube sizea quarter of the widthgetEnvironmentCubeSize: a quarter of the width as a power of two, 64 to 1024 (ENVIRONMENT_MIN_CUBE_SIZE, ENVIRONMENT_MAX_CUBE_SIZE). 4 reads of the image per texel, v kept half a texel inside it (the sampler repeats, for u), then a 2x2 box per mip.
Irradiancea small cube or 9 SH numbersA cube of IRRADIANCE_CUBE_SIZE (32), 512 cosine samples per texel, filtered importance sampling.
Specularone roughness per mipSPECULAR_CUBE_SIZE (256) with SPECULAR_MIPS (6): mip m is roughness m / 5, 256 GGX samples per texel, mip 0 a copy. The shader reads roughness × 5, with perceptual roughness.
BRDF table2 channels, per engineBRDF_LUT_SIZE (128), 512 samples, in an RGBA16F texture (x and y used), baked in the engine's first frame.
Rotation, intensity—SceneEnvironment::rotation turns every lookup around +Y in the shader, and SceneEnvironment::orientation (a quaternion) then places the environment in any frame, such as a globe's local east, up and south (toEnvironment in shaders/lib/environment.slang, large worlds), so turning needs no new bake; intensity scales the light and the sky.
Sky—Renderer::drawSky draws the environment cube (mip 0) where depth is still 0, after the view's last draw pass. In a target with motion (TAA) the ray takes out the jitter, and the sky writes the motion of the camera's turn only, since it is infinitely far. A debug view draws no sky.
OcclusionAO, probesOnly the material's occlusion texture, on diffuse and specular alike. The environment light is not shadowed (D23).
Lifetime—Until destroyEnvironment: its scenes then have none, and its textures and slots go once the GPU is done with them.

Where it lives in code

WhatWhere
APIAssetLoader::loadEnvironment, Renderer::isLoaded, Renderer::setSceneEnvironment, SceneEnvironment in include/rasm/scene.h
LoadingdecodeEnvironment and Renderer::setEnvironmentImage in src/assets/environment.cpp
The bakeRenderer::recordEnvironmentBakes and Renderer::finishEnvironmentBakes in src/renderer/environmentBake.cpp; state in Environments, sizes and storage slots in src/renderer/environmentBake.h
Bake shaderscubeMain, downsampleMain, specularMain, irradianceMain, brdfMain in shaders/passes/environment.slang
ShadinggetEnvironmentLight, getSampleMip, sampleGgx, getEquirectUV, toEnvironment in shaders/lib/environment.slang; called from shadePBR in shaders/lib/pbr.slang
SkyRenderer::drawSky in src/renderer/gpuScene.cpp, shaders/passes/sky.slang
Per viewwriteSceneEnvironment fills the SceneData environment fields in prepareSceneView
Exampleexamples/08_ibl/main.cpp: spheres from rough to smooth and plastic to metal, DamagedHelmet, a sun lined up with the photo's
Keep these true
  • The roughness of mip m in specularMain and the mip the shader reads in getEnvironmentLight use the same rule: roughness × (SPECULAR_MIPS − 1).
  • getEquirectUV and the lab on this page use the same mapping; toEnvironment and the example's sun direction turn the same way.
  • One bake fits its storage slots: the static_assert in environmentBake.h checks it against RESERVED_STORAGE_IMAGES, the slots kept for the bake below the storage targets' ones.
  • The bake's textures end SAMPLED through RenderContext::transitionImageLayout, so later passes and a dropped frame see the right state.

Further reading