Algorithm Search⌘K

Algorithmadvanced

Spherical harmonic irradiance environment map

Also called Ramamoorthi-Hanrahan irradiance map.

Nine spherical harmonic coefficients give the diffuse irradiance of a distant environment as E(n) = n^T M n. The error is at most 3/32 (about 9%) of the total light, and under 3% on average.

Time
Θ(s) buildΘ(1) evaluate
Space
Θ(1) extra
Where
s = the number of texels of the environment map
Properties
deterministicnot in placeonlineiterative
Origin
Ravi Ramamoorthi, Pat Hanrahan, 2001

A spherical harmonic irradiance environment map gives the light that a diffuse surface receives from a distant environment, for any normal, with nine numbers per color channel. The input is an environment map of radiance. The algorithm projects it onto the nine real spherical harmonics of order l≤2l \le 2, multiplies them by the coefficients of the clamped cosine, and puts the result into a symmetric 4×44 \times 4 matrix MM. The irradiance at a unit normal nn is then E(n)=n~TMn~E(n) = \tilde n^T M \tilde n with n~=(nx,ny,nz,1)\tilde n = (n_x, n_y, n_z, 1), a few multiply-adds in a shader. Ramamoorthi and Hanrahan published it in 2001. The error is at most 3/32≈9%3/32 \approx 9\% of the total light of the environment for any lighting, which is a proved bound, and the average error over all normals is under 3% for any physical lighting, which the paper takes from Basri and Jacobs. On natural maps the paper measured smaller errors. The page handles the diffuse part of image-based lighting; the glossy part is the split sum approximation, and the general use of spherical harmonics for light is spherical harmonic lighting.

In plain words

A matte surface gets light from every direction above it, and it weights each direction by how much it faces that direction. This sum changes slowly when the surface turns, because it averages over half of the sky. A slow function can be described by a few numbers, like a smooth curve that needs only a few terms of a series. The method finds nine such numbers for the whole environment, once. To shade a pixel, it combines the nine numbers with the normal of the pixel, which gives the light for that normal at once, without a look at the environment again. The answer is smooth and fast, but it loses sharp detail such as the exact edge of a shadow from the sun.

The problem

The input is a distant lighting environment, given as ss texels (ωk,Lk,Δωk)(\omega_k, L_k, \Delta\omega_k): a unit direction, a radiance and a solid angle, for one color channel. The solid angles add up to 4π4\pi. The output is a function that returns, for a unit normal nn, an approximation of the irradiance

E(n)=∫S2L(ω)max⁡(0,n⋅ω) dω.E(n) = \int_{S^2} L(\omega) \max(0, n \cdot \omega)\, d\omega.

A Lambertian surface with albedo ρ\rho then has the outgoing radiance ρE(n)/π\rho E(n) / \pi, see Lambertian reflectance. The standing assumptions are: the sources are far away, so LL does not depend on the position (a physical approximation); the surface is diffuse; and nothing blocks the light, so there is no shadow and no interreflection. The environment can be a cube map or a latitude and longitude map; only the texel directions and solid angles matter.

The spherical harmonics are the ones of the paper, with zz as the polar axis: Y00=0.282095Y_{00} = 0.282095; Y1,−1,Y10,Y11=0.488603 (y,z,x)Y_{1,-1}, Y_{10}, Y_{11} = 0.488603\,(y, z, x); Y2,−2,Y2,−1,Y21=1.092548 (xy,yz,xz)Y_{2,-2}, Y_{2,-1}, Y_{21} = 1.092548\,(xy, yz, xz); Y20=0.315392 (3z2−1)Y_{20} = 0.315392\,(3z^2 - 1); and Y22=0.546274 (x2−y2)Y_{22} = 0.546274\,(x^2 - y^2). They are orthonormal on the sphere (a proved property).

The algorithm

  1. IRRADIANCE-MAP(texels)
  2. 1L_lm ← 0 for the nine pairs (l, m) with l ≤ 2
  3. 2for each texel (ω, L, Δω)
  4. 3for each (l, m): L_lm ← L_lm + L · Y_lm(ω) · Δω
  5. 4M ← [[c1 L22, c1 L2-2, c1 L21, c2 L11],
  6. [c1 L2-2, -c1 L22, c1 L2-1, c2 L1-1],
  7. [c1 L21, c1 L2-1, c3 L20, c2 L10],
  8. [c2 L11, c2 L1-1, c2 L10, c4 L00 - c5 L20]]
  9. 5return M
  10. IRRADIANCE(M, n)
  11. 6ñ ← (n_x, n_y, n_z, 1)
  12. 7return ñᵀ M ñ

Projection (lines L1 to L3). This is Equation 10 of the paper, a quadrature of ∫LYlm dω\int L Y_{lm}\, d\omega. Each texel adds its radiance times the nine basis values times its solid angle. The texels can come in any order and need no storage, so the loop is one pass over the map.

The kernel. The irradiance is the convolution of LL with the clamped cosine A(t)=max⁡(t,0)A(t) = \max(t, 0). By the Funk-Hecke theorem, this convolution multiplies each coefficient of band ll by one number, A^l=2π∫01tPl(t) dt\hat A_l = 2\pi \int_0^1 t P_l(t)\, dt. The values are A^0=π\hat A_0 = \pi, A^1=2π/3\hat A_1 = 2\pi/3 and A^2=π/4\hat A_2 = \pi/4. The paper gives the general formula: A^l\hat A_l is 0 for odd l>1l > 1, and for even ll it falls off like l−5/2l^{-5/2}, so A^4=−0.1309\hat A_4 = -0.1309 and A^6=0.0491\hat A_6 = 0.0491 are already small. This decay is why nine terms are enough.

The matrix (line L4). Line L4 folds A^l\hat A_l and the basis constants into five numbers: c1=0.429043c_1 = 0.429043, c2=0.511664c_2 = 0.511664, c3=0.743125c_3 = 0.743125, c4=0.886227c_4 = 0.886227 and c5=0.247708c_5 = 0.247708, for example c4=A^0Y00c_4 = \hat A_0 Y_{00} and c1=A^2⋅0.546274c_1 = \hat A_2 \cdot 0.546274. The quadratic form n~TMn~\tilde n^T M \tilde n then equals ∑l≤2A^lLlmYlm(n)\sum_{l \le 2} \hat A_l L_{lm} Y_{lm}(n) term by term. One matrix is built per color channel, so an RGB map gives three matrices.

Evaluation (lines L6 and L7). Line L7 is Equation 11 of the paper. In a shader it is three 4-vector products per channel. The expanded form of Equation 13, c1L22(x2−y2)+c3L20z2+c4L00−c5L20+2c1(L2,−2xy+L21xz+L2,−1yz)+2c2(L11x+L1,−1y+L10z)c_1 L_{22}(x^2 - y^2) + c_3 L_{20} z^2 + c_4 L_{00} - c_5 L_{20} + 2 c_1 (L_{2,-2} xy + L_{21} xz + L_{2,-1} yz) + 2 c_2 (L_{11} x + L_{1,-1} y + L_{10} z), gives the same number.

Example

The environment has two texels that act as point lights: power LΔω=2L \Delta\omega = 2 from +z+z and power 11 from +x+x. The table shows the nonzero coefficients after each texel.

step L00L_{00} L10L_{10} L11L_{11} L20L_{20} L22L_{22}
after L1 0 0 0 0 0
texel +z+z, weight 2 0.564190 0.977206 0 1.261566 0
texel +x+x, weight 1 0.846284 0.977206 0.488603 0.946174 0.546274

At +z+z, Y20=0.315392⋅2Y_{20} = 0.315392 \cdot 2; at +x+x, Y20=0.315392⋅(−1)Y_{20} = 0.315392 \cdot (-1) and Y22=0.546274Y_{22} = 0.546274. Line L4 gives, in exact fractions,

M=(15/64001/40−15/64000045/641/21/401/233/64).M = \begin{pmatrix} 15/64 & 0 & 0 & 1/4 \\ 0 & -15/64 & 0 & 0 \\ 0 & 0 & 45/64 & 1/2 \\ 1/4 & 0 & 1/2 & 33/64 \end{pmatrix}.
normal nn E9(n)=n~TMn~E_9(n) = \tilde n^T M \tilde n exact E(n)E(n) error
+z+z 142/64 = 2.21875 2 0.21875
+x+x 80/64 = 1.25 1 0.25
+y+y 18/64 = 0.28125 0 0.28125
−z-z 14/64 = 0.21875 0 0.21875

The total power is 3, so the bound is 3⋅3/32=0.281253 \cdot 3/32 = 0.28125. The normal +y+y is perpendicular to both lights and reaches the bound. Point lights are the worst case for the method. A smooth sky is the best case: for the radiance L=1L = 1 on the upper hemisphere and 0 below, the projection gives L00=πL_{00} = \sqrt\pi, L10=0.488603 πL_{10} = 0.488603\,\pi and 0 for the other seven coefficients, and E9(n)=π(1+nz)/2E_9(n) = \pi(1 + n_z)/2, which is the exact irradiance.

Correctness

Three facts make the algorithm correct; the proof gives all steps. First, by the Funk-Hecke theorem, the convolution with the clamped cosine maps each harmonic YlmY_{lm} to A^lYlm\hat A_l Y_{lm}. Second, the quadratic form of line L7 equals ∑l≤2A^lLlmYlm(n)\sum_{l \le 2} \hat A_l L_{lm} Y_{lm}(n), term by term. Together they give E9=EE_9 = E for lighting with no component above band 2 (a proved property). Third, for any lighting L≥0L \ge 0, E9(n)=∫L(ω)A9(n⋅ω) dωE_9(n) = \int L(\omega) A_9(n \cdot \omega)\, d\omega with A9(t)=3/32+t/2+15t2/32A_9(t) = 3/32 + t/2 + 15 t^2/32. Since ∣A−A9∣≤3/32|A - A_9| \le 3/32, with equality at t=0t = 0, the error is at most 3/323/32 of ∫L dω\int L\, d\omega, the total light, at every normal (a proved bound). The same bound holds exactly for the texel sums, which is what the tests check.

The paper states the error in two ways (Section 3.1). The maximum error for any pixel, as a fraction of the total intensity of the lighting, is 9%, the value of 3/323/32. The average error over all surface orientations is under 3% for any physical lighting, a result of Basri and Jacobs. For its three natural environment maps, the paper measured an average error under 1% and a maximum pixel error under 5% (a measurement). The stub summary of this page said only "an error below about three percent"; that number is an average, not a worst case.

Proof: Correctness and error bound of the nine term irradiance mapfull

Setting. The lighting is a radiance L(ω)≥0L(\omega) \ge 0 on the unit sphere S2S^2, for distant sources, so it depends on the direction only. The surface is Lambertian and the visibility is ignored. The irradiance at a unit normal nn is

E(n)=∫S2L(ω) A(n⋅ω) dω,A(t)=max⁡(t,0).E(n) = \int_{S^2} L(\omega)\, A(n \cdot \omega)\, d\omega, \qquad A(t) = \max(t, 0).

YlmY_{lm} are the real spherical harmonics of the page, orthonormal on S2S^2. Lines L1 to L3 compute Llm=∑kL(ωk)Ylm(ωk)ΔωkL_{lm} = \sum_k L(\omega_k) Y_{lm}(\omega_k) \Delta\omega_k for l≤2l \le 2, line L4 builds the matrix MM and line L7 returns E9(n)=n~TMn~E_9(n) = \tilde n^T M \tilde n with n~=(x,y,z,1)\tilde n = (x, y, z, 1). The claims are about this computation in exact arithmetic.

Claim 1 (the kernel in each band). For every ll and every unit nn,

∫S2Ylm(ω)A(n⋅ω) dω=A^l Ylm(n),A^l=2π∫01t Pl(t) dt,\int_{S^2} Y_{lm}(\omega) A(n \cdot \omega)\, d\omega = \hat A_l\, Y_{lm}(n), \qquad \hat A_l = 2\pi \int_0^1 t\, P_l(t)\, dt,

where PlP_l is the Legendre polynomial. In particular A^0=π\hat A_0 = \pi, A^1=2π/3\hat A_1 = 2\pi/3 and A^2=π/4\hat A_2 = \pi/4.

Proof. The function AA is in L2([−1,1])L^2([-1, 1]), so it has the Legendre expansion A(t)=∑jajPj(t)A(t) = \sum_j a_j P_j(t) with aj=2j+12∫−11A(t)Pj(t) dt=2j+12∫01tPj(t) dta_j = \frac{2j+1}{2} \int_{-1}^1 A(t) P_j(t)\, dt = \frac{2j+1}{2} \int_0^1 t P_j(t)\, dt. The addition theorem gives Pj(n⋅ω)=4π2j+1∑m′Yjm′(n)Yjm′(ω)P_j(n \cdot \omega) = \frac{4\pi}{2j+1} \sum_{m'} Y_{jm'}(n) Y_{jm'}(\omega). Put this into the integral. By orthonormality only the term j=lj = l, m′=mm' = m is left, and its value is al4π2l+1Ylm(n)=2π∫01tPl(t) dt⋅Ylm(n)a_l \frac{4\pi}{2l+1} Y_{lm}(n) = 2\pi \int_0^1 t P_l(t)\, dt \cdot Y_{lm}(n). With P0=1P_0 = 1, P1=tP_1 = t and P2=(3t2−1)/2P_2 = (3t^2 - 1)/2, the integrals are 1/21/2, 1/31/3 and (3/4−1/2)/2=1/8(3/4 - 1/2)/2 = 1/8, so A^0=π\hat A_0 = \pi, A^1=2π/3\hat A_1 = 2\pi/3 and A^2=π/4\hat A_2 = \pi/4. □\square

Claim 2 (the matrix is the truncated sum). For all coefficients LlmL_{lm} and all unit nn, n~TMn~=∑l≤2∑mA^lLlmYlm(n)\tilde n^T M \tilde n = \sum_{l \le 2} \sum_m \hat A_l L_{lm} Y_{lm}(n).

Proof. Write the constants as c1=A^2⋅0.546274=A^2⋅1415/πc_1 = \hat A_2 \cdot 0.546274 = \hat A_2 \cdot \frac14 \sqrt{15/\pi}, c2=12A^13/(4π)c_2 = \frac12 \hat A_1 \sqrt{3/(4\pi)}, c3=3A^2⋅145/πc_3 = 3 \hat A_2 \cdot \frac14 \sqrt{5/\pi}, c4=A^0⋅121/πc_4 = \hat A_0 \cdot \frac12 \sqrt{1/\pi} and c5=A^2⋅145/πc_5 = \hat A_2 \cdot \frac14 \sqrt{5/\pi}. Expand n~TMn~\tilde n^T M \tilde n for the symmetric MM of line L4:

c1L22(x2−y2)+c3L20z2+c4L00−c5L20+2c1(L2,−2xy+L21xz+L2,−1yz)+2c2(L11x+L1,−1y+L10z).c_1 L_{22}(x^2 - y^2) + c_3 L_{20} z^2 + c_4 L_{00} - c_5 L_{20} + 2 c_1 (L_{2,-2} xy + L_{21} xz + L_{2,-1} yz) + 2 c_2 (L_{11} x + L_{1,-1} y + L_{10} z).

Compare with the sum term by term. Band 0: A^0L00Y00=c4L00\hat A_0 L_{00} Y_{00} = c_4 L_{00}. Band 1: A^13/(4π)=2c2\hat A_1 \sqrt{3/(4\pi)} = 2 c_2, and Y1,−1,Y10,Y11Y_{1,-1}, Y_{10}, Y_{11} are 3/(4π)\sqrt{3/(4\pi)} times y,z,xy, z, x. Band 2: the factor of Y2,−2,Y2,−1,Y21Y_{2,-2}, Y_{2,-1}, Y_{21} is 1215/π=2⋅1415/π\frac12\sqrt{15/\pi} = 2 \cdot \frac14 \sqrt{15/\pi}, so their terms are 2c12 c_1 times xyxy, yzyz, xzxz; the term of Y22Y_{22} is c1(x2−y2)c_1 (x^2 - y^2); the term of Y20Y_{20} is A^2145/π(3z2−1)=c3z2−c5\hat A_2 \frac14 \sqrt{5/\pi} (3 z^2 - 1) = c_3 z^2 - c_5. Every term matches. □\square

Claim 3 (exact for band limited lighting). If the rule of lines L1 to L3 gives the exact coefficients Llm=∫LYlm dωL_{lm} = \int L Y_{lm}\, d\omega, and LL has no component in the bands l≥3l \ge 3, then E9(n)=E(n)E_9(n) = E(n) for every nn.

Proof. Write L=∑l≤2,mLlmYlmL = \sum_{l \le 2, m} L_{lm} Y_{lm}. By linearity and Claim 1, E(n)=∑l≤2,mLlmA^lYlm(n)E(n) = \sum_{l \le 2, m} L_{lm} \hat A_l Y_{lm}(n), which is E9(n)E_9(n) by Claim 2. □\square

The test file uses a rule that is Gauss-Legendre in zz on each hemisphere and uniform in φ\varphi. It integrates every polynomial of degree at most 4 in (x,y,z)(x, y, z) exactly, so the coefficients of a band limited lighting, and of the sky of the page, are exact.

Claim 4 (the kernel of nine terms). Define A9(t)=∑l≤22l+14πA^lPl(t)A_9(t) = \sum_{l \le 2} \frac{2l+1}{4\pi} \hat A_l P_l(t). Then A9(t)=332+t2+1532t2A_9(t) = \frac{3}{32} + \frac t2 + \frac{15}{32} t^2, and max⁡t∈[−1,1]∣A(t)−A9(t)∣=332\max_{t \in [-1, 1]} |A(t) - A_9(t)| = \frac{3}{32}, reached only at t=0t = 0.

Proof. The three terms are 14ππ=14\frac{1}{4\pi}\pi = \frac14, 34π2π3t=t2\frac{3}{4\pi}\frac{2\pi}{3} t = \frac t2 and 54ππ43t2−12=15t2−532\frac{5}{4\pi}\frac{\pi}{4}\frac{3t^2 - 1}{2} = \frac{15 t^2 - 5}{32}. Their sum is the stated polynomial. On [0,1][0, 1], A9(t)−A(t)=(15t2−16t+3)/32A_9(t) - A(t) = (15 t^2 - 16 t + 3)/32. This parabola has its values 3/323/32 at t=0t = 0 and 2/322/32 at t=1t = 1, and its smallest value −19/480≈−0.0396-19/480 \approx -0.0396 at t=8/15t = 8/15, so its absolute value is at most 3/323/32, with equality only at t=0t = 0. On [−1,0][-1, 0], A9(t)−A(t)=(15t2+16t+3)/32A_9(t) - A(t) = (15 t^2 + 16 t + 3)/32, the mirror image of the same parabola, with the same bound. □\square

Claim 5 (error bound for any lighting). If L≥0L \ge 0 and the coefficients are exact, then for every unit nn,

∣E(n)−E9(n)∣≤332∫S2L(ω) dω.|E(n) - E_9(n)| \le \frac{3}{32} \int_{S^2} L(\omega)\, d\omega.

The same bound holds for the texel sums: if EE is the brute force sum ∑kLkA(n⋅ωk)Δωk\sum_k L_k A(n \cdot \omega_k) \Delta\omega_k and E9E_9 is computed from the coefficients of lines L1 to L3 on the same texels, then ∣E−E9∣≤332∑kLkΔωk|E - E_9| \le \frac{3}{32} \sum_k L_k \Delta\omega_k. The bound is reached by a point light at a normal perpendicular to it.

Proof. By the addition theorem, ∑l≤2,mA^lYlm(n)Ylm(ω)=A9(n⋅ω)\sum_{l \le 2, m} \hat A_l Y_{lm}(n) Y_{lm}(\omega) = A_9(n \cdot \omega). Multiply by L(ω)L(\omega) and integrate, then use Claim 2: E9(n)=∫L(ω)A9(n⋅ω) dωE_9(n) = \int L(\omega) A_9(n \cdot \omega)\, d\omega. So E(n)−E9(n)=∫L(ω)(A−A9)(n⋅ω) dωE(n) - E_9(n) = \int L(\omega) (A - A_9)(n \cdot \omega)\, d\omega. With L≥0L \ge 0 and Claim 4, its absolute value is at most 332∫L\frac{3}{32} \int L. For the texels, the same steps hold with the integral replaced by the sum over kk, because the coefficients of line L3 are exactly ∑kLkYlm(ωk)Δωk\sum_k L_k Y_{lm}(\omega_k) \Delta\omega_k. For a point light of power PP in the direction dd and n⊥dn \perp d, E(n)=0E(n) = 0 and E9(n)=PA9(0)=332PE_9(n) = P A_9(0) = \frac{3}{32} P. □\square

Ramamoorthi and Hanrahan state this as a maximum pixel error of 9% of the total intensity; 3/32=9.375%3/32 = 9.375\%. Their second number, an average error under 3% over all normals for any physical lighting, they take from Basri and Jacobs. This proof does not cover it.

Cost. Lines L1 to L3 do 9 multiply-adds per texel, Θ(s)\Theta(s) for ss texels, and keep 9 numbers. Line L4 costs O(1)O(1). Lines L6 and L7 cost 16 multiplications and additions, O(1)O(1) per normal. An RGB map repeats the work three times. ■\blacksquare

Complexity

The model is the real RAM, with one unit per arithmetic operation and per evaluation of sin⁡\sin and cos⁡\cos, and ss texels.

  • Build: Θ(s)\Theta(s). Lines L2 and L3 do 9 multiply-adds for each texel. Line L4 is constant work. The paper compares this with the direct convolution of the map, which costs Θ(Ts)\Theta(T s) for TT output texels, and reports under a second against about two hours for a 300×300300 \times 300 map on the hardware of 2001 (a measurement).
  • Evaluate: Θ(1)\Theta(1). Lines L6 and L7 cost 16 multiplications and additions per channel. There is no texture fetch.
  • Space: Θ(1)\Theta(1). The algorithm keeps 9 coefficients, or 10 distinct entries of the symmetric matrix, per channel. The output map is not stored.

Properties

  • Exact for band limited lighting. Lighting that is a polynomial of degree at most 2 in the direction gives the exact irradiance. The hemisphere sky above is one such case for the irradiance.
  • Error bound. At most 3/323/32 of the total light at any normal, for lighting that is not negative (proved). The bound is tight for a point light.
  • Linear in the lighting. The coefficients and the matrix depend linearly on LL, so the map of a sum of environments is the sum of their maps, and an environment can be blended over time by blending the matrices.
  • Smooth output. E9E_9 is a quadratic polynomial in nn, so it has no seams and no aliasing, and it needs no filtering.
  • Rotation. A rotation of the environment mixes the coefficients only inside each band: MM goes to RMRTR M R^T for the 4×44 \times 4 rotation RR that acts on (x,y,z)(x, y, z) and keeps the last coordinate.

Variants and improvements

  • Tabulated irradiance map. The older way to get the same function is to convolve the environment with the clamped cosine into a small cube map, the irradiance map of Miller and Hoffman and Greene. It costs one texture fetch per pixel, and its memory and build cost are higher.
  • Coefficients in place of the matrix. Many engines store the nine A^lLlm\hat A_l L_{lm} values per channel and evaluate the sum of Equation 7 in the shader. It is the same function.
  • Fewer bands. Bands 0 and 1 (four coefficients) give the constant and linear part only, with a larger error. More bands add little for the diffuse term, because A^l\hat A_l is small.
  • Windowing. Bright small sources make E9E_9 go below zero on the far side, because the truncated series rings. A window on the coefficients, for example the Hanning window that Sloan describes, reduces the ringing and blurs the light. The window is tuning.
  • Probes in space. One map per point of a grid gives an irradiance volume, with interpolation between the probes.
  • Shadows and interreflection. The method ignores visibility. Precomputed radiance transfer adds them with a transfer vector per vertex.

When to use it

Use it for the diffuse part of image-based lighting on dynamic objects, when the environment is far away and smooth enough, and when memory and bandwidth matter: nine numbers per channel replace a texture. It is a good fit for sky and probe lighting, and for lighting that changes every frame, because the projection is one pass. For sharp lighting such as a small sun, add the sun as a separate light and leave it out of the map. For glossy reflection, use a prefiltered map and the split sum approximation. For the reference answer, integrate the environment by Monte Carlo integration.

Pitfalls

  • Solid angles left out. Line L3 must multiply by Δω\Delta\omega. On a cube map or a latitude and longitude map, the texels near the corners or the poles have a smaller solid angle. Equal weights at line L3 give a biased LlmL_{lm}.
  • Wrong axis convention. The paper uses zz as the polar axis. In a yy up engine, either rotate the directions at line L3 and the normal at line L6 in the same way, or permute the entries of MM. Mixing the two conventions gives light from the wrong side.
  • Forgetting A^l\hat A_l, or applying it twice. Line L4 already holds A^l\hat A_l in c1c_1 to c5c_5. If the code stores convolved coefficients A^lLlm\hat A_l L_{lm} and then uses the matrix of line L4, the bands are scaled twice.
  • The 1/π1/\pi of the BRDF. Line L7 returns irradiance. The diffuse radiance is ρE/π\rho E / \pi. Using ρE\rho E makes the surface π\pi times too bright.
  • Negative values. For lighting with a bright small source, E9E_9 can be negative at normals that face away from it. Clamp the result of line L7 at 0, or window the coefficients.
  • Gamma encoded input. The projection needs linear radiance. Decode an sRGB map first, see gamma correction.
  • Rounded constants. The printed c2=0.511664c_2 = 0.511664 and c3=0.743125c_3 = 0.743125 come from the rounded basis constants; the exact values are 0.51166340.5116634 and 0.74312390.7431239. Compute them from π\pi when a check needs more than six digits.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

irradiance_environment_map.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/irradiance-environment-map/. The authors are listed in prov/H7PF86.jsonl.

"""The irradiance environment map of Ramamoorthi and Hanrahan (2001).

The environment is a list of texels (direction, radiance, solid angle) of one
color channel, for distant lighting. The algorithm projects the radiance onto
the nine real spherical harmonics of order l <= 2, puts the coefficients into
a symmetric 4 by 4 matrix M (Equation 12 of the paper), and evaluates the
irradiance at a unit normal n as E(n) = (n, 1)^T M (n, 1) (Equation 11).
For an RGB map, run it once for each channel.

Precondition: the directions are unit vectors and the solid angles add up to
4 pi (any quadrature rule on the sphere). Cost: Theta(9 S) for S texels to
build M, and Theta(1) for each evaluation.

The basis order in a coefficient list is (0,0), (1,-1), (1,0), (1,1), (2,-2),
(2,-1), (2,0), (2,1), (2,2). The convention is the one of the paper:
z is the polar axis, x = sin theta cos phi and y = sin theta sin phi.
"""

import math

# Normalization constants of the real spherical harmonics (Equation 3).
Y0 = 0.5 / math.sqrt(math.pi)                    # 0.282095
Y1 = math.sqrt(3.0 / (4.0 * math.pi))            # 0.488603
Y2 = 0.5 * math.sqrt(15.0 / math.pi)             # 1.092548
Y20 = 0.25 * math.sqrt(5.0 / math.pi)            # 0.315392
Y22 = 0.25 * math.sqrt(15.0 / math.pi)           # 0.546274

# The clamped cosine kernel in each band (Equations 8 and 9).
A_HAT = (math.pi, 2.0 * math.pi / 3.0, math.pi / 4.0)
BAND = (0, 1, 1, 1, 2, 2, 2, 2, 2)

# The constants of Equation 12, from the two lists above.
C1 = A_HAT[2] * Y22                              # 0.429043
C2 = A_HAT[1] * Y1 / 2.0                         # 0.511664
C3 = A_HAT[2] * Y20 * 3.0                        # 0.743125
C4 = A_HAT[0] * Y0                               # 0.886227
C5 = A_HAT[2] * Y20                              # 0.247708

Vec = tuple[float, float, float]
Texel = tuple[Vec, float, float]


def sh9(d: Vec) -> list[float]:
    """The nine real spherical harmonics at the unit vector d."""
    x, y, z = d
    return [
        Y0,
        Y1 * y,
        Y1 * z,
        Y1 * x,
        Y2 * x * y,
        Y2 * y * z,
        Y20 * (3.0 * z * z - 1.0),
        Y2 * x * z,
        Y22 * (x * x - y * y),
    ]


def project(texels: list[Texel]) -> list[float]:
    """Equation 10: L_lm = sum of L(w) Y_lm(w) dw over the texels."""
    coeffs = [0.0] * 9  # @line L1
    for d, radiance, domega in texels:  # @line L2
        y = sh9(d)
        for k in range(9):  # @line L3
            coeffs[k] += radiance * y[k] * domega
    return coeffs


def irradiance_matrix(coeffs: list[float]) -> list[list[float]]:
    """Equation 12: the symmetric 4 by 4 matrix M from the nine L_lm."""
    l00, l1m1, l10, l11, l2m2, l2m1, l20, l21, l22 = coeffs
    return [  # @line L4
        [C1 * l22, C1 * l2m2, C1 * l21, C2 * l11],
        [C1 * l2m2, -C1 * l22, C1 * l2m1, C2 * l1m1],
        [C1 * l21, C1 * l2m1, C3 * l20, C2 * l10],
        [C2 * l11, C2 * l1m1, C2 * l10, C4 * l00 - C5 * l20],
    ]


def build(texels: list[Texel]) -> list[list[float]]:
    """IRRADIANCE-MAP: lines L1 to L5."""
    m = irradiance_matrix(project(texels))
    return m  # @line L5


def irradiance(m: list[list[float]], n: Vec) -> float:
    """Equation 11: E(n) = (n, 1)^T M (n, 1) for a unit normal n."""
    h = (n[0], n[1], n[2], 1.0)  # @line L6
    return sum(h[i] * m[i][j] * h[j] for i in range(4) for j in range(4))  # @line L7


def irradiance_sh(coeffs: list[float], n: Vec) -> float:
    """Equation 7: E(n) = sum of A_hat_l L_lm Y_lm(n), the same value as line L7."""
    y = sh9(n)
    return sum(A_HAT[BAND[k]] * coeffs[k] * y[k] for k in range(9))


def irradiance_brute_force(texels: list[Texel], n: Vec) -> float:
    """The reference: E(n) = sum of L(w) max(0, n . w) dw over all texels."""
    total = 0.0
    for d, radiance, domega in texels:
        c = n[0] * d[0] + n[1] * d[1] + n[2] * d[2]
        if c > 0.0:
            total += radiance * c * domega
    return total


def point_light_coeffs(d: Vec, power: float) -> list[float]:
    """The exact coefficients of a delta light of the given power in direction d."""
    return [power * y for y in sh9(d)]


def gauss_legendre(n: int) -> list[tuple[float, float]]:
    """Nodes and weights of the n point Gauss-Legendre rule on [-1, 1], by Newton's method."""
    out = []
    for i in range(1, n + 1):
        x = math.cos(math.pi * (i - 0.25) / (n + 0.5))
        for _ in range(100):
            p0, p1 = 1.0, x
            for k in range(2, n + 1):
                p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
            dp = n * (x * p1 - p0) / (x * x - 1.0)
            dx = p1 / dp
            x -= dx
            if abs(dx) < 1e-15:
                break
        p0, p1 = 1.0, x
        for k in range(2, n + 1):
            p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
        dp = n * (x * p1 - p0) / (x * x - 1.0)
        out.append((x, 2.0 / ((1.0 - x * x) * dp * dp)))
    return out


def sphere_texels(radiance, n_z: int, n_phi: int) -> list[Texel]:
    """Sample a radiance function on the sphere as texels.

    The rule is Gauss-Legendre in z on [-1, 0] and on [0, 1] separately, and
    uniform in phi. It integrates exactly a polynomial in (x, y, z) of degree
    below min(2 n_z, n_phi) on each hemisphere, so a lighting with a jump at
    the horizon still projects exactly when it is a polynomial on each half.
    """
    texels = []
    rule = gauss_legendre(n_z)
    for lo in (-1.0, 0.0):
        for t, w in rule:
            z = lo + 0.5 * (t + 1.0)
            s = math.sqrt(max(0.0, 1.0 - z * z))
            for j in range(n_phi):
                phi = 2.0 * math.pi * (j + 0.5) / n_phi
                d = (s * math.cos(phi), s * math.sin(phi), z)
                texels.append((d, radiance(d), 0.5 * w * 2.0 * math.pi / n_phi))
    return texels
test_irradiance_environment_map.py 154 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/irradiance-environment-map/. The authors are listed in prov/H7PF86.jsonl.

"""Tests of the irradiance environment map against closed forms and brute force.

The constants are checked against the values printed in the paper, the basis
for orthonormality, the matrix form against the spherical harmonic sum, and
the nine term irradiance against brute force quadrature: exactly for lighting
that is band limited, and within the proved bound 3/32 of the total light for
any lighting that is not negative.
"""

import math
import random

from irradiance_environment_map import (
    A_HAT,
    C1,
    C2,
    C3,
    C4,
    C5,
    build,
    gauss_legendre,
    irradiance,
    irradiance_brute_force,
    irradiance_matrix,
    irradiance_sh,
    point_light_coeffs,
    project,
    sh9,
    sphere_texels,
)


def unit(rng: random.Random) -> tuple[float, float, float]:
    while True:
        v = (rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-1, 1))
        r = math.sqrt(v[0] ** 2 + v[1] ** 2 + v[2] ** 2)
        if 0.1 < r <= 1.0:
            return (v[0] / r, v[1] / r, v[2] / r)


def test_constants_of_the_paper() -> None:
    for got, want in ((C1, 0.429043), (C2, 0.511664), (C3, 0.743125), (C4, 0.886227), (C5, 0.247708)):
        # The exact c2 and c3 are 0.5116634 and 0.7431239. The printed values
        # 0.511664 and 0.743125 come from the rounded basis constants.
        assert abs(got - want) < 2e-6
    for got, want in zip(A_HAT, (3.141593, 2.094395, 0.785398)):
        assert abs(got - want) < 5e-7


def test_kernel_is_the_clamped_cosine() -> None:
    # A_hat_l = 2 pi times the integral of t P_l(t) over [0, 1].
    legendre = (lambda t: 1.0, lambda t: t, lambda t: 0.5 * (3 * t * t - 1))
    rule = gauss_legendre(6)
    for l in range(3):
        val = 2 * math.pi * sum(0.5 * w * ((x + 1) / 2) * legendre[l]((x + 1) / 2) for x, w in rule)
        assert abs(val - A_HAT[l]) < 1e-12


def test_basis_is_orthonormal() -> None:
    texels = sphere_texels(lambda d: 1.0, 3, 8)
    assert abs(sum(t[2] for t in texels) - 4 * math.pi) < 1e-12
    for i in range(9):
        for j in range(9):
            s = sum(sh9(d)[i] * sh9(d)[j] * dw for d, _, dw in texels)
            assert abs(s - (1.0 if i == j else 0.0)) < 1e-12


def test_matrix_equals_the_harmonic_sum() -> None:
    rng = random.Random(7)
    for _ in range(50):
        coeffs = [rng.uniform(-2, 2) for _ in range(9)]
        m = irradiance_matrix(coeffs)
        assert all(m[i][j] == m[j][i] for i in range(4) for j in range(4))
        for _ in range(5):
            n = unit(rng)
            assert abs(irradiance(m, n) - irradiance_sh(coeffs, n)) < 1e-12


def test_point_light_check_values() -> None:
    d = (0.0, 0.0, 1.0)
    m = irradiance_matrix(point_light_coeffs(d, 1.0))
    assert abs(irradiance(m, d) - 17 / 16) < 1e-12
    assert abs(irradiance(m, (0.0, 0.0, -1.0)) - 1 / 16) < 1e-12
    assert abs(irradiance(m, (1.0, 0.0, 0.0)) - 3 / 32) < 1e-12


def test_kernel_of_nine_terms() -> None:
    # The addition theorem: sum of A_hat Y(w) Y(n) = 3/32 + t/2 + 15 t^2 / 32 with t = n . w.
    rng = random.Random(3)
    for _ in range(100):
        n, w = unit(rng), unit(rng)
        t = sum(a * b for a, b in zip(n, w))
        val = irradiance_sh(point_light_coeffs(w, 1.0), n)
        assert abs(val - (3 / 32 + t / 2 + 15 * t * t / 32)) < 1e-12


def test_sky_is_exact() -> None:
    texels = sphere_texels(lambda d: 1.0 if d[2] > 0 else 0.0, 4, 8)
    coeffs = project(texels)
    assert abs(coeffs[0] - math.sqrt(math.pi)) < 1e-12
    assert abs(coeffs[2] - 0.5 * math.sqrt(3 * math.pi)) < 1e-12
    assert all(abs(coeffs[k]) < 1e-12 for k in (1, 3, 4, 5, 6, 7, 8))
    m = build(texels)
    rng = random.Random(11)
    for _ in range(30):
        n = unit(rng)
        assert abs(irradiance(m, n) - math.pi * (1 + n[2]) / 2) < 1e-12


def test_band_limited_lighting_matches_brute_force() -> None:
    rng = random.Random(5)
    coeffs = [rng.uniform(-1, 1) for _ in range(9)]
    coeffs[0] = 4.0

    def radiance(d):
        return sum(c * y for c, y in zip(coeffs, sh9(d)))

    m = build(sphere_texels(radiance, 3, 8))
    fine = sphere_texels(radiance, 24, 96)
    for _ in range(8):
        n = unit(rng)
        assert abs(irradiance(m, n) - irradiance_sh(coeffs, n)) < 1e-12
        assert abs(irradiance(m, n) - irradiance_brute_force(fine, n)) < 2e-3


def test_error_bound_for_any_lighting() -> None:
    rng = random.Random(13)
    texels = sphere_texels(lambda d: 0.0, 6, 12)
    for trial in range(10):
        lit = [(d, rng.random() ** 6 * 10.0, dw) for d, _, dw in texels]
        total = sum(r * dw for _, r, dw in lit)
        m = build(lit)
        worst = 0.0
        for _ in range(20):
            n = unit(rng)
            err = abs(irradiance(m, n) - irradiance_brute_force(lit, n))
            worst = max(worst, err)
            assert err <= 3 / 32 * total + 1e-9
        assert worst > 0.0


def test_linear_in_the_lighting() -> None:
    rng = random.Random(17)
    texels = sphere_texels(lambda d: 0.0, 3, 8)
    a = [(d, rng.random(), dw) for d, _, dw in texels]
    b = [(d, rng.random(), dw) for d, _, dw in texels]
    ab = [(d, 2.0 * x[1] + 3.0 * y[1], d2) for (d, _, d2), x, y in zip(texels, a, b)]
    ma, mb, mab = build(a), build(b), build(ab)
    for i in range(4):
        for j in range(4):
            assert abs(mab[i][j] - 2.0 * ma[i][j] - 3.0 * mb[i][j]) < 1e-12

History

Reflection mapping goes back to Blinn and Newell (1976), and Miller and Hoffman (1984) convolved environment maps to get diffuse and glossy reflection maps; Greene (1986) stored environments as cube maps and also prefiltered them. These maps were built by direct convolution, which was slow. In 2001, Ramamoorthi and Hanrahan, and at the same time Basri and Jacobs in computer vision, showed that the clamped cosine acts as a low pass filter on the sphere, so that the irradiance is close to a function of the first nine spherical harmonics. Ramamoorthi and Hanrahan wrote it as a quadratic form in the normal that a vertex or pixel shader could evaluate. Spherical harmonics then became the common way to store diffuse lighting in games, in precomputed radiance transfer (Sloan, Kautz and Snyder 2002) and in light probes.

References

  1. Ravi Ramamoorthi and Pat Hanrahan, An efficient representation for irradiance environment maps, SIGGRAPH 2001, 497 to 500, Section 2 (Equations 3 to 9, the basis and the clamped cosine coefficients), Section 3.1 (prefiltering, Equation 10, and the error statement) and Section 3.2 (Equations 11 to 13, the matrix form and the constants c1 to c5)
  2. Ronen Basri and David W. Jacobs, Lambertian reflectance and linear subspaces, IEEE International Conference on Computer Vision (ICCV), 2001, the analysis of the clamped cosine kernel and the bound on the average error of a nine term approximation (general locator, cited by Ramamoorthi and Hanrahan for the 3% figure)
  3. Tomas Akenine-Möller, Eric Haines, Naty Hoffman, Angelo Pesce, Michał Iwanicki and Sébastien Hillaire, Real-Time Rendering, fourth edition, CRC Press, 2018, Chapter 10, Local Illumination (the parts on spherical harmonics and on environment lighting)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.build
  • a full proof of time.evaluate
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example