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.
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.
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.
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.
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.
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
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
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°.
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.
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.
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.
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²)
- 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
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.
- draw the scenedepth written where there is geometry
- one triangle at the far planedepth test: only where nothing was drawn
- pixel → view ray → worldthe inverse of the camera's rotation
- 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:
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});
What the bake costs
GPU time of each step for venice_sunset_2k.hdr (a 512 cube), Release, RTX 3060:
| Step | GPU time |
|---|---|
| Cube from the image | 0.12 ms |
| Cube mips | 0.07 ms |
| Specular mips 0 to 5 | 0.02, 0.44, 0.13, 0.07, 0.06, 0.05 ms |
| Irradiance | 0.06 ms |
| Whole bake | about 1.0 ms, in one frame |
| BRDF table | 0.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
| Part | This page | RASM |
|---|---|---|
| Input | an equirectangular panorama or a cube | A Radiance .hdr panorama only (AssetLoader::loadEnvironment), decoded with stbi_loadf, clamped to 65504 and packed to half floats on a worker. |
| Cube size | a quarter of the width | getEnvironmentCubeSize: 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. |
| Irradiance | a small cube or 9 SH numbers | A cube of IRRADIANCE_CUBE_SIZE (32), 512 cosine samples per texel, filtered importance sampling. |
| Specular | one roughness per mip | SPECULAR_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 table | 2 channels, per engine | BRDF_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. |
| Occlusion | AO, probes | Only 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
| What | Where |
|---|---|
| API | AssetLoader::loadEnvironment, Renderer::isLoaded, Renderer::setSceneEnvironment, SceneEnvironment in include/rasm/scene.h |
| Loading | decodeEnvironment and Renderer::setEnvironmentImage in src/assets/environment.cpp |
| The bake | Renderer::recordEnvironmentBakes and Renderer::finishEnvironmentBakes in src/renderer/environmentBake.cpp; state in Environments, sizes and storage slots in src/renderer/environmentBake.h |
| Bake shaders | cubeMain, downsampleMain, specularMain, irradianceMain, brdfMain in shaders/passes/environment.slang |
| Shading | getEnvironmentLight, getSampleMip, sampleGgx, getEquirectUV, toEnvironment in shaders/lib/environment.slang; called from shadePBR in shaders/lib/pbr.slang |
| Sky | Renderer::drawSky in src/renderer/gpuScene.cpp, shaders/passes/sky.slang |
| Per view | writeSceneEnvironment fills the SceneData environment fields in prepareSceneView |
| Example | examples/08_ibl/main.cpp: spheres from rough to smooth and plastic to metal, DamagedHelmet, a sun lined up with the photo's |
- The roughness of mip m in
specularMainand the mip the shader reads ingetEnvironmentLightuse the same rule:roughness × (SPECULAR_MIPS − 1). getEquirectUVand the lab on this page use the same mapping;toEnvironmentand the example's sun direction turn the same way.- One bake fits its storage slots: the
static_assertinenvironmentBake.hchecks it againstRESERVED_STORAGE_IMAGES, the slots kept for the bake below the storage targets' ones. - The bake's textures end
SAMPLEDthroughRenderContext::transitionImageLayout, so later passes and a dropped frame see the right state.
Further reading
- Brian Karis, "Real Shading in Unreal Engine 4" (SIGGRAPH 2013 course): the split sum, the prefiltered mips and the BRDF table.
- Mark Colbert, Jaroslav Křivánek, "GPU-Based Importance Sampling" (GPU Gems 3, chapter 20, 2007): filtered importance sampling.
- Romain Guy, Mathias Agopian, "Physically Based Rendering in Filament" (2018): IBL, the DFG table, spherical harmonics.
- Ravi Ramamoorthi, Pat Hanrahan, "An Efficient Representation for Irradiance Environment Maps" (SIGGRAPH 2001): irradiance in 9 numbers.
- Sébastien Lagarde, Charles de Rousiers, "Moving Frostbite to Physically Based Rendering" (SIGGRAPH 2014 course): specular occlusion, light probes.