Lighting in Taos Explorer has to work for a pilot taxiing past a hangar at 9 p.m., for the same pilot at 35,000 feet at noon, and for the astronaut looking back at the Earth from the Moon. The ground under them is mostly photographs: Google Photorealistic 3D Tiles and aerial imagery that already contain sunlight, shadows and sky color from the day they were flown. So the lighting system has two jobs. It shades real PBR surfaces (aircraft, cars, boats, the station) the way a modern deferred renderer does. It also has to take the old daylight out of the photographs, put the hour's own light in, and switch on the cities when the sun sets. This page goes through the shading pass and its BRDF, the two suns behind the day/night cycle, the sky probe that supplies ambient light and reflections, ambient occlusion, how the photographs are relit, local and night lights, and the water.
The lighting pass
src/renderer/features/deferred_lighting_feature.ts · src/renderer/render_graph/passes/deferred_lighting_pass.ts · src/shaders/deferred_lighting.wgsl · src/shaders/modules/light_uniforms.wgsl · explorer/main.ts
Everything opaque in Explorer, from the photogrammetry tiles to the airframe, is drawn into a
G-buffer first (01 · Anatomy of a frame covers the targets and why the
depth precision works at planet scale). Lighting is then one fullscreen triangle,
DeferredLightingPass, that reads the G-buffer, the shadow maps, the cloud-shadow lookup,
the AO target, the sky probe and the aerial-perspective volume, and writes HDR radiance into an
rgba16float target. Sky pixels are discarded at the top of the fragment shader (the
atmosphere pass already drew them). Everything else that adds light (local lights, water, city
lights, glowing points) runs after it as more passes over the same HDR target.
Decoding the G-buffer
The fragment shader reads each target with textureLoad at the pixel's integer coordinate
(no filtering, no derivatives), and reconstructs world position from depth through the inverse
view-projection. The world-space normal is stored as N·0.5+0.5 in a half-float target, so
it decodes with one multiply-add and a normalize. The table lists what lighting uses.
| Target | Channels | Read by lighting as |
|---|---|---|
| albedo · roughness | rgba8unorm | base color; perceptual roughness, floored at max(minRoughness 0.045, 0.04) |
| normal · metallic | rgba16float | N = normalize(rgb·2−1); metallic in .a |
| emissive | rgba16float | emitted radiance added last; .a = 8-bit light-exclusion mask |
| material data | rgba8unorm | .r shading model (1 = unlit), .g specular (F0 = 0.08·specular), .b baked AO, .a material id (×255 → MaterialParams storage buffer) |
| material data 2 | rgba8unorm | per-pixel multipliers on clearcoat, coat roughness, sheen roughness, iridescence |
| material data 3 | rgba16float | world anisotropy tangent (.xyz) and strength (.a) |
| depth | depth32float | world position; a geometric normal for horizon occlusion |
The photogrammetry tiles and the extruded OSM buildings set slimGBuffer: their pipeline
writes with a zero write mask to the emissive and extension targets. Those targets are cleared to
identity values ((1,1,1,1) for the multipliers, (0,0,0,0) for anisotropy), so the lighting shader
needs no branch to tell a slim pixel from a full one. The material id indexes a small storage buffer
of glTF extension parameters (clearcoat, sheen, iridescence, diffuse transmission, subsurface),
which keeps those values out of the G-buffer entirely.
Variants
The pass is compiled from #defines into a few variants rather than one shader full of
runtime branches: HAS_AO (whether an AO target is bound), SHADOW_FILTER_VSM
(the EVSM2 moment map in place of the depth map plus comparison sampler, the same slot count so the
stage stays under its sampled-texture limit) and IBL_DIFFUSE_SH (order-3 spherical
harmonics in place of the irradiance cube). Explorer runs the PCSS variant with AO on (EVSM2 is the
vsm setting, off by default), and does not enable SH: its diffuse sky light comes from the
probe's 32² irradiance cube. One uniform block, LightUniforms, is shared by every pass that
needs the sun. It lives in its own module so that every pass shares one layout. A private copy
drifts when the struct grows: if the cascade array (8 matrices) grew in one copy and not another,
every later field in the stale copy would shift, and a godray or fog shader would read
shadowsEnabled == 0 out of matrix data and go fully lit.
How the terms add up
The end of the fragment shader is the whole lighting model in a few lines. The sun's direct term is scaled by everything that blocks the sun (shadow map, contact shadows, cloud-shadow LUT, stained glass, water caustics). The ambient term is scaled only by what blocks the sky (AO and baked occlusion). Then aerial perspective is applied over the sum:
let direct = (diffuse_brdf + specular_brdf) * light.color * light.intensity * NdotL * shad * horizon_fade;
// …
let ambient = (diffuse_ibl * ao_diffuse * (1.0 - rt_w)
+ specular_ibl * spec_ao * ibl_spec_w)
* horizon_fade * light.iblIntensity * mat_occlusion
+ ambient_floor(albedo, metallic);
// … clearcoat, sheen, diffuse transmission and subsurface lobes …
// Cloud shadow works the same way: the cloud deck occludes the sun disc, so
// its transmittance scales every direct lobe while sky ambient stays put.
lit_direct = lit_direct * sun_cookie(world_pos) * cloud_t * sun_tint * sun_water_caustics(world_pos);
let color = lit_direct + lit_ambient + ssgi_contrib + spec_gi_contrib + emissive_in;
let haze = apply_aerial_perspective(color, world_pos, light.sunDirection, in.uv);
A few of these inputs are bound but inert in Explorer: no SSGI or voxel GI feature is registered,
so their slots hold 1×1 black defaults, and the cookie is off. The global IBL cube is the engine's
1×1 black default too. All of Explorer's sky light comes through the reflection-probe path, and the
0.01·albedo ambient_floor keeps a surface from being exactly black when that path
returns nothing. Aerial perspective is on by default (effects.aerialFog); its froxel
volume, sky-view convergence and curved-horizon mode are the subject of
04 · Atmosphere. The shadow factor, including the far
screen-space march, the terrain shadows merged into the cloud LUT and the overcast penumbra widening
(1 + 4·(1 − cloud_t)), belongs to 03 · Shadows.
The BRDF
src/shaders/modules/pbr_brdf.wgsl · src/shaders/deferred_lighting.wgsl · src/shaders/point_spot_lighting.wgsl
Every lit path in the engine (deferred, forward, forward+, point/spot) imports one module,
pbr_brdf.wgsl, so a material looks the same whichever path draws it. The model is
Cook–Torrance microfacet specular over a Lambert diffuse:
- DGGX / Trowbridge–Reitz normal distribution on the perceptual-roughness-squared α
- Vheight-correlated Smith visibility in its common approximate form, with the 1/(4 n·l n·v) denominator folded in, so the product is D·V·F
- F₀mix(0.08 · specular · specularColor, albedo, metallic): 0.04 for the default specular 0.5
- Ecomp1 + F₀ (1/Ess − 1), Ess = DFG.x + DFG.y from the split-sum LUT
The energy-compensation term restores the energy a single-scattering GGX lobe loses on rough surfaces (light that bounces more than once between microfacets). It is negligible for dielectrics at F₀ ≈ 0.04 and large for rough metals. It is sampled once per pixel from the 64² DFG LUT and applied to both the direct and the image-based specular, so a rough metal under the sun and the same metal in the shade lose the same amount of energy, which in practice means none.
A sun with a radius
A GGX lobe with α near zero under a point light is a spike one pixel wide that aliases into sparkle. Explorer has plenty of near-mirrors: clear-coated paint (coat roughness 0.012 as authored), chrome, wet runways and puddles. The lighting pass therefore treats the sun as a disk. It aims the specular half-vector at the point on the disk closest to the reflection ray, the representative-point method, and widens the lobe with an energy normalization so the highlight's total does not grow:
// Sun disk for the direct specular lobe — matches the sky's drawn sun
// (atmosphere_model.wgsl SUN_COS_THRESH, ~1.6° angular radius).
const SUN_DISK_COS: f32 = 0.9996;
const SUN_DISK_SIN: f32 = 0.028282;
// …
let R = reflect(-V, N);
let LdotR = dot(L, R);
let perp = R - LdotR * L;
var L_s = R;
if (LdotR < SUN_DISK_COS) {
L_s = select(L, normalize(L * SUN_DISK_COS + normalize(perp) * SUN_DISK_SIN), dot(perp, perp) > 1e-8);
}
let a = roughness * roughness;
let a_s = min(a + 0.5 * SUN_DISK_SIN, 1.0);
let norm = (a / a_s) * (a / a_s);
D = distribution_ggx(spec_NdotH, roughness) * norm;
The radius is about 1.6°, roughly six times the real sun's, because it matches the disk the sky
shader draws, and a puddle should reflect the sun the player can see. Diffuse still uses the disk
center L. The anisotropic path (KHR_materials_anisotropy) keeps the plain
point-light lobe.
Specular IBL and the grazing streak
The image-based specular follows the split-sum approximation: a prefiltered cube sampled at
mip = roughness·(5 − 1), times F·DFG.x + DFG.y, times energy compensation. A prefiltered
cube is built for a view looking straight down the normal, though, and a real GGX lobe seen at a
grazing angle is long in the plane of incidence and narrow across it. That stretched lobe is why a
wet runway shows long vertical streaks of the lights and sky beyond it. env_specular_lobe
approximates it with five taps fanned along the reflection's elevation, using a sharper mip for the
narrow width across:
env_specular_lobe. "Up" is the normal's component perpendicular to R, so the taps spread in the plane of incidence. Head-on and on rough surfaces (whose lobes the coarse mips already blur) it collapses to a single tap.It serves wet runways, and it also keeps a glossy floor steady at a grazing angle, where a single
reflection sample would snap between sky and below-horizon ground as the eye moved.
The clear-coat lobe uses the same function at its own roughness. Two more occlusion terms keep
reflections from leaking. Lagarde's specular occlusion widens the AO cone with roughness, so a
mirror is barely occluded by a crevice while rough specular is occluded almost like diffuse.
Horizon occlusion fades the reflection where the normal-mapped R dips below the true
surface: h = clamp(1 + 1.3·(R·Ng), 0, 1)². Because the G-buffer holds only the
perturbed normal, Ng is rebuilt from two neighboring depth taps. Screen-space
derivatives are not allowed there (the code runs after the sky discard, in non-uniform
control flow), and the reconstruction is skipped where a neighbor is on the far plane, so a
silhouette cannot produce a false normal.
The aircraft finishes author clear-coat
roughness as low as 0.012, but the deferred coat lobe clamps to 0.04 and the base lobe to the
0.045 minRoughness floor. The clamps are deliberate (they keep specular aliasing in
check), and the sun-disk normalization above is what keeps those floored lobes from turning into
one-pixel sparkle. In practice the visible sharpness of a mirror coat comes from the reflected sky,
not from the authored number.
Two suns
explorer/main.ts (applySun, moonLightNow, frame loop key-light block) · explorer/lib/sim/sim_clock.ts · src/geo/live/moon.ts
Deferred lighting, shadows and godrays read exactly one directional light: the first enabled
DirectionalLight in the scene. Explorer has two directional lights and adds only one of
them to the scene.
realSunholds the true sun for the current UTC instant. Its game object is deliberately never added to the scene. It is a holder for a direction, color and intensity, and it drives the sky dome, the aerial haze (aerialSunDirection), the sky probe, the sea-level water, the city lights' terminator, the scene grade and auto exposure.sunis the scene's key light: what lights surfaces and casts shadows. It is the sun by day and moonlight by night, and in space it becomes the unfiltered sun again.
realSun; anything that must cast light on surfaces reads the key light.The real sun
The sun is not a time-of-day dial laid over the local frame.
applySun takes the sun's Earth-fixed direction for the clock's UTC instant
(sunEcefDir) and rotates it into the floating world frame, whose +Y is local up. The
clock starts at the place's local timeOfDay (default 09:00) on today's date, runs at
timeScale (default 1, real time), and can be pinned with ?time= and
?date=. Pinning makes side-by-side comparisons of anything sun-dependent reproducible.
The sun's elevation sine sets a day factor, and the day factor sets intensity and a warming color:
- ethe real sun's elevation; full strength from about 14.5° up (sin e = 0.25)
- look.sunthe Studio look's sun multiplier, 1.15 in the shipped look.json
The sun's color is an analytic ramp from white-yellow to orange. It is not looked up from the atmosphere's transmittance LUT, although that LUT exists in the frame (the HQ clouds use it to redden their own sun term, see 05 · Clouds). The ramp is cheap and tunable, it reaches its warmest exactly when the key light is already near zero, and the scene grade adds most of the visible warmth at a low sun.
The key light: sun, then Moon
While the sun is above the horizon (toSun.y > 0) the key light copies the real
sun's direction and color, with its intensity also multiplied by cloudSunFactor. When
the sun sets, the key light is re-aimed at the Moon, wherever the ephemeris puts it, and given a cool
color and a small intensity scaled by the Moon's height and phase:
const MOON_COLOR = new Vec3(0.55, 0.66, 0.95);
const MOON_INTENSITY = 0.4;
// …
function moonLightNow(): { dir: Vec3d; level: number } {
const sunE = sunEcefDir(clock.utcMs, sunEcefScratchDir);
const moonE = moonEcef(clock.utcMs).dir;
const lit = moonIlluminated(sunE, moonE); // (1 − cos elongation) / 2
// … the direction: the camera's view of the placed Moon, else the ephemeris …
const elevation = -dir.y;
return { dir, level: Math.max(0, Math.min(1, elevation / 0.15)) * Math.pow(lit, 2.5) };
}
// Night: key light = moonlight from where the Moon really is …
sun.color = MOON_COLOR;
sun.intensity = MOON_INTENSITY * ml.level * cloudSunFactor;
The illuminated fraction is raised to the 2.5 power because the Moon's brightness falls much faster than its lit area. The code comment's target is "a quarter moon is about a tenth of a full one"; 0.52.5 ≈ 0.18 gives somewhat more than that. Moonlight rises over its first ~8.6° of elevation (sin = 0.15), so a setting Moon fades rather than switching off. The ratio of full sun to full moon here is 5.75 : 0.4, about 14 : 1, where the real ratio is in the hundreds of thousands. The scale is compressed on purpose. A night has to stay readable on a screen, and auto exposure, whose maximum is eased from 4.0 by day to 0.5 at night, plus the night grade decide how dark it looks, not the raw ratio.
The hand-over happens at the horizon, where the real sun's contribution is already zero (day = 0
at sin e = 0), so swapping direction from the sun to the Moon does not pop the lit side of the
scene. Cloud dimming is applied one frame late on purpose. applySun rewrites the
light's direction, and the frame loop re-aims the light afterwards (at the orbiting Moon by night, at
the real sun in space). Calling it in place would leave one frame lit from the wrong side, which at
night shows as the landscape flashing.
Overcast, horizon fade and space
- cloudSunFactor1 − 0.75 · smoothstep(0.55, 1.15, coverage) · below-cloud, eased at 1.5/s. Dims only the key light (down to a quarter under solid overcast); the sky probe and the clouds' own lighting are untouched. Auto exposure is pulled down up to −0.9 EV with it, "an overcast day is darker to look at, not only flatter."
- disableHorizonFadetrue. The engine default fades the direct and ambient terms by smoothstep(−0.05, 0.05, L.y) of the key light. At night that gate would follow the Moon: with the Moon set it would switch off all sky light, the airglow floor included, and the land would go pitch black. Both lights already fall to zero at their own horizons, so Explorer turns the gate off.
- space sunabove 100 km (back below 80 km, hysteresis), or at the Moon or Mars, the key light becomes the real sun at full strength regardless of local time: (1, 0.98, 0.95) × 1.6 at the Moon, (1, 0.93, 0.84) × 0.78 at Mars. Without it the Moon seen from orbit would be a barely lit ball whenever it is night under the camera.
- lunar eclipseat the Moon, if it lies within ~1.6 Earth radii of the anti-solar axis, the key light drops by up to 92% and turns copper red (0.8, 0.32, 0.12).
applySun, moonLightNow, buildProbeLighting, the water's sky brightness, the city lights' terminator (for flat ground under the camera) and sceneGrade, plotted against the sine of the real sun's elevation and normalized to 0..1. The vertical line is the slider. Cloud cover is taken as clear.Sky light from a probe that bakes on demand
src/renderer/features/reflection_probe_feature.ts · src/shaders/reflection_probe_capture.wgsl · src/shaders/reflection_probe_ibl.wgsl · explorer/main.ts (buildProbeLighting, probeGroundSource, probeCloudState)
Ambient light and reflections come from a single reflection probe in 'sky-and-clouds'
capture mode. Its box is 1,000 km on a side (extentHalfSize = 1e6) with zero falloff,
so its weight is 1 everywhere the camera goes and it fully replaces the global (black) IBL. Box
projection is off, so the sky reads as infinitely far. The probe does not capture the scene. It
paints a procedural environment from parameters the host hands it, and then convolves that
environment into irradiance and prefiltered radiance:
| Stage | Size · format | Notes |
|---|---|---|
| capture cube | 512² (phone 256²) · rgba16float × 6 | fullscreen triangle per face, fs_sky |
| irradiance cube | 32² · rgba16float | cosine-weighted, 256 samples per texel |
| prefiltered cube | 256² (phone 128²) · rgba16float · 5 mips | GGX importance sampling, 256 samples, firefly clamp at luminance 10 |
| DFG LUT | 64² · rg | shared, device-cached |
The desktop sizes are twice the phone sizes because clear-coated paint is close to a mirror, and a 128-texel prefiltered sky visibly smears its reflection. The convolution reads mip 0 of the capture directly, without filtered importance sampling, since the capture has no mip chain. It rotates each texel's sample pattern by a per-texel random azimuth (Cranley–Patterson). A fixed pattern near the cube's ±Y poles would sweep bright features across neighboring texels, and calm water would mirror that as rays converging under the camera.
What the probe paints
sky_color is a three-stop gradient (ground, horizon, zenith) plus a sun disk and halo,
with three optional layers on top:
- Real ground below the horizon. The camera is placed on a sphere of the Earth's local radius. A downward direction is ray-traced against that sphere and samples the whole-globe day imagery (Blue Marble class, 5120 px wide on desktop), hazed toward the horizon color over 25 km + 4 × altitude. Glossy paint and glass then reflect the land and water below, with the horizon where it really is at altitude. The imagery is scaled by a gain normalized to an average land albedo of 0.15.
- The real cloud deck. The HQ clouds' ground-shadow map, a 1024²
r8unormtop-down transmittance over 60 km, is copied each frame intoProbeCloudLut. For a capture direction, the shader intersects the deck height, follows the sun ray from that point down to the ground, and reads the transmittance there: the cloud at a point on the deck is whatever the sun ray through it crossed. Cover is drawn over the sky and lit with the sun color; tops seen from above are brighter (×1.15) than bases seen from below (×0.75). - Stylized clouds, a cheap sine-fbm layer used only when no real deck is supplied, scaled by the cover setting.
When it re-bakes
A full bake (six face captures plus the convolutions) would be the single biggest fixed GPU cost
in the app if it ran every frame, so the probe is
updateMode = 'on-demand'. The capture depends only on the sun, the clouds and where the
camera is on the globe, not on where it looks, so camera motion alone never triggers a bake.
- sun moved1.5° of travel since the last bake while the clock runs, about six minutes of a real day. In real time that is one bake every few minutes; in a fast time-lapse, a couple a second instead of one every frame. Slider drags, arrival at a place and intensity changes force a bake at once.
- cloud covera change of more than 0.05 in the on-screen cover.
- camera travel3 km of travel, or a change in altitude by a factor of e^0.3 (≈1.35), or the day imagery arriving.
Stepping the ambient light in 1.5° increments is invisible because the probe holds only low-frequency sky light. The sharp sun highlight is the analytic disk from the previous section, not the probe's painted sun.
Night: the airglow floor
The probe's palette is the same day/night function as everything else, with one addition. On a
moonless night the key light is near zero, and the only thing lighting the ground is this probe's
irradiance. buildProbeLighting therefore scales the palette by a level that never falls
below 0.2, and adds a cool night term that fades in as the day fades out:
const day = Math.max(0, Math.min(1, -d.y / 0.25)); // 1 sun up, 0 at/below horizon
const lvl = 0.20 + 0.80 * day; // sky brightness floor at night
const night = 1 - day;
const g = (r, gg, b, nr, ng, nb) =>
({ x: r * lvl + nr * night, y: gg * lvl + ng * night, z: b * lvl + nb * night });
return {
sunDir: { x: d.x, y: d.y, z: d.z }, sunIntensity: realSun.intensity, /* … */
skyTop: g(0.25, 0.45, 0.95, 0.10, 0.14, 0.26),
skyHorizon: g(0.95, 1.05, 1.20, 0.14, 0.17, 0.26),
groundColor: g(0.22, 0.20, 0.17, 0.05, 0.05, 0.06),
ground: probeGroundSource ? probeGroundSource() : null,
clouds: probeCloudState, /* … */
};
The comment in the source puts it plainly. The deferred pass's diffuse ambient is the convolution
of this procedural sky, not of the visible atmosphere, so a night floor has to be added here or the
ground reads pitch black once the Moon is down. It lifts only ambient light and reflections. The
visible night sky comes from the atmosphere pass. Finally, iblIntensity scales the
whole probe contribution. Explorer sets it from the Studio look's sky value, 0.5 in the
shipped look. Sky light at twice that strength gives a flat, washed-out image (sunlit to shaded
asphalt only 2.2 : 1), and it is the term that matters: bloom, flare, godrays and haze each change
the image by under 2% in A/B tests.
Ambient occlusion
src/renderer/features/ao_feature.ts · src/renderer/render_graph/passes/gtao_pass.ts · src/shaders/gtao.wgsl · src/shaders/ssao_blur.wgsl · src/shaders/modules/pbr_brdf.wgsl
The probe's light reaches every pixel unoccluded, so without AO the narrow streets of a scanned
city light up as if they were open plazas. AOFeature offers SSAO, GTAO, HBAO+ and CORTAO
behind one interface. Explorer creates it with method: 'gtao', radius: 2.0, bias: 0.01,
strength: 0.8, on by default.
GTAO (Jimenez et al. 2016) runs at half resolution, reading the full-resolution normal and depth
at 2 × half_coord. For each of 2 slices around the view vector, with a 4×4 noise texture
jittering the slice angle and step offset, it marches 4 steps each way in screen space, tracks the
highest horizon on each side, clamps the horizons to the hemisphere of the normal projected into the
slice, and integrates the cosine-weighted visibility analytically:
- h±horizon angles from the view vector, clamped to [n − π/2, n + π/2]
- nthe projected normal's signed angle in the slice
- thicknesssamples farther than radius·(1 + 10·bias) = 2.2 m are ignored, so a far wall doesn't lower a horizon
With Explorer's 60° vertical field of view at 1080 lines, P₁₁·½·H ≈ 935, so the 2 m radius spans
256 px closer than about 7 m and bottoms out at the 4-pixel minimum beyond about 470 m. In practice
the GTAO is a contact and crevice term for street level and for the aircraft, and from altitude it
turns into a thin screen-space edge darkening. The output is an r8unorm target
smoothed by a separable bilateral depth-aware blur. The strength exponent of 0.8 is below 1, which
slightly lightens the raw visibility rather than deepening it.
AO offAll on
How the AO is applied
AO is applied per lobe (aoMultiBounce, default on) instead of as one flat multiplier.
The diffuse ambient term uses Jimenez's multi-bounce fit, a per-channel cubic in visibility and
albedo that gives back the energy a bright surface bounces into its own crevices. Without it a
single AO scalar over-darkens white concrete and colored roofs. The specular ambient term uses
Lagarde's specular occlusion, which depends on view angle, AO and roughness. The baked glTF
occlusion (material data .b) stays a flat multiplier on both. AO never touches the sun's direct
term: occluding the sun is the shadow map's job.
The lighting shader also accepts a bent normal from an AO target that provides one (CORTAO writes the mean unoccluded direction into .gba). GTAO's single-channel target samples as (ao, 0, 0, 1), whose .gba decodes to (−1, −1, 1). Its squared length is 3, impossible for a unit vector, so a length test selects the plain normal and no variant flag is needed.
Relighting photographs
src/assets/photo_stats.ts · src/shaders/geometry.wgsl (photo_delight) · src/shaders/modules/ground_detail.wgsl (ground_grade) · src/geo/tile_pave.ts · explorer/main.ts (sceneGrade)
A photogrammetry texture is not albedo. It is radiance under one sun at one hour: sunlit facades are bright, shadowed ones are dark and blue (lit by the sky alone), and every shadow the city cast that morning is painted on the ground. Relit by Explorer's own sun, a baked shadow gets darkened a second time by the shadow map and a sunlit wall that is now in shade still looks lit. Explorer removes the baked light in two places.
Per-tile statistics, per-texel judgment
tilesRelight (on by default) measures each photogrammetry texture once, off the main
thread, from a 24×24 copy. It finds the lit level as the 70th percentile of luminance, below the
glints and white roofs. Lit texels are those within 60% of that level, and the measure records their
mean blue share. Shadowed texels are those below half the lit level and bluer than the lit texels by
at least 0.03 of blue share. Per channel, it stores the lit/shadow ratio, clamped to 1.5–6. The
thresholds came from measuring Google's San Francisco photographs: below half the lit level, texels
turn bluer by +0.06 at 0.4 to +0.18 at 0.1, while the lit ones stay within ±0.01. Shadows there sit
at 0.2–0.5 of the lit level, much less dark than one might assume, and thresholds set for darker
shadows lift only about 2% of texels, which looks like no change at all.
The shader then judges each texel on its own. A texture atlas is cut into many small unrelated islands, so anything that looked at neighbors would mix them:
fn photo_delight(c: vec3<f32>) -> vec3<f32> {
let lit = material.photoLit; // x lit luminance, y lit blue share
let w = vec3<f32>(0.2126, 0.7152, 0.0722);
let lum = dot(c, w);
let dark = 1.0 - smoothstep(0.3 * lit.x, 0.6 * lit.x, lum);
let blue = c.b / max(c.r + c.g + c.b, 1e-4) - lit.y;
let s = dark * smoothstep(0.005, 0.06, blue) * material.photoLift.w;
let lifted = c * mix(vec3<f32>(1.0), material.photoLift.rgb, s); // per-channel lit/shadow ratio
let cap = max(lit.x * 1.05, lum) / max(dot(lifted, w), 1e-5);
return lifted * min(1.0, cap); // never brighter than the lit level
}
Lifting by a per-channel ratio removes the blue cast together with the darkness. The cap stops a texel barely in shade from being pushed brighter than the sunlit ones. Darkness alone is not enough: asphalt, dark canopy and wet soil are dark without being blue-shifted. Even so, airfield asphalt among dry grass has the same darkness ratio and blue share as real city shadows, so no per-texel color test can tell the two apart. Relighting would produce dark and tan triangles along taxiways, worse where coarse parent tiles show through their children. The exclusion is therefore geographic: a tile with airfield pavement on or beside it (from OSM's runway and taxiway polygons and lines) is not relit.
The imagery's own grade
Draped aerial imagery and photoreal ground draws (flagged in model.extra.z) go
through a second, gentler stage, ground_grade. It lifts texels whose luminance is below
0.08 and whose relative blue excess (b − r)/L is up to 0.3. The lift is toward sunlit ground
(gain 3 × (1.15, 1, 0.8)), by the imageryShadowLift setting, 0.5 by default. After that come
optional brightness, contrast about mid-gray, and saturation. tilesPavement (also on)
is geometry, not shading. While a tile is baked, vertices on OSM roads and airfield pavement are
moved onto a robust three-pass smooth surface fitted through the mesh's own pavement, so melted cars
and half-meter runway waves do not catch the low sun as lumps. That matters most for the
streaky wet-runway reflections above, which magnify every bump.
Grading for the hour
The last lighting-dependent step happens in linear HDR just before the tone curve.
sceneGrade(low, overcast, rain, night) rebuilds the color grade every frame from the real
sun. A clear day gets contrast 1.18, saturation 1.15 and a slight warmth (the scans and the haze lean
blue-gray). A low sun adds warmth (+12) and a split tone. Overcast flattens and cools. Night lowers
saturation to 0.6, since rods see little color, but is not tinted, because a cool grade on top of the
already cool night light turns the whole scene navy. Contrast is a power curve about 18% gray, not
a linear scale, because a linear contrast drives anything darker than about a tenth of mid-gray
through zero, which at night is the whole image.
Local lights
src/renderer/features/point_spot_light_feature.ts · src/shaders/point_spot_lighting.wgsl · explorer/lib/vehicles/car_beam.ts · explorer/main.ts
Point and spot lights are a second fullscreen pass, PointSpotLightFeature, blended
additively (one, one) over the lighting pass's output. It reuses the same
BRDF module and DFG energy compensation, and a windowed inverse-square falloff normalized to the
intensity at 1 m:
Explorer feeds it explicit lists rather than scene components, and every light in them is built and pooled per frame:
| Light | Type · cone | Intensity · range | Count |
|---|---|---|---|
| aircraft landing lights | spot, 4° inner / 22° outer, 0.06 below the nose | 25,000 · 700 m; × 0.0005day | per lamp |
| car low beams | spot, 59°/60°, IES profile, 0.7° down | 20,000 · 160 m | per lamp |
| position, beacon, strobe | point, radius 3 m (steady) / 9 m (flash) | 1.5 · level, flashes brighter | per lamp |
| afterburner / rocket flame | point, radius 14 m, flickering orange | × flame level | per engine |
| apron floodlights | spot, 30°/62° down from a 20 m mast head | 9,000 × night · 90 m | nearest 16 (phone 6) within 3 km |
| airport traffic landing lights | spot, 4°/22° | 25,000 × level · 700 m | nearest 3 (phone 1) |
| lightning | point, radius 9 km, (0.82, 0.88, 1.0) | 2.5×10⁷ × flash | 1, under the storm cell |
The landing lights fade by day for a reason. A light bright enough to light a runway at night
is many times the sun's illuminance where its beam meets the ground a few meters ahead, and by day it
would blow that patch out to white. Fading geometrically with the day factor, 0.0005day,
leaves a few hundredths at dusk and almost nothing at noon. The tight 4° core with a wide 22° edge
has a reason too: a narrow cone leaves a pool that begins 8 m ahead, which looks like a light standing
out in front of the aircraft rather than coming from the wing.
An IES low beam
Cars need a different shape again. A plain cone puts the pool of light out ahead of the car: the
near road is seen from the lamp at a steep angle, outside a narrow cone, and inside it the inverse
square makes the first few meters the brightest. car_beam.ts builds a photometric
profile in place of a cone. The spot pass samples it from an IES LUT, one 256-sample row per profile over
0–180° off the aim axis. The LUT is r16float rather than 8-bit because, once a
luminaire is normalized to its peak, the dim tail lives in the bottom few percent of the range,
and 8 bits quantize it into visible concentric bands:
Illuminance on flat ground from a lamp at height h goes as I·sin³(angle down)/h². An inverse-cube-of-sine falloff past the hot spot therefore keeps the road about evenly lit from the hot spot back to the bumper. The foreground is then dimmed to 40%, as a real lamp's is. The spot cone is opened to the profile's full 60° spread, so the profile alone shapes the beam.
Why no culling
The feature can cull lights into screen tiles or depth clusters, and by default ('auto')
switches to tiled above 24 lights and back below 16. Explorer pins culling: 'none', which
brute-forces every light per pixel with no culling dispatch. The light lists are short by
construction, capped at 16 apron floods and 3 traffic beams plus the player's own lamps. The lights
are also large on screen: a landing light's 700 m range or the 9 km lightning light covers most
tiles, so a culling pass would spend a dispatch and reject almost nothing. Pinning the mode also
stops the light count from moving back and forth across the auto threshold as floods come and go
at night.
Night lights
explorer/lib/ground/ground_night_lights.ts · explorer/lib/ground/ground_night_lights.wgsl · explorer/lib/ground/urban_mask.ts · explorer/lib/ground/obstruction_lights.ts · src/geo/satellite_feature.ts · src/geo/satellite.wgsl
A real city at night has hundreds of thousands of lights. None of them exist in the photogrammetry, and only a few hundred (the aircraft's, the airport's, the nearby cars') are known individually. Explorer builds night from two mechanisms: a procedural city-lights pass driven by satellite night imagery, and additive glowing points for the lights whose positions are known.
Town at 21:00: lamps on the road mask, pools, windows, car lamps
Airport at 19:30: edge and centerline points, apron floodsCity lights from VIIRS
GroundNightLightsFeature is a fullscreen additive pass inserted just before the
godrays, after lighting and water. It maps every ground pixel to latitude and longitude and samples
NASA's VIIRS night-lights imagery, the same layer the orbital globe paints. At best that imagery is
about 490 m per pixel. That is far too coarse to draw lights from, so it is used only as a density:
how lit an area is. The lights themselves are hashed points on grids fixed to the Earth.
- Terminator. Lights come on with
smoothstep(0.02, −0.12, n·toSun), wherenis the surface's up direction, so a distant city is lit by its own sunset rather than the camera's. The pass is skipped while the camera is more than 0.3 into the day side. - Where lamps can stand. Two grids: streetlights every 32 m (radiance 6) and brighter area lights every 128 m (radiance 20), each cell holding at most one lamp somewhere in its middle half. Both divide the ground frame's 4096 m period. Near the camera, an urban mask built from OpenStreetMap (roads in R, buildings in G, wall orientation in B) restricts lamps to roads and keeps them off roofs. Beyond the mask, the photo's own color thins them: none on dark bluish water, 70% fewer on green.
- Far: dots. Each lamp is drawn as a round dot on screen, not a disk on the ground, which a low view would stretch into dashes. The dot is sized through the inverse of the ground-to-screen Jacobian (from
dpdx/dpdyof the ground coordinates). It is never smaller than about a pixel. A lamp smaller than that dims instead, so a far grid averages to the same light and distant cities don't shimmer. - Near: heads, poles and pools. Within 1.5 km a lamp is a glowing head 0.22 m in radius at 9 m (street) or 14 m (area) height, found where the view ray crosses the plane of the heads, so heads show above a low camera's horizon even against the sky. Within 900 m each lamp throws a pool on the ground with a cos³/d² cut-off-fixture falloff, multiplied by the G-buffer albedo so it lights the actual surface.
- Windows. Within 2.5 km (not on phones), walls are found by a wide normal over a few pixels, because a single photogrammetry facet leans every way. Windows are laid out on a floor every 3.2 m and a bay every 3.4 m, squared to the building's footprint orientation from the mask, with a hashed share lit in warm or cool colors.
- Skyglow. A 10-step march along the view ray, out to 30 km, accumulates the light rising from the ground (VIIRS blurred over 4 km) times the haze of the lowest air (1.2 km scale height). The result is a warm dome over a city, seen overhead from inside it and on the horizon from far off. Everything fades into the night air over 120 km.
ground_night_lights.wgsl (log-like axis, not to scale). Each band fades over its last 30%. The handoff from heads and pools to dots is what keeps a street-level view and a 30 km view of the same town consistent.Two exclusions keep it honest. Surfaces with the NOT_GROUND bit (128) in the G-buffer's
light-exclusion byte, the aircraft for instance, get no ground lights, so an airframe parked on an
apron does not grow streetlights. And lamps "on" a wall seen edge-on smear into streaks, so a
point lamp is kept only where the surface is level (|face_n·up| between 0.75 and 0.9 by smoothstep).
Lamp radiance is the City lights setting (default 1.5) × 0.5. The urban mask covers ±10 km of
street-level map and is rebuilt only below 40 km altitude and below 1 km/s. Rebuilding it while
racing over the ground in a spaceship would run the browser out of connections, and the scenery's
own tiles would fail with it.
Glowing points for known lights
Lights with known positions are drawn by nine instances of one small feature,
GeoSatelliteFeature, which also draws the live satellite layer. Each instance is 16
bytes: a float32x3 world position and an rgba8 color whose alpha is a size scale. The vertex shader
expands it into a screen-facing quad sized in pixels, optionally attenuated with distance and
clamped between a minimum and maximum pixel size. The fragment shader masks a radial glow, tests
occlusion by hand against G-buffer depth (no depth attachment, so it handles reversed-Z by
normalizing both depths), and blends additively into HDR:
let sceneD = dz_standard(textureLoad(depthTex, vec2<i32>(fragCoord.xy), 0));
if (dz_standard(fragCoord.z) > sceneD) { discard; } // behind the scene
let r = sqrt(r2);
let core = pow(1.0 - r, camera.params.y); // coreSharpness
let halo = pow(1.0 - r2, camera.params.w) * camera.params.z; // haloFalloff, haloGain
let glow = (core + halo) * camera.params.x; // brightness
return vec4<f32>(pow(in.color, vec3<f32>(2.2)) * glow, glow);
| Instance | What it draws | size px (base / min–max) | atten. m | bright |
|---|---|---|---|---|
| RunwayLightFeature | runway edge/end bars, taxi edges (blue), centerlines (green), guard lights, apron mast heads, beacon; up to 8,000 | 7 / 1.5–11 | 200 | 4 |
| PlaneLightFeature | the player's and 24 others' position, beacon, strobe, landing lamps | 12 / 3–20 | 30 | 5 |
| StreetLampFeature | the street cars' head and tail lamps at night (not the streetlights) | 10 / 4–16 | 25 | 6 |
| AdsbLightFeature | live ADS-B traffic's lights, up to 400 aircraft | 12 / 2.5–22 | 60 | 5 |
| AirportTrafficLightFeature | the simulated airport traffic's lights, up to 400 | 12 / 2.5–22 | 60 | 5 |
| RoofLightFeature | red obstruction lights on tall roofs (one per cluster; the tallest flash, each building on its own flasher, 20–40 a minute), up to 800. A pinpoint core (sharpness 30) in a thin haze (halo gain 0.012, falloff 4) that the lens bloom widens | 3 / 4–18 | 300 | 400 |
| IssLightFeature | the station's red/green truss lights, double-flash strobes, floodlights (night side) | 10 / 2–14 | 60 | 2.5 |
| IssBeaconFeature | a strobing marker above the station, visible from anywhere | 5 / 6–20 | 400 | 2.5 |
| GeoSatelliteFeature | the satellites themselves (see 06) | 3 / 1–… | 1.5×10⁶ | 2.5 |
The split between the two mechanisms is deliberate. A light that must be seen from kilometers away, such as a runway edge light, a roof beacon or an airliner's strobe, needs a minimum on-screen size so it does not vanish below a pixel. A screen-space sprite gets that for free, and a G-buffer pass cannot. The cars' lamps are sprites at the cars for another reason: painted by the city-lights pass from the 10 m road mask, they would be streaks across the road seen from the ground. Only the lights that must light something (landing lights on a runway, floods on an apron) also get a real spot light in the previous section's pass.
Materials worth a note
explorer/lib/aircraft/aircraft_finish.ts · explorer/lib/vehicles/vehicle_glass.ts · src/renderer/features/ssr_feature.ts · src/shaders/ssr_resolve.wgsl · src/shaders/screen_space_reflections.wgsl · explorer/lib/studio/
Paint, metal, and a wet skin
The aircraft and vehicle models arrive with one middling glTF roughness for everything.
applyAircraftFinish replaces it by material name with a small set of finishes:
- clear-coated paintbase roughness 0.22, coat 1.0 at coat roughness 0.012 (a freshly waxed airframe)
- satin / matte0.45 with a 0.6 coat at 0.14 / 0.62, no coat (military)
- metalspolished 0.22 / metallic 0.95; brushed 0.38 / 0.85; chrome 0.04 / 1.0
- car show paint0.3 under a coat of 1.0 at 0.02
- ISSsolar cells as a mirror coat (0.025) over a dark faintly metallic grid, so a whole wing flashes the sun; gold Kapton array backs; satin beta-cloth blankets
The dry values are remembered, and setAircraftWetness(w) derives a wet finish from
them in rain. Albedo darkens by up to 18% on non-metals (the color is seen through water), base
roughness drops by 45%, and coat strength rises toward 1 with coat roughness toward 0.02. Matte paint
turns glossy and gloss paint turns mirror-like. Because the coat goes through the same
env_specular_lobe as the base, a wet airframe at a grazing angle shows the same elongated
streaks as a wet runway.
Glass
Windscreens, cabin windows and light lenses are alpha-blended, and the deferred path has no
blended pass, so VehicleGlassFeature draws them as a small forward pass over the lit HDR,
occluded by a manual depth compare. Each pane adds a Fresnel reflection, a tight sun glint, a slight
tint, and a scattering film of smudges and scratches that lights up toward the sun. From outside, the
reflection is the real sky probe's cube (the same cube the deferred pass uses). From the cockpit, it
is a cabin probe baked once per aircraft, so the glareshield and panel mirror in the side windows.
The map's buildings have no glass of their own: their windows are a filtered grid drawn on the
walls in the deferred geometry pass (facade_windows in geometry.wgsl), and a
building's glass is chosen from a number hashed from its wall color and style
(facade_glass). A curtain wall is mostly coated glass: blue-green, blue, gray, bronze or a
silver mirror, some clear. A coating is written as part metal (metallic 0.9) with the albedo set so
that F0 = mix(0.04, albedo, metallic) is the coating's color, which leaves its diffuse,
the room seen through it, faint. Plain glass is a dielectric (F0 0.04) whose albedo is the dark room
or the blind behind it. Panes are smooth (roughness 0.035, rising to 0.16 as a pane nears a pixel)
and each is tilted a fraction of a degree and bowed in or out on its own, so the sky's reflection
breaks into the patchwork of a real tower; the specular AA turns that spread into roughness far
off. A curtain wall's mullions are anodized metal (black, dark bronze, clear or the wall's color),
and its spandrels either metal panels or the same glass with nothing lit behind it.
Behind clear glass close up, each window has a room (facade_room, interior mapping;
PbrMaterial.facadeInterior, off on phones): the eye's ray from the pane is followed into a
box one bay wide, one floor tall and 3.5 to 14 m deep, by bay and floor counts per meter taken from
the uv's and the position's derivatives. It meets a ceiling (an office's rows of light panels, a
home's one lamp), a floor (carpet or wood), side and back walls in a room's own color, and a desk or
sofa partway in. By day a room is a fifth of its own albedo, dim beside the street. At night the same
grid of panes is lit as emission in the G-buffer (facadeLight, from the city lights' gain
and how dark it is; facadeHour, the local hour): the share lit follows
facade_lit_share, offices a floor at a time through the working day and thinning through
the evening, homes room by room in the morning and the evening, shops while open, and a few all
night. The full-screen night pass then leaves the map's buildings alone (their draws carry the
building mask bit) and keeps its lit windows for photoreal tiles and buildings with no facade. The
slim G-buffer has no emission, so on it the night pass draws them as before.
The facade's style rides in the vertex color's alpha as a 14-bit code (facadeCode,
read back as round(a × 65536) − 1): the building's own bits (curtain wall, twelve wall
materials, seven roofs, hangar, offices) and a wall face's (a hangar's door, a shop floor, the crown).
The tile build splits walls into those faces. Shops get a taller first floor of wide windows under
signs, some lit at night. A tower of 40 m or more has its top floor or two as a crown, either louvers
over a plant floor or, for half the glass towers, a colored wash uplit floor by floor at night. A tower
over 90 m on a convex plan may step in once or twice (towerTiers). At airports, a low,
simple building within 40 m of an apron (or inside the airport's bounds) is a hangar, with painted
sheet walls, an arched or low-pitched roof and a door of panels on the wall nearest the apron. A
larger, more intricate one is a terminal of glass, with jet bridges (a steel corridor on a column, a
cab at its end) out to the map's gates within 80 m, or, where the map has none, every 55 m along
its walls facing an apron. Shop floors get awnings over about half their shops, a sloped fabric
panel and valance in one of six colors. The apron floodlights' masts (apron_masts.ts)
stand where the runway lights put their heads, a merged mesh of poles, cross-arms and lamp housings
for the nearest airport. Walls also take a region's palette: adobe and
stucco in the American Southwest, painted boards in New England, whitewash and ochre round the
Mediterranean.
Screen-space reflections (off by default)
The ground tiles are too rough to be worth tracing, so SSR exists for the aircraft only, and
effects.ssr is off by default ("noisy"). When it is on, it traces at half resolution
with 40 steps plus 4 refinement steps out to 300 m, 3 m thickness, for roughness up to 0.5,
discarding contributions below 0.02 and blending 15% new per frame into a temporal history. Rather
than adding to the probe reflection the lighting pass already applied, the trace subtracts it: each
hit returns hit − probe along the same reflection direction, and the additive composite turns
that into a replacement. Without the subtraction, a probe-lit surface would get both reflections. SSR is
registered after the clouds, so a ray that leaves the screen toward the sky finds them.
The Studio
A development-only panel (?studio, absent from release builds) edits materials by
name and the global look, and saves overrides to explorer/assets/studio/, which do ship.
Its look file multiplies exposure (0.85), sun (1.15), sky light (iblIntensity 0.5),
shadow softness, and the grade's contrast (1.1), saturation and warmth. Material overrides are
applied after applyAircraftFinish, and a changed material refreshes its remembered dry
values so rain wets what was tuned, not the original.
Water
src/geo/sea_level_water_feature.ts · src/geo/sea_level_water.wgsl · src/geo/water_feature.ts · src/renderer/render_graph/passes/ocean/ocean_fft_sim_pass.ts · explorer/lib/vehicles/water_wake.ts · explorer/lib/vehicles/boat_wake.ts · explorer/lib/vehicles/boat_spray.ts
The photogrammetry ocean is a flat textured mesh at roughly sea level, with no water mask. The terrain datasets do have one. Explorer has a water renderer for each case.
GeoWaterFeature(Cesium World Terrain) redraws each quantized-mesh terrain tile's water as its own surface after lighting, sampling the tile's watermask texture per fragment for a texel-sharp coastline, with a refraction snapshot of the lit HDR. It is lit by the key light.SeaLevelWaterFeature(the photoreal tiles and the open terrain, on Earth only) is a screen-space pass that decides, pixel by pixel, which lit G-buffer pixels are water, and re-shades them. It is lit by the real sun.
One setting, Settings → Water → Sea (seaWater, on by default), turns the sea
on or off; the dataset decides which of the two draws it.
Finding the sea in a G-buffer
Each pixel faces three tests. It must be at sea level, with its height above the EGM96 geoid within a band (1.5 m half-width near the camera, widening with distance). It must be flat, with its normal within 6° of local up, relaxing to about 15° by 10 km where coarse tiles decimate the sea into bumpy meshes. And its imagery must read as water, blue-dominant with color weight 0.85, or dark where the OSM water mask says water. The height test is the hard one. Reconstructing a world position and subtracting a 6,371 km radius in f32 leaves no meters at all. The host instead computes in f64 a tangent frame anchored on the ellipsoid under the camera, and the shader measures height against the osculating sphere there:
Shading: waves, Fresnel, glint
The water's normal comes from the engine's FFT ocean (OceanFftSimPass), shared with
the ocean samples. One 128² grid (64² on phones) is evolved per frame into 16 octave slices of an
rgba16float array, slice s tiling 0.5·2s m, from 0.5 m to 16 km. The
spectrum is fetch-limited JONSWAP (200 km fetch) with Donelan–Banner spreading. The wind is held to
6–28 m/s (4 m/s minimum in flight, from the aircraft's own surface wind). A swell multiplier lifts the
longest octaves by up to 2.6×. The shader draws a layer only once its waves span about 8 pixels. The
slope variance of the finer layers is folded into the GGX roughness rather than drawn, so the glint
widens and breaks up with distance instead of aliasing into a crosshatch. Lakes damp the long
waves (little fetch).
// Schlick Fresnel with water's F0 = 0.02 …
let fres = clamp(0.02 + 0.98 * pow(1.0 - NdotV, max(params.sky.a, 0.5)), 0.0, 1.0);
let underwater = mix(scene.rgb, params.tint.rgb * skyB, params.misc.w); // lit tile color as "refraction"
// (Widened by the waves too small to draw: GGX alpha^2 grows with their slope variance.)
let rough = clamp(sqrt(sqrt(rough0 * rough0 * rough0 * rough0 + 2.0 * roughVar)), 0.03, 0.6);
// …
let glint = min(dGGX * fSun * NdotL, 8.0) * params.sunColor.rgb * params.sunDir.w;
var col = mix(underwater, skyRefl, fres) + glint;
The lit tile color stands in for refraction, since the imagery already shows the sea bed and the
water's color, pulled 45% toward a water tint so stitched ocean textures read as one sea. The
reflection is an analytic sky gradient plus a halo around the reflected sun rather than the probe,
with a night brightness of 0.05 + 0.95·day from the real sun. Whitecaps cover a share of
the sea from the Monahan–O'Muircheartaigh wind fit (2.95×10⁻⁶·U3.52, capped at 20%): none
in a light breeze, flecks from about 7 m/s. The water takes the lighting pass's aerial perspective
too. Without it, the sea would show clear through fog that hides the land beside it.
Wakes, rain, ice
Things that touch the water write into a 512² rgba16float wake map covering 1,024 m
around the camera. The map is fixed to the Earth by an ECEF center and scrolled when the camera
leaves its middle. Its channels are white water (fading over 8 s), rough water (18 s), and this
frame's wake-crest height and white water. An aircraft low over the sea stamps prop-wash spray. A hull
lays down its Kelvin wake: boat_wake.ts keeps the stern's track and places, for each
track point, the crests at the Kelvin half-angle of asin(1/3) = 19.47°, narrowing as √(0.6/Fr) once the
Froude number passes 0.6, as fast planing boats' wakes do. The water shader tilts its normal by the
crests' slope and adds their foam. BoatSpray throws bow sheets and a rooster tail as
sprites. In rain, raindrop rings spread in 0.6 m cells within 80 m. In a deep winter or a hard frost,
lakes (water away from the sea-level band) freeze over a few minutes into a dark glossy sheet, or
white under snow, lit by sky and sun like the ground. A hull still opens a lead through the ice where
the wake map's rough water is, with broken floes along its edges that close up again as the rough
water fades.
Swell near the shore
Near the shore the FFT tile cannot carry the swell: it is the same everywhere, and a swell
slows, shortens and turns as the bed rises under it. wave_rays.ts traces it in as
rays over the bed's 4 km grid, in a worker, and bakes a 512² rgba32uint square:
the phase's travel time τ as a full float, and in halves the amplitude, the wavenumber vector, the
breaking ratio, its running maximum and the surf similarity number. Under the square, 64 more rows
hold the breakers' cross-section (128 positions through the wave × 32 steps of progress × two kinds,
spilling and plunging: the offset along the ray and up, and the foam), and after them a second
square of the swell sent back off steep shores (the phase it adds, its share, the wall's normal),
which the module adds as the incident train mirrored in the wall's line, wavenumber k − 2(k·n)n.
A host that bakes no second square gets none. The water's two passes and
the view from under it share one WGSL module, sea_swell.wgsl, which reads it with
four textureLoad taps (no filtering needed). The phase ω τ − ω t gives the
height, the slope (−a sin φ · k) tilts the shading's normal, and a Gerstner shift of at most
0.6 / k draws the water toward each crest on the displaced surface. Under the square the FFT's
layers from 256 m tiles fade out (from 1 km fully), since the swell stands in for them. In the
shading pass the square is the 19th texture, so it is bound only where the device allows that
many; the displaced surface has it everywhere. waveHeightAt adds the same swell, read
on the CPU from the same square, so a hull rides the crests that are drawn.
Near the break the module reshapes the crest: the sinusoid becomes a solitary wave, then a bore,
with the section's offsets added in the crest's frame, mixed between the two kinds by the surf
similarity number and scaled by the crest's own strength (its set, and a hash and noise along it).
The section's foam, the bore's front and the trail behind it feed the whitecap term per pixel, and
the lip's normal is turned over with it. The same code runs in TypeScript (breakers.ts)
for waveHeightAt, kept line for line the same.
The displaced surface is a mesh of rings about the point under the camera, its cells growing with the distance as the pixels they cover do: with the eye 2 m over the water they are about 1 m deep 50 m out and 3 m at 150 m, too coarse for a lip a few tenths of a meter thick. So while a swell with breakers is shown and the camera is low, a square patch of fine cells (0.5 m, 384 a side; 0.67 m and 192 on a phone) is laid ahead of the camera, its middle on a lattice of its cells fixed to the ground so its vertices do not swim as the camera turns. It is drawn by the same vertex code as the rings, as a strip of quads per row, instanced, and the rings discard their fragments inside it, a few cells in from its edge so the two overlap with no crack. A crest seen 100 m off keeps a clean silhouette where the rings left it ragged. The cells are even, not packed at the crests.
Rivers have small features of their own near the camera: a standing wave below a rock, a hole,
an eddy line, a waterfall's splash-down pool (river_features.wgsl). Each is a shape
written as a function of the place in the flow's frame and a phase that loops, so it plays forever
with no seam; the host places up to 24 in the water's uniform block (center, flow, size, height,
strength, seed, three vec4 each), and the shader sums them, taking the slope by finite
differences and the foam from the shape. They are not a texture: the water pass has no texture
binding left. They are sampled at the drawn surface point, not the one carried down to the sea's
level, since a river's surface is the leveled ground under it, wherever that lies, and they only
tilt and whiten it: nothing there is displaced.
The rocks under the standing waves are ordinary draws, one each, flagged as not the ground: the water pass takes whatever lies at a river's level where its current runs for the river, so an unflagged rock, or one in an instanced batch whose tint does not carry the flag, was painted over as water. Each is set on the height of the finest terrain tile drawn there, since that is the river's surface on screen.
A rip current is drawn from the same patterns. The swell map packs the jet's speed out to sea beside the reflection's share in its texture (a pair of half floats), and the water pass carries the foam lines out along the swell's way, against it, at that speed: bolder inside the surf zone, faint past it. The same speed makes the water's body murkier and tan, as the river's silt does.
Running water's patterns (its drifting foam lines, the rapids' churn and standing waves) are stretched along the flow. They are read along the nearest two of 16 fixed directions and blended, not turned with the flow itself: the pattern's coordinates run to tens of thousands of meters, and turned by the local current, a turn of a hundredth of a degree moved them by meters, packing the foam into stripes. The water maps (mask, shelf and flow) are looked up from the world origin's longitude and latitude plus the point's offset from it, with the offset's angles taken against the origin's own vectors: a point's position from the Earth's center in 32-bit floats is good only to half a meter, and read that way the flow stepped in squares that size, which the carried patterns turned into a checkerboard of foam.
None of this water is geometry. On a planet streamed from photographs, the sea surface is a classification of pixels that already exist, so it costs one fullscreen pass however much coastline is in view, and it cannot drift off the shoreline the way a separately drawn water mesh would. What that gives up is real refraction and displaced waves: the sea stays flat in silhouette, which from the altitudes most of Explorer is seen at is not visible.
References
- B. Walter, S. Marschner, H. Li, K. Torrance, “Microfacet Models for Refraction through Rough Surfaces”, EGSR 2007. The GGX distribution.
- E. Heitz, “Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs”, JCGT 2014. Height-correlated Smith visibility.
- B. Karis, physically based shading course notes, SIGGRAPH 2013. Split-sum IBL, the DFG LUT, representative-point area lights (the sun-disk lobe).
- C. Fdez-Agüera, “A Multiple-Scattering Microfacet Model for Real-Time Image-based Lighting”, JCGT 2019. The energy-compensation term.
- S. Lagarde, C. de Rousiers, physically based rendering course notes, SIGGRAPH 2014. Specular occlusion and horizon occlusion.
- J. Jimenez, X. Wu, A. Pesce, A. Jarabo, “Practical Real-Time Strategies for Accurate Indirect Occlusion”, SIGGRAPH 2016 course. GTAO and its multi-bounce fit.
- C. Schlick, “An Inexpensive BRDF Model for Physically-based Rendering”, Eurographics 1994. The Fresnel approximation.
- IES LM-63, “Standard File Format for the Electronic Transfer of Photometric Data”. The photometric profile the car beam is written as.
- M. Román et al., “NASA's Black Marble nighttime lights product suite”, Remote Sensing of Environment 2018. The VIIRS night-lights data behind the city lights.
- J. Tessendorf, “Simulating Ocean Water”, SIGGRAPH course notes 2001. FFT ocean synthesis.
- K. Hasselmann et al., “Measurements of wind-wave growth and swell decay during the Joint North Sea Wave Project (JONSWAP)”, 1973; M. Donelan, J. Hamilton, W. Hui, “Directional spectra of wind-generated waves”, 1985. The wave spectrum and its spreading.
- E. Monahan, I. O'Muircheartaigh, “Optimal power-law description of oceanic whitecap coverage dependence on wind speed”, J. Phys. Oceanogr. 1980. The whitecap cover fit.
- Lord Kelvin, “On Ship Waves”, 1887. The 19.47° wake half-angle.