Algorithmadvanced
Precomputed atmospheric scattering
Also called Bruneton atmospheric scattering.
Precompute transmittance and single and multiple Rayleigh and Mie scattering into 2D and 4D tables, so that sky and aerial perspective render from any altitude with a few lookups.
- Time
- Θ(q) single_scattering_rayΘ(t q) transmittance_table
- Space
- Θ(t) table
- Where
- q = the number of quadrature steps along one ray; t = the number of entries of the transmittance table
- Model
- Real RAM
- Properties
- deterministicnot in placeofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Eric Bruneton, Fabrice Neyret, 2008
Precomputed atmospheric scattering draws the color of a clear sky, and the haze between the camera and distant objects, from tables that are computed once for a given atmosphere. The atmosphere is a spherical shell around the planet, with air molecules that scatter by the Rayleigh law and aerosols that scatter by the Mie law, each with a density that falls exponentially with altitude. Bruneton and Neyret (2008) store the transmittance in a 2D table over altitude and view angle, and the single and multiple scattered light in a 4D table over altitude, view angle, sun angle and the angle between the view and the sun. A pixel then costs a few texture reads, from any altitude and for any sun position. This page explains the method and gives a toy version in code: the code builds the transmittance table and computes single scattering along one view ray by quadrature with it. The toy does not build the 4D table and has no multiple scattering, and its numbers are those of a toy atmosphere.
In plain words
Sunlight that enters the air bounces off molecules and small particles. Blue light bounces much more than red light, which is why the sky looks blue, and why the sun looks red near the horizon, when its light crosses much more air. To find the color of the sky in one direction, you would add up the light that bounces toward you from every point along that direction, weakened by the air it crosses on its way. That sum is slow. But in a round planet with layered air, the answer only depends on a few numbers: how high you are, where you look and where the sun is. So the method works out the answer for many such cases ahead of time and stores them in tables. At run time it reads the tables.
The problem
The input is an atmosphere: the ground radius , the top radius , the scattering and extinction coefficients of molecules and aerosols at sea level, their scale heights, and the phase functions. The output is the radiance that reaches a point from the direction , for the sun at a fixed direction with irradiance , and the transmittance between two points. The standing assumptions are physical laws of the model, stated as such:
- Extinction. Light along a segment is attenuated by , the Beer-Lambert law, with .
- Density. and at altitude . Bruneton and Neyret use km and km, and per km at 680, 550 and 440 nm. These ratios follow the law of Rayleigh scattering within 1%.
- Phase functions. Rayleigh and the Cornette-Shanks function for Mie, with the cosine of the angle between the view and the sun.
- Symmetry. The atmosphere depends only on altitude. Then depends only on , , and , four numbers. This is why a 4D table is enough.
The single scattered part is
with , the distance to the ground or to the top, the visibility of the sun and the transmittance from toward the sun. Higher orders replace by the light of the previous order that arrives at from all directions.
The algorithm
The full method of Bruneton and Neyret has these steps:
- Transmittance. Compute to the top of the atmosphere on a 2D grid, by quadrature of the optical depth.
- Single scattering. Compute on a 4D grid, by quadrature along each ray, with every transmittance read from step 1. Implementations usually keep the single scattering phase functions out of the table and apply them per pixel, so that the sharp forward peak of Mie scattering does not need a fine angular grid (a design choice, not a requirement).
- Ground irradiance. Compute the irradiance on the ground as a function of and , for light that the ground reflects back into the air.
- Higher orders. For each order : at every 4D grid point, integrate the order light over incoming directions with the phase functions, which gives the scattering density; then integrate that density along each ray with the transmittance, and add the result to the 4D table.
- Rendering. For a sky pixel, read the 4D table at the camera and multiply by the phase functions. For a surface at seen from , the aerial perspective is , two 4D lookups and one transmittance, and the surface color is attenuated by .
The toy code covers step 1 and step 2 for one view ray:
SINGLE-SCATTERING(r, μ, μs, ν)- 1
for each table entry (x_r, x_μ): T[x_r][x_μ] ← exp(-optical depth from (r, μ) to the top) ▷ once - 2
D ← distance to the ground if the ray hits it, else to the top - 3
S ← 0 - 4
for k ← 0 to q: s ← k D / q; w ← 1/2 at the two ends, 1 inside - 5
r_s ← sqrt(r² + s² + 2 r μ s); μ_s,y ← (r μs + s ν) / r_s - 6
T_view ← T(r, μ) / T(r_s, μ_y), or T(r_s, -μ_y) / T(r, -μ) if the ray hits the ground - 7
if the sun is below the horizon at r_s, skip this step; else T_sun ← T(r_s, μ_s,y) - 8
S ← S + w · T_view · T_sun · (β_R(r_s) P_R(ν) + β_M(r_s) P_M(ν)) - 9
return S · D / q
Line L1 fills the transmittance table at the rays given by the mapping of Bruneton's 2017 code: with and , and the distance to the top scaled between its least value (looking up) and its largest value (along the horizon). Lookups are bilinear in . Line L2 gives the length of the ray in the atmosphere. Line L5 uses the law of cosines for the point at distance . Line L6 gets the transmittance of the part of the ray up to from two table entries, because transmittance multiplies along a ray. Line L7 checks whether the planet hides the sun at that point. Line L8 adds the light scattered toward the camera, and line L9 finishes the trapezoidal rule.
Example
The toy atmosphere uses the Rayleigh values above, km, km, per km, an albedo of 0.9 for the aerosols and ; these last values are tuning of the toy. The table has entries with 200 steps each, and single scattering uses . The three numbers are red, green and blue, per unit sun irradiance.
| view from the ground | quantity | red | green | blue |
|---|---|---|---|---|
| straight up | transmittance to the top | 0.9496 | 0.8929 | 0.7633 |
| along the horizon (876 km of air) | transmittance to the top | 0.1192 | 0.0135 | 0.0001 |
| straight up, sun at the zenith | single scattering, 1/sr | 0.0242 | 0.0293 | 0.0393 |
| straight up, sun 60 degrees from the zenith | single scattering, 1/sr | 0.0033 | 0.0069 | 0.0133 |
| 78 degrees from the zenith, toward a setting sun (, ) | single scattering, 1/sr | 0.0190 | 0.0216 | 0.0135 |
These are measurements of the toy. The zenith is blue when the sun is high, by a factor of 4 between blue and red, and the light near a low sun is yellow and red, because the blue part of the sunlight is lost on the long path to each scattering point. The table lookups agree with direct quadrature to within in transmittance over random rays, and the single scattering values to within 1% for the five test rays. With a table that is linear in instead of in the distance , the largest transmittance error grew to , all of it near the horizon.
Correctness
The proof shows that line L5 gives the altitude and the sun angle at each point of the ray, that the ground test of lines L2 and L7 is exact, that the table mapping of line L1 is a bijection with the stated inverse, that line L6 equals the transmittance of the segment (because optical depth adds along a ray and does not depend on the direction), that the phase functions integrate to 1 over the sphere for any , and that lines L3 to L9 are the trapezoidal rule for the single scattering integral, which converges as grows. These are proved properties. The model itself (exponential layers, Rayleigh and Mie laws, single and multiple scattering) is physical law applied to an idealized atmosphere. The error of the bilinear table is not bounded by the proof; it is a measurement of the tests.
Proof: Correctness of the transmittance table and the single scattering sumfull
Setting. The planet is a ball of radius with its center at the origin, and the atmosphere is the shell up to radius . The extinction coefficient depends only on and is continuous and nonnegative. A view ray starts at with , in the unit direction with ; the sun is in the unit direction with and . The transmittance of a segment is , and is the transmittance from to the top boundary along a ray that does not hit the ground. The claims are in exact arithmetic, except where a claim names the quadrature.
Claim 1 (the point on the ray). The point has , view cosine and sun cosine (line L5).
Proof. and . The view cosine at is , and the sun cosine is .
Claim 2 (the ground test). For , the ray meets the ground sphere at a positive distance if and only if . The distances to the ground and to the top used in line L2 are and .
Proof. By Claim 1, when , so . For , the product of the roots is negative, so exactly one root is positive, the one with the plus sign. For , the product of the roots is and their sum is . Real positive roots need a nonnegative discriminant, , and a positive sum, ; together these say . The tangent case only touches the sphere, which the code counts as a miss. The first hit is the smaller root, with the minus sign.
Claim 3 (the table coordinates). Let , and the distance to the top. The map is a bijection from the rays that miss the ground, and , onto (for ), and its inverse is , with .
Proof. is an increasing function of from 0 to 1. For fixed , Claim 2 gives , whose derivative in is since . So decreases strictly from its value at to its value at , which is . At the ray is tangent to the ground at distance from and then reaches the top after a further , so . Hence is a strictly monotone map onto . For the inverse, gives , so , and .
So line L1 fills the table at well defined rays, and a lookup returns the bilinear interpolation of the exact table values at the coordinates of the query.
Claim 4 (transmittance from two lookups). Let with , where is the distance of line L2. If the ray misses the ground, . If it hits the ground, . This is line L6.
Proof. The optical depth is an integral over a segment, so it adds over consecutive segments, and multiplies: for on . It depends only on the segment, not on the direction, so . If the ray misses the ground, let be its exit point at the top. The ray from in direction is the rest of the same ray, with by Claim 1, so , and . If the ray hits the ground, the cosine is negative for all (by Claim 2 the hit is before the closest approach to the center, where ), so and , and the reversed rays from and point upward and miss the ground. The reversed ray from in direction passes through and then reaches the top at a point , which is also the exit point of the reversed ray from . So .
Claim 5 (sun visibility). At the point , the sun is blocked by the planet exactly when , and otherwise the light that reaches from the sun is the sun irradiance times . This is line L7.
Proof. The sunlight that reaches travels along the ray from in direction , reversed. By Claim 1 that ray has the coordinates , and by Claim 2 it hits the ground exactly when . If it misses the ground, it leaves the atmosphere at the top, and the light is attenuated by the transmittance of that segment.
Claim 6 (the single scattering sum). Lines L3 to L9 compute the composite trapezoidal rule with intervals for
where is 1 if the sun is visible at and 0 otherwise, with the transmittances replaced by the table lookups of Claims 3 and 4. With exact transmittances the sum converges to as , with error when the integrand is twice continuously differentiable on .
Proof. Line L4 visits the points with weights at the ends and 1 elsewhere, line L8 adds the weighted integrand per channel (zero when line L7 finds the sun blocked), and line L9 multiplies by ; this is the trapezoidal rule. The integrand is bounded, and it is continuous except where jumps, which happens at most at finitely many points of the segment. A bounded function with finitely many discontinuities is Riemann integrable, and the trapezoidal sums converge to its integral. When the integrand is , the standard error bound of the composite trapezoidal rule is . The single scattering integrand itself is the definition: light from the sun, attenuated to , scattered toward with the probability density of each phase function times its scattering coefficient, and attenuated back to .
Claim 7 (the phase functions). , and for every .
Proof. For Rayleigh, . For Cornette-Shanks, with . For , . For , the substitution reduces to . For , set , and , which runs over , so runs over . Then , and the three needed integrals are , and . Expanding ,
where the bracket simplifies with . Multiplying by gives 1.
What is not proved. The bilinear interpolation of the table adds an error that the claims do not bound; the tests measure it against direct quadrature. The coefficients of the toy atmosphere are data, and the page labels them.
Cost. Line L1 computes table entries with quadrature steps each, work once. One view ray costs with three table lookups per step, each, independent of .
Complexity
The model is the real RAM, with table entries and quadrature steps per ray. The transmittance table costs once. One view ray of single scattering costs , with three table lookups per step, independent of . The table needs space, three numbers per entry.
For the full method, let be the number of entries of the 4D table, the number of directions for the scattering density and the number of orders. Each order costs for the density and for the integration along rays, so the precomputation costs . Rendering costs per pixel. With a few dozen entries along each of the four axes, the 4D table has a few hundred thousand to a few million entries; the cost is paid again whenever the atmosphere changes, but not when the sun or the camera moves.
Properties
- Exact symmetry reduction. For a spherically layered atmosphere, two configurations with the same differ by a rotation about the center of the planet, which maps the atmosphere to itself, so the four numbers determine the radiance exactly (a proved property). The tables lose information only through their resolution.
- Linearity. The result is linear in , and single scattering is linear in the scattering coefficients for a fixed transmittance.
- No dependence on the camera path. The tables are the same for every viewpoint, from the ground to space; only a change of the atmosphere needs a new precomputation.
- Only the planet casts shadows. The tables assume that nothing but the planet blocks the sun inside the air, so light shafts behind mountains or clouds need separate methods.
Variants and improvements
- Fewer tables. Hillaire (2020) replaces the 4D table by a sky view table for the current camera, a small 3D table for aerial perspective in the view frustum and a 2D table for multiple scattering, recomputed each frame, which lets artists change the atmosphere at run time.
- Better parameterizations. Bruneton's 2017 reimplementation maps the angles with the distance to the boundary, as in line L1, to put more entries near the horizon and to avoid extrapolation at the ends of the table.
- Ozone. An absorbing layer in the middle atmosphere changes the color of the twilight sky; later implementations add it as one more extinction term.
- Analytic fits. For a camera on the ground only, the Preetham sky model and its successors fit formulas to simulated skies and need no tables.
- Path tracing. Volumetric path tracing of the same atmosphere gives reference images, at a cost far from real time.
When to use it
Use precomputed scattering when the camera can be anywhere from the ground to space, the sun moves, and the atmosphere is the same for long periods, as in flight simulators, planet renderers and open world games. Use an analytic sky model when the camera stays on the ground and only the sky dome is needed. Use per frame methods such as Hillaire's when the atmosphere parameters change often. For clouds, fog banks and other local media, use ray marching of participating media, since the tables assume a layered, clear atmosphere.
Pitfalls
- Units. Kilometers and meters mixed between the radii and the scattering coefficients change every result by orders of magnitude. Line L1 must use the same length unit for both.
- The horizon. Transmittance changes fastest near the horizon. A table that is linear in undersamples it, as the example measured, and gives a dark or bright band at the horizon. Use the distance mapping of line L1.
- Division in line L6. Near the horizon both table values in line L6 are small and their ratio is unstable; the result can exceed 1. Clamp it to 1, and use the reversed form for rays that hit the ground, since the direct form would read the table for rays that are not in it.
- Too few steps in line L4. A horizontal ray crosses about 876 km of air in the toy atmosphere, while the Mie layer has a scale height of 1.2 km. A fixed number of steps that works for upward rays misses most of the haze along the horizon.
- The shadow of the planet. Without the test of line L7, points in the shadow of the planet still scatter sunlight, and the sky stays bright after sunset.
- Phase in the table. Putting the Mie phase function into the 4D table blurs the bright halo around the sun, because the table has a coarse grid in .
- Display. The output is linear radiance with a large range; it needs tone mapping before display.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/precomputed-atmospheric-scattering/. The authors are listed in prov/22XP7T.jsonl.
"""A toy of precomputed atmospheric scattering: a transmittance table and single scattering.
This is a toy, not the full method. It precomputes the transmittance table
T(r, mu) of a spherical planet with an exponential Rayleigh and Mie
atmosphere, and uses it to compute the single scattered light along one view
ray by quadrature. The full method also stores single scattering in a 4D
table over (r, mu, mu_s, nu), adds multiple scattering orders and ground
irradiance, and reads the tables in a shader; this file does none of that.
Units: lengths in km, scattering coefficients in 1/km, the sun irradiance is
1 in each of the three channels (red 680 nm, green 550 nm, blue 440 nm), so
the result is radiance per unit sun irradiance, in 1/sr. The Rayleigh values
and scale heights are those of Bruneton and Neyret (2008); the Mie values and
the planet radii are tuning constants of this toy.
Geometry: r is the distance to the planet center, mu the cosine of the view
zenith angle, mu_s that of the sun zenith angle, nu the cosine of the angle
between the view and the sun. A point at distance s along the view ray has
r_s = sqrt(r^2 + s^2 + 2 r mu s), mu_s' = (r mu + s) / r_s and
mu_s_s = (r mu_s + s nu) / r_s.
"""
import math
Vec3 = tuple[float, float, float]
RG = 6360.0 # ground radius, km (tuning of the toy)
RT = 6420.0 # top of the atmosphere, km (tuning of the toy)
H_R = 8.0 # Rayleigh scale height, km
H_M = 1.2 # Mie scale height, km
BETA_R = (5.8e-3, 13.5e-3, 33.1e-3) # Rayleigh scattering at sea level, 1/km
BETA_M_SCA = 4.0e-3 # Mie scattering at sea level, 1/km (tuning)
BETA_M_EXT = BETA_M_SCA / 0.9 # Mie extinction, 1/km (tuning: albedo 0.9)
G_MIE = 0.8 # Mie asymmetry (tuning)
def phase_rayleigh(nu: float) -> float:
"""Rayleigh phase function, normalized over the sphere: 3 / (16 pi) (1 + nu^2)."""
return 3.0 / (16.0 * math.pi) * (1.0 + nu * nu)
def phase_mie(nu: float, g: float = G_MIE) -> float:
"""Cornette-Shanks phase function, normalized over the sphere."""
k = 3.0 / (8.0 * math.pi) * (1.0 - g * g) / (2.0 + g * g)
return k * (1.0 + nu * nu) / (1.0 + g * g - 2.0 * g * nu) ** 1.5
def extinction(r: float) -> Vec3:
"""Extinction coefficient at radius r, per channel, in 1/km."""
h = max(r - RG, 0.0)
rm = BETA_M_EXT * math.exp(-h / H_M)
rr = math.exp(-h / H_R)
return (BETA_R[0] * rr + rm, BETA_R[1] * rr + rm, BETA_R[2] * rr + rm)
def mu_horizon(r: float) -> float:
"""The cosine of the view zenith angle of the horizon seen from radius r."""
return -math.sqrt(max(0.0, 1.0 - (RG / r) ** 2))
def hits_ground(r: float, mu: float) -> bool:
return mu < mu_horizon(r)
def dist_to_top(r: float, mu: float) -> float:
return max(0.0, -r * mu + math.sqrt(max(0.0, r * r * (mu * mu - 1.0) + RT * RT)))
def dist_to_ground(r: float, mu: float) -> float:
return max(0.0, -r * mu - math.sqrt(max(0.0, r * r * (mu * mu - 1.0) + RG * RG)))
def point_on_ray(r: float, mu: float, s: float) -> tuple[float, float]:
"""Radius and view zenith cosine at distance s along the ray (r, mu)."""
rs = math.sqrt(max(r * r + s * s + 2.0 * r * mu * s, RG * RG))
return rs, max(-1.0, min(1.0, (r * mu + s) / rs))
def optical_depth(r: float, mu: float, d: float, q: int = 200) -> Vec3:
"""Integral of the extinction over the first d km of the ray, trapezoidal rule with q steps."""
if d <= 0.0:
return (0.0, 0.0, 0.0)
ds = d / q
acc = [0.0, 0.0, 0.0]
for k in range(q + 1):
w = 0.5 if k in (0, q) else 1.0
e = extinction(point_on_ray(r, mu, k * ds)[0])
for c in range(3):
acc[c] += w * e[c]
return (acc[0] * ds, acc[1] * ds, acc[2] * ds)
def transmittance_to_top(r: float, mu: float, q: int = 200) -> Vec3:
"""Direct quadrature of the transmittance from (r, mu) to the top, for a ray that misses the ground."""
tau = optical_depth(r, mu, dist_to_top(r, mu), q)
return (math.exp(-tau[0]), math.exp(-tau[1]), math.exp(-tau[2]))
H_TOP = math.sqrt(RT * RT - RG * RG) # distance from the ground to the top along the horizon
def table_coords(r: float, mu: float) -> tuple[float, float]:
"""The unit coordinates (x_r, x_mu) of a ray (r, mu) that misses the ground.
x_r = rho / H with rho = sqrt(r^2 - RG^2), and x_mu places the distance d
to the top between its least value RT - r (straight up) and its largest
value rho + H (along the horizon). This is the mapping of Bruneton's 2017
code; it puts more entries near the horizon, where T changes fast.
"""
rho = math.sqrt(max(0.0, r * r - RG * RG))
d = dist_to_top(r, mu)
d_min, d_max = RT - r, rho + H_TOP
x_mu = (d - d_min) / (d_max - d_min) if d_max > d_min else 0.0
return rho / H_TOP, min(max(x_mu, 0.0), 1.0)
def ray_of_coords(x_r: float, x_mu: float) -> tuple[float, float]:
"""The inverse of table_coords."""
rho = H_TOP * x_r
r = math.sqrt(rho * rho + RG * RG)
d_min, d_max = RT - r, rho + H_TOP
d = d_min + x_mu * (d_max - d_min)
mu = 1.0 if d == 0.0 else (H_TOP * H_TOP - rho * rho - d * d) / (2.0 * r * d)
return r, max(-1.0, min(1.0, mu))
class TransmittanceTable:
"""T(r, mu) to the top of the atmosphere on a regular grid in (x_r, x_mu)."""
def __init__(self, nr: int = 32, nu: int = 64, q: int = 200) -> None:
if nr < 2 or nu < 2:
raise ValueError("the table needs at least 2 entries per axis")
self.nr, self.nu = nr, nu
self.data = []
for i in range(nr):
row = []
for j in range(nu):
r, mu = ray_of_coords(i / (nr - 1), j / (nu - 1))
row.append(transmittance_to_top(r, mu, q)) # @line L1
self.data.append(row)
def lookup(self, r: float, mu: float) -> Vec3:
"""Bilinear lookup of T(r, mu) for a ray that does not hit the ground."""
r = min(max(r, RG), RT)
x_r, x_mu = table_coords(r, mu)
x = x_r * (self.nr - 1)
y = x_mu * (self.nu - 1)
i, j = min(int(x), self.nr - 2), min(int(y), self.nu - 2)
fx, fy = x - i, y - j
d = self.data
return tuple(
(1 - fx) * ((1 - fy) * d[i][j][c] + fy * d[i][j + 1][c])
+ fx * ((1 - fy) * d[i + 1][j][c] + fy * d[i + 1][j + 1][c])
for c in range(3))
def between(self, r: float, mu: float, s: float, ground: bool) -> Vec3:
"""Transmittance from (r, mu) to the point at distance s, from two table lookups."""
rs, mus = point_on_ray(r, mu, s)
if ground:
num, den = self.lookup(rs, -mus), self.lookup(r, -mu)
else:
num, den = self.lookup(r, mu), self.lookup(rs, mus)
return tuple(min(1.0, num[c] / den[c]) for c in range(3))
def single_scattering(table: TransmittanceTable, r: float, mu: float, mu_s: float,
nu: float, q: int = 100, g: float = G_MIE) -> Vec3:
"""Single scattered radiance along the view ray (r, mu) for the sun at (mu_s, nu)."""
ground = hits_ground(r, mu)
d = dist_to_ground(r, mu) if ground else dist_to_top(r, mu) # @line L2
pr, pm = phase_rayleigh(nu), phase_mie(nu, g)
acc = [0.0, 0.0, 0.0] # @line L3
for k in range(q + 1): # @line L4
s = k * d / q
w = 0.5 if k in (0, q) else 1.0
ry, _ = point_on_ray(r, mu, s) # @line L5
mu_sy = max(-1.0, min(1.0, (r * mu_s + s * nu) / ry))
t_view = table.between(r, mu, s, ground) # @line L6
if hits_ground(ry, mu_sy): # @line L7
continue
t_sun = table.lookup(ry, mu_sy)
h = ry - RG
br, bm = math.exp(-h / H_R), BETA_M_SCA * math.exp(-h / H_M)
for c in range(3):
acc[c] += w * t_view[c] * t_sun[c] * (BETA_R[c] * br * pr + bm * pm) # @line L8
ds = d / q
return (acc[0] * ds, acc[1] * ds, acc[2] * ds) # @line L9
def single_scattering_direct(r: float, mu: float, mu_s: float, nu: float,
q: int = 100, q_inner: int = 200, g: float = G_MIE) -> Vec3:
"""The same integral with every transmittance by direct quadrature, for the tests."""
ground = hits_ground(r, mu)
d = dist_to_ground(r, mu) if ground else dist_to_top(r, mu)
pr, pm = phase_rayleigh(nu), phase_mie(nu, g)
acc = [0.0, 0.0, 0.0]
for k in range(q + 1):
s = k * d / q
w = 0.5 if k in (0, q) else 1.0
ry, _ = point_on_ray(r, mu, s)
mu_sy = max(-1.0, min(1.0, (r * mu_s + s * nu) / ry))
if hits_ground(ry, mu_sy):
continue
tau = optical_depth(r, mu, s, q_inner)
t_sun = transmittance_to_top(ry, mu_sy, q_inner)
h = ry - RG
br, bm = math.exp(-h / H_R), BETA_M_SCA * math.exp(-h / H_M)
for c in range(3):
acc[c] += w * math.exp(-tau[c]) * t_sun[c] * (BETA_R[c] * br * pr + bm * pm)
ds = d / q
return (acc[0] * ds, acc[1] * ds, acc[2] * ds)
test_precomputed_atmospheric_scattering.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/precomputed-atmospheric-scattering/. The authors are listed in prov/22XP7T.jsonl.
"""Tests of the toy: the transmittance table and single scattering against direct quadrature.
The table coordinates invert, the table matches a direct quadrature of the
optical depth, optical depth adds along a ray, the transmittance between two
points from two table lookups matches the direct value, the phase functions
integrate to 1 over the sphere, and single scattering from the table matches
the same integral with every transmittance computed directly. The color
checks at the end are measurements of the toy, not proved properties.
"""
import math
import random
import pytest
from precomputed_atmospheric_scattering import (
BETA_R, RG, RT, TransmittanceTable, dist_to_ground, dist_to_top,
mu_horizon, optical_depth, phase_mie, phase_rayleigh, point_on_ray, ray_of_coords,
single_scattering, single_scattering_direct, table_coords, transmittance_to_top)
TABLE = TransmittanceTable(32, 64, 200)
def rand_ray(rng: random.Random, ground: bool = False) -> tuple[float, float]:
r = RG + rng.uniform(0.0, RT - RG)
mh = mu_horizon(r)
mu = rng.uniform(-1.0, mh) if ground else rng.uniform(mh, 1.0)
return r, mu
def test_table_coordinates_invert() -> None:
rng = random.Random(1)
for _ in range(500):
x, y = rng.random(), rng.random()
r, mu = ray_of_coords(x, y)
assert RG - 1e-9 <= r <= RT + 1e-9 and mu >= mu_horizon(r) - 1e-9
x2, y2 = table_coords(r, mu)
assert abs(x - x2) < 1e-9 and abs(y - y2) < 1e-9
# The corners: the ground looking up, the ground along the horizon, the top looking up.
assert table_coords(RG, 1.0) == (0.0, 0.0)
assert abs(table_coords(RG, 0.0)[1] - 1.0) < 1e-12
assert abs(table_coords(RT, 1.0)[0] - 1.0) < 1e-12
def test_table_matches_direct_quadrature() -> None:
rng = random.Random(2)
for _ in range(300):
r, mu = rand_ray(rng)
a, b = TABLE.lookup(r, mu), transmittance_to_top(r, mu)
assert all(abs(x - y) < 3e-3 for x, y in zip(a, b))
assert all(0.0 < y <= 1.0 for y in b)
def test_transmittance_basics() -> None:
assert transmittance_to_top(RT, 1.0) == (1.0, 1.0, 1.0)
zen, hor = transmittance_to_top(RG, 1.0), transmittance_to_top(RG, 0.0)
for c in range(3):
assert hor[c] < zen[c] < 1.0
# Blue light is scattered out more than red light.
assert zen[2] < zen[1] < zen[0] and hor[2] < hor[1] < hor[0]
def test_optical_depth_adds_along_the_ray() -> None:
rng = random.Random(3)
for _ in range(20):
r, mu = rand_ray(rng)
d = dist_to_top(r, mu)
s1 = rng.uniform(0.0, d)
r1, mu1 = point_on_ray(r, mu, s1)
whole = optical_depth(r, mu, d, 4000)
parts = [a + b for a, b in zip(optical_depth(r, mu, s1, 4000), optical_depth(r1, mu1, d - s1, 4000))]
assert all(abs(x - y) < 1e-5 * x for x, y in zip(whole, parts))
def test_transmittance_between_two_points() -> None:
rng = random.Random(4)
for ground in (False, True):
for _ in range(100):
r, mu = rand_ray(rng, ground)
d = dist_to_ground(r, mu) if ground else dist_to_top(r, mu)
s = rng.uniform(0.0, d)
tau = optical_depth(r, mu, s, 400)
want = [math.exp(-t) for t in tau]
got = TABLE.between(r, mu, s, ground)
assert all(abs(x - y) < 1e-2 for x, y in zip(got, want))
def test_phase_functions_are_normalized() -> None:
def sphere_integral(f, m=20000):
h = 2.0 / m
acc = f(-1.0) + f(1.0)
for k in range(1, m):
acc += (4 if k % 2 else 2) * f(-1.0 + k * h)
return 2.0 * math.pi * acc * h / 3.0
assert abs(sphere_integral(phase_rayleigh) - 1.0) < 1e-9
for g in (0.0, 0.5, 0.8):
assert abs(sphere_integral(lambda nu: phase_mie(nu, g)) - 1.0) < 1e-6
# With g = 0 the Cornette-Shanks function is the Rayleigh function.
assert abs(phase_mie(0.3, 0.0) - phase_rayleigh(0.3)) < 1e-15
assert phase_mie(1.0) > 50 * phase_mie(-1.0)
def test_single_scattering_matches_direct_transmittance() -> None:
rays = [(RG + 0.001, 1.0, 1.0, 1.0), (RG + 0.001, 1.0, 0.5, 0.5),
(RG + 0.001, 0.2, 0.05, 0.9), (RG + 10.0, -0.5, 0.7, 0.0),
(RG + 30.0, 0.4, 0.3, -0.6)]
for r, mu, mu_s, nu in rays:
a = single_scattering(TABLE, r, mu, mu_s, nu)
b = single_scattering_direct(r, mu, mu_s, nu)
assert all(abs(x - y) < 1e-2 * y for x, y in zip(a, b))
def test_no_light_when_the_sun_is_far_below_the_horizon() -> None:
assert single_scattering(TABLE, RG, 1.0, -0.5, -0.5) == (0.0, 0.0, 0.0)
def test_colors_of_the_toy_sky() -> None:
# Measurements of the toy. Rayleigh data follow lambda^-4 within 1 percent.
assert abs(BETA_R[2] / BETA_R[0] / (680.0 / 440.0) ** 4 - 1.0) < 1e-2
# The zenith with the sun at 60 degrees from it is blue.
s = single_scattering(TABLE, RG, 1.0, 0.5, 0.5)
assert s[2] > s[1] > s[0] > 0.0
# Looking near the sun as it sets, red and green win over blue.
s = single_scattering(TABLE, RG, 0.2, 0.05, 0.9)
assert s[0] > s[2] and s[1] > s[2]
def test_bad_table() -> None:
with pytest.raises(ValueError):
TransmittanceTable(1, 8)
History
Nishita, Sirai, Tadamura and Nakamae (1993) computed single scattering of sunlight in a spherical atmosphere with exponential density, to display the Earth from space. Preetham, Shirley and Smits (1999) fitted an analytic model to simulated skies seen from the ground. Bruneton and Neyret (2008) reduced the radiance of a layered atmosphere to four parameters, precomputed single and multiple scattering into tables, and rendered sky and aerial perspective from any altitude on the GPU. Bruneton published a documented reimplementation in 2017. Hillaire (2020) moved most of the work back to each frame with smaller tables, so that the atmosphere can change while the program runs.
References
- Eric Bruneton and Fabrice Neyret, Precomputed atmospheric scattering, Computer Graphics Forum 27(4), 2008, 1079 to 1086 (Eurographics Symposium on Rendering), the atmosphere model (Rayleigh and Mie scattering coefficients, scale heights, phase functions), the parameterization of the 2D and 4D tables, and the precomputation of multiple scattering orders
- Eric Bruneton, Precomputed Atmospheric Scattering, a new implementation (2017), documented source code, the file atmosphere/functions.glsl, with the transmittance computation, the mapping from (r, mu) to texture coordinates, the phase functions and the transmittance between two points from two lookups
- Tomoyuki Nishita, Takao Sirai, Katsumi Tadamura and Eihachiro Nakamae, Display of the earth taking into account atmospheric scattering, SIGGRAPH 93, 175 to 182, the single scattering model of sunlight in a spherical atmosphere with exponential density (general locator)
- Sébastien Hillaire, A Scalable and Production Ready Sky and Atmosphere Rendering Technique, Computer Graphics Forum 39(4), 2020, 13 to 22, the smaller lookup tables and the approximation of multiple scattering that replace the 4D table (general locator)
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 22XP7T Edit this page History Report an error Markdown