Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

SkyAtmosphere.altitude: a planet's sky from the street to low orbit (#282)

Evan (Yifeng) Wang7876d8709030
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 948b5e9..b4d0cb9 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -841,6 +841,14 @@ at the end. `THREERT_EDIT_LOG=1` says where a rebuild was decided, and a frame's
simulated is copied on the GPU to the grids that are the same still; new parameters make nothing again. A
program's pass is compiled in the frame it comes in.
- **Groups and cameras.** A new group, and a camera that is not the scene's, draw nothing.
+- **A planet's altitude.** `SkyAtmosphere.altitude` (m) says the scene's ground is a globe about a floating origin and
+ how high the viewer is above it, from the street to low orbit. The sky is baked from there (above the atmosphere's
+ top: black space and the air's limb), its horizon dipped and black below it (`sky::Horizon::Planet`), and aerial
+ perspective runs over the sphere straight below the camera (pathtrace.wgsl `aerial_planet`, its reference and tests
+ in `sky.rs` `aerial_columns`), so that from high up the haze thins instead of lying at sea-level density around the
+ camera. A new altitude alone is not another sky (`Changes::altitude`): the haze takes it at once, and the sky is
+ baked again in place as for a moving sun, on the worker thread, once it is 5 % (at least 250 m) from the altitude
+ it was baked for (`LiveCore::move_altitude`).
Still a rebuild: particle systems that come or go, and their functions and programs; a geometry function; a posed model the scene has not got, and any new model under software traversal (its room does
not grow); a material that becomes a particle's or gets vertex colours; a rect light's card that comes, goes or takes
diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.ts
index c45007f..02566c5 100644
--- a/packages/scene/src/core.ts
+++ b/packages/scene/src/core.ts
@@ -2346,7 +2346,18 @@ export class SkyAtmosphere {
* it, by day and by night (the glow). Off at 0 (the default): surfaces are seen through clear air.
*/
aerialPerspective = 0;
- constructor(opts: { sun?: DirectionalLight | null; groundAlbedo?: ColorLike; skyLightIntensity?: number; dynamic?: boolean; glow?: ColorLike; glowIntensity?: number; horizonGlow?: ColorLike; horizonGlowIntensity?: number; horizonGlowHeight?: number; aerialPerspective?: number } = {}) {
+ /**
+ * A planet: the viewer's real altitude above the ground (sea level), m, from the street to low orbit, for a scene
+ * whose ground is a globe drawn about a floating origin (the camera kept near the origin, +y the local up there). The
+ * sky is baked from that altitude instead of the camera's height: above the atmosphere's top (100 km) space is
+ * black with the air's thin limb above the horizon; the horizon dips with altitude and the sky is black below it
+ * (the globe's geometry is what shows there). Aerial perspective runs over the sphere below the camera, so it thins
+ * with altitude instead of lying at sea-level density around the camera. Set it as the camera moves: the live view
+ * re-bakes the sky in place (on a worker thread, as for a `dynamic` sun) once it has moved 5 % (at least 250 m)
+ * from the altitude it was baked for. null (the default): a flat world, baked from the camera's height when built.
+ */
+ altitude: number | null = null;
+ constructor(opts: { sun?: DirectionalLight | null; groundAlbedo?: ColorLike; skyLightIntensity?: number; dynamic?: boolean; glow?: ColorLike; glowIntensity?: number; horizonGlow?: ColorLike; horizonGlowIntensity?: number; horizonGlowHeight?: number; aerialPerspective?: number; altitude?: number | null } = {}) {
this.sun = opts.sun ?? null;
if (opts.groundAlbedo !== undefined) this.groundAlbedo = new Color(opts.groundAlbedo);
if (opts.skyLightIntensity !== undefined) this.skyLightIntensity = opts.skyLightIntensity;
@@ -2357,6 +2368,7 @@ export class SkyAtmosphere {
if (opts.horizonGlowIntensity !== undefined) this.horizonGlowIntensity = opts.horizonGlowIntensity;
if (opts.horizonGlowHeight !== undefined) this.horizonGlowHeight = opts.horizonGlowHeight;
if (opts.aerialPerspective !== undefined) this.aerialPerspective = opts.aerialPerspective;
+ if (opts.altitude !== undefined) this.altitude = opts.altitude;
}
}
diff --git a/packages/scene/src/engine.ts b/packages/scene/src/engine.ts
index bef2bfe..033f1d4 100644
--- a/packages/scene/src/engine.ts
+++ b/packages/scene/src/engine.ts
@@ -67,7 +67,7 @@ export interface CameraDesc {
}
export type SkyDesc =
- | { type: "atmosphere"; /** the sun light's object */ sun: number | null; groundAlbedo: Vec3; rayleighScale: number; mieScale: number; mieAnisotropy: number; skyLightIntensity: number; /** the sun moves (time of day) */ dynamic?: boolean; /** night-sky glow, nits */ glow?: Vec3; /** its light dome: nits at the horizon (RGB), the elevation (radians) it falls to 1/e by */ horizonGlow?: [number, number, number, number]; /** aerial perspective: density multiple (0 = off) */ aerial?: number }
+ | { type: "atmosphere"; /** the sun light's object */ sun: number | null; groundAlbedo: Vec3; rayleighScale: number; mieScale: number; mieAnisotropy: number; skyLightIntensity: number; /** the sun moves (time of day) */ dynamic?: boolean; /** night-sky glow, nits */ glow?: Vec3; /** its light dome: nits at the horizon (RGB), the elevation (radians) it falls to 1/e by */ horizonGlow?: [number, number, number, number]; /** aerial perspective: density multiple (0 = off) */ aerial?: number; /** a planet's viewer altitude, m (SkyAtmosphere.altitude) */ altitude?: number }
| { type: "color"; color: Vec3; /** nits */ intensity: number; skyLightIntensity: number }
| { type: "hdri"; texture: number; intensity: number; rotation: number; skyLightIntensity: number }
| {
@@ -1599,6 +1599,7 @@ export class SceneBinding {
if (env.glowIntensity > 0) a.glow = vec3(env.glow).map((c) => c * env.glowIntensity) as Vec3;
if (env.horizonGlowIntensity > 0) a.horizonGlow = [...vec3(env.horizonGlow).map((c) => c * env.horizonGlowIntensity), env.horizonGlowHeight] as [number, number, number, number];
if (env.aerialPerspective > 0) a.aerial = env.aerialPerspective;
+ if (env.altitude !== null && Number.isFinite(env.altitude)) a.altitude = Math.max(0, env.altitude);
return a;
}
if (env instanceof SkyColor) return { type: "color", color: vec3(env.color), intensity: env.intensity, skyLightIntensity: env.skyLightIntensity };
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index a6a1873..c2bd65a 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -1954,7 +1954,8 @@ fn sky_mis(d: vec3<f32>, pdf: f32) -> vec3<f32> {
wgt = power_heuristic(pdf, env_pdf(d));
}
var c = env_radiance(d) * wgt;
- if (has(F_AERIAL) && pdf <= 0.0) { c = aerial_light(d); }
+ // (On a planet the camera sees the bake itself: space, the limb, black below the dipped horizon.)
+ if (has(F_AERIAL) && pdf <= 0.0 && P.aerial.w <= 0.0) { c = aerial_light(d); }
if (pdf > 0.0) { c += sun_disks(d, pdf); }
return c;
}
@@ -2541,13 +2542,74 @@ fn aerial_od(y0: f32, dy: f32, t: f32, h: f32) -> f32 {
fn aerial_tr(o: vec3<f32>, d: vec3<f32>, t: f32) -> vec3<f32> {
let rayleigh = vec3<f32>(5.802e-6, 13.558e-6, 33.1e-6) * P.aerial.y;
let mie = 3.996e-6 * P.aerial.z + 0.444e-6;
+ if (P.aerial.w > 0.0) {
+ let c = aerial_planet(o - P.cam_pos.xyz, d, t, P.aerial.w);
+ return exp(-P.aerial.x * (rayleigh * c.x + mie * c.y));
+ }
return exp(-P.aerial.x * (rayleigh * aerial_od(o.y, d.y, t, 8000.0) + mie * aerial_od(o.y, d.y, t, 1200.0)));
}
+// On a planet (SkyAtmosphere.altitude: P.aerial.w, the camera's altitude in m): the air over a sphere of the sky's
+// ground radius whose centre is straight below the camera, so that from high up the haze thins with altitude instead of
+// lying at sea-level density around the camera. The columns of air and haze (m at sea-level density) along the
+// segment from the camera-relative point `q`, by Chapman's function as an erfcx; the derivation, its sources and the
+// tests that hold it to a quadrature: sky.rs `aerial_columns`, of which this is a copy line by line.
+const AERIAL_R: f32 = 6.36e6;
+
+fn aerial_erfcx(y: f32) -> f32 {
+ return 1.1283792 / (y + sqrt(y * y + 0.6166356 * y + 1.2732395)) * (1.0 + 0.0295 * y * y / (1.0 + 0.312 * y * y * y));
+}
+
+fn aerial_column(h: f32, mu: f32, scale: f32) -> f32 {
+ let x = (AERIAL_R + h) / scale;
+ return scale * exp(-max(h, -500.0) / scale) * sqrt(0.5 * PI * x) * aerial_erfcx(max(mu, 0.0) * sqrt(0.5 * x));
+}
+
+// A point's altitude and the zenith cosine of `d` there (`q`: the point less the camera).
+fn aerial_at(q: vec3<f32>, d: vec3<f32>, h0: f32) -> vec2<f32> {
+ let up = q.y + h0;
+ let s2 = q.x * q.x + q.z * q.z;
+ let y = up + AERIAL_R;
+ let r = sqrt(y * y + s2);
+ return vec2<f32>(up + s2 / (r + y), (q.x * d.x + y * d.y + q.z * d.z) / r);
+}
+
+fn aerial_planet(q: vec3<f32>, d: vec3<f32>, t: f32, h0: f32) -> vec2<f32> {
+ let a = aerial_at(q, d, h0);
+ let b = aerial_at(q + d * t, d, h0);
+ let lowest = -(q.x * d.x + (q.y + h0 + AERIAL_R) * d.y + q.z * d.z);
+ let p = aerial_at(q + d * clamp(lowest, 0.0, t), d, h0);
+ var od = vec2<f32>(0.0);
+ for (var i = 0u; i < 2u; i++) {
+ let scale = select(1200.0, 8000.0, i == 0u);
+ var c: f32;
+ if (lowest <= 0.0) {
+ c = aerial_column(a.x, a.y, scale) - aerial_column(b.x, b.y, scale);
+ } else if (lowest >= t) {
+ c = aerial_column(b.x, -b.y, scale) - aerial_column(a.x, -a.y, scale);
+ } else {
+ c = 2.0 * aerial_column(p.x, 0.0, scale) - aerial_column(a.x, -a.y, scale) - aerial_column(b.x, b.y, scale);
+ }
+ od[i] = max(c, 0.0);
+ }
+ return od;
+}
+
// The sky a little above the horizon (2.3 degrees: clear of the baked sky's fade to its black lower half), or where
// the ray points if higher: the haze's light, and what camera rays see of the sky near the horizon with F_AERIAL, so
// that the hazed land meets the sky without the fade's dark seam.
+// On a planet (P.aerial.w > 0) the bake is black below its dipped horizon; the haze's light is the limb's, the air
+// seen edge on in the ray's azimuth: the bake's row the horizon crosses (P.sky_color.w, its v), read back whole (its
+// alpha: the share of the row the sky covers; sky.rs `Horizon::Planet`), for rays up to a row above its centre too (the
+// globe's own silhouette may be there, and the map read between the limb and the row above it is darker than either).
+// Higher, the sky where the ray points.
fn aerial_light(d: vec3<f32>) -> vec3<f32> {
+ if (P.aerial.w > 0.0 && P.sky_color.w > 0.0 && P.env.x > 0.5) {
+ let uv = env_uv(d);
+ if (uv.y < P.sky_color.w - 1.0 / P.env.z) { return env_radiance(d); }
+ let l = textureSampleLevel(env_tex, samp, vec2<f32>(uv.x, P.sky_color.w), 0.0);
+ return l.rgb / max(l.a, 1e-3);
+ }
return env_radiance(normalize(vec3<f32>(d.x, max(d.y, 0.04), d.z)));
}
diff --git a/renderer/src/desc.rs b/renderer/src/desc.rs
index 0c90b43..a9baeb1 100644
--- a/renderer/src/desc.rs
+++ b/renderer/src/desc.rs
@@ -210,6 +210,12 @@ pub enum Sky {
/// density (0 = off; pathtrace.wgsl `aerial_tr`).
#[serde(default)]
aerial: f32,
+ /// The viewer's altitude above the ground (m) on a planet whose ground is the scene's globe (`SkyAtmosphere`
+ /// `altitude`): the sky is baked from there, its horizon dipped (`sky::Horizon::Planet`), and the aerial
+ /// perspective runs over the sphere below the camera. Changing it re-bakes in place past a threshold
+ /// (live/edits.rs `move_altitude`). None: a flat world, the sky baked from the camera's height when built.
+ #[serde(default)]
+ altitude: Option<f32>,
},
#[serde(rename_all = "camelCase")]
Color { color: Vec3, intensity: f32, sky_light_intensity: f32 },
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index 34cbce6..116edf4 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -925,24 +925,30 @@ pub struct SkyBaked {
pub color: Vec3,
pub has_env: bool,
pub sun: Option<Vec3>,
+ /// A planet's limb row (`sky::SkyBake::horizon_v`), 0 otherwise: `Params::sky_color[3]`.
+ pub horizon_v: f32,
}
-/// Bakes a scene's sky (`cloud_cover`: an atmosphere's; `altitude`: the camera's, m). The last atmosphere and the last
-/// gradient are kept: edits that leave the sky's inputs as they were reuse the bake.
+/// Bakes a scene's sky (`cloud_cover`: an atmosphere's; `altitude`: the camera's, m, unless the sky names a planet's
+/// own). The last atmosphere and the last gradient are kept: edits that leave the sky's inputs as they were reuse the
+/// bake.
pub fn bake_sky(sky: &scene::SkyData, cloud_cover: f32, altitude: f32) -> SkyBaked {
match sky {
- scene::SkyData::Atmosphere { sun_dir, sun_lux, rayleigh, mie, g: mie_g, ground, dynamic, glow, .. } => {
+ scene::SkyData::Atmosphere { sun_dir, sun_lux, rayleigh, mie, g: mie_g, ground, dynamic, glow, altitude: planet } => {
static LAST: std::sync::Mutex<Option<(Vec<u32>, std::sync::Arc<sky::SkyBake>)>> = std::sync::Mutex::new(None);
- let alt = altitude;
+ let (alt, horizon) = match planet {
+ Some(a) => (*a, sky::Horizon::Planet),
+ None => (altitude, sky::Horizon::Level),
+ };
let (bw, bh) = if *dynamic { sky::DYNAMIC_SKY } else { (1024, 512) };
- let key: Vec<u32> = [*rayleigh, *mie, *mie_g, ground.x, ground.y, ground.z, sun_dir.x, sun_dir.y, sun_dir.z, sun_lux.x, sun_lux.y, sun_lux.z, alt, glow.uniform.x, glow.uniform.y, glow.uniform.z, glow.horizon.x, glow.horizon.y, glow.horizon.z, glow.height, bw as f32, cloud_cover].iter().map(|f| f.to_bits()).collect();
+ let key: Vec<u32> = [*rayleigh, *mie, *mie_g, ground.x, ground.y, ground.z, sun_dir.x, sun_dir.y, sun_dir.z, sun_lux.x, sun_lux.y, sun_lux.z, alt, glow.uniform.x, glow.uniform.y, glow.uniform.z, glow.horizon.x, glow.horizon.y, glow.horizon.z, glow.height, bw as f32, cloud_cover, if planet.is_some() { 1.0 } else { 0.0 }].iter().map(|f| f.to_bits()).collect();
let mut last = LAST.lock().unwrap();
let bake = match last.as_ref() {
Some((k, b)) if *k == key => b.clone(),
_ => {
let atm = sky::Atmosphere::earth(*rayleigh, *mie, *mie_g, *ground);
- let b = std::sync::Arc::new(if *dynamic || !glow.is_zero() || cloud_cover > 0.0 {
- sky::bake_atmosphere_tables(&atm, &sky::SkyTables::new(&atm), *sun_dir, *sun_lux, alt, bw, bh, *glow, cloud_cover)
+ let b = std::sync::Arc::new(if *dynamic || !glow.is_zero() || cloud_cover > 0.0 || planet.is_some() {
+ sky::bake_atmosphere_tables(&atm, &sky::SkyTables::new(&atm), *sun_dir, *sun_lux, alt, bw, bh, *glow, cloud_cover, horizon)
} else {
sky::bake_atmosphere(&atm, *sun_dir, *sun_lux, alt, bw, bh)
});
@@ -950,7 +956,7 @@ pub fn bake_sky(sky: &scene::SkyData, cloud_cover: f32, altitude: f32) -> SkyBak
b
}
};
- SkyBaked { env: gpu::EnvMap { width: bake.width, height: bake.height, texels: bake.texels.clone() }, color: Vec3::ZERO, has_env: true, sun: Some(bake.sun_illuminance) }
+ SkyBaked { env: gpu::EnvMap { width: bake.width, height: bake.height, texels: bake.texels.clone() }, color: Vec3::ZERO, has_env: true, sun: Some(bake.sun_illuminance), horizon_v: bake.horizon_v }
}
scene::SkyData::Gradient(gr) => {
static LAST: std::sync::Mutex<Option<(sky::Gradient, std::sync::Arc<sky::SkyBake>)>> = std::sync::Mutex::new(None);
@@ -963,10 +969,10 @@ pub fn bake_sky(sky: &scene::SkyData, cloud_cover: f32, altitude: f32) -> SkyBak
b
}
};
- SkyBaked { env: gpu::EnvMap { width: bake.width, height: bake.height, texels: bake.texels.clone() }, color: Vec3::ZERO, has_env: true, sun: None }
+ SkyBaked { env: gpu::EnvMap { width: bake.width, height: bake.height, texels: bake.texels.clone() }, color: Vec3::ZERO, has_env: true, sun: None, horizon_v: 0.0 }
}
- scene::SkyData::Color(c) => SkyBaked { env: gpu::EnvMap { width: 1, height: 1, texels: vec![[c.x, c.y, c.z, 1.0]] }, color: *c, has_env: false, sun: None },
- scene::SkyData::None => SkyBaked { env: gpu::EnvMap { width: 1, height: 1, texels: vec![[0.0; 4]] }, color: Vec3::ZERO, has_env: false, sun: None },
+ scene::SkyData::Color(c) => SkyBaked { env: gpu::EnvMap { width: 1, height: 1, texels: vec![[c.x, c.y, c.z, 1.0]] }, color: *c, has_env: false, sun: None, horizon_v: 0.0 },
+ scene::SkyData::None => SkyBaked { env: gpu::EnvMap { width: 1, height: 1, texels: vec![[0.0; 4]] }, color: Vec3::ZERO, has_env: false, sun: None, horizon_v: 0.0 },
}
}
@@ -975,7 +981,7 @@ impl SkyBaked {
/// light-sampled (`floor`: `Prepared::env_nee_floor`).
pub fn write(&self, p: &mut gpu::Params, floor: f32) {
p.env = [if self.has_env { 1.0 } else { 0.0 }, self.env.width as f32, self.env.height as f32, p.env[3]];
- p.sky_color = [self.color.x, self.color.y, self.color.z, 0.0];
+ p.sky_color = [self.color.x, self.color.y, self.color.z, self.horizon_v];
p.counts2[1] = sky_sampled(sky_brightest(&self.env, self.color), floor, self.has_env) as u32;
}
}
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index 1108ad4..0e71545 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -1014,6 +1014,9 @@ impl LiveCore {
self.env.settings = scene::EnvSettings::of(world);
self.env.settings.write(&mut self.sc.base);
}
+ if changes.altitude && !changes.sky && !changes.structural && !self.move_altitude(world)? {
+ changes.structural = true;
+ }
if changes.sky && !changes.structural && !self.apply_sky(world)? {
self.fallback = Some("a sky whose map does not fit the scene's buffers in place".into());
self.fallbacks += 1;
@@ -1196,7 +1199,7 @@ impl LiveCore {
pub(super) fn move_sun(&mut self, world: &World) {
let Some((id, dir, lux)) = scene::atmosphere_sun(world) else { return };
if self.env.sky.worker.is_none() {
- self.env.sky.worker = DynamicSky::new(world, self.env.sky.map, self.env.sky.altitude);
+ self.env.sky.worker = DynamicSky::new(world, self.env.sky.map);
}
let Some(sky) = self.env.sky.worker.as_ref() else { return };
let cover = self.env.settings.cloud_cover;
@@ -1205,7 +1208,7 @@ impl LiveCore {
if e.set_sun_light(world, id, colour) {
self.sc.up.put_lights(&self.g.queue, &e.lights);
}
- let _ = sky.ask.send((dir, lux, cover));
+ let _ = sky.ask.send((dir, lux, cover, self.env.sky.altitude));
if self.fixed_dt.is_some() {
if let Ok(b) = sky.done.recv() {
self.put_sky(b);
@@ -1214,13 +1217,31 @@ impl LiveCore {
self.lit_changed = self.frame.max(1);
}
+ /// A planet's viewer altitude changed (`SkyAtmosphere.altitude`, its sky otherwise the same): the kernel's haze took
+ /// it with the environment's settings already; the sky is re-baked, as for a moving sun (`move_sun`: on the worker
+ /// thread, in place), once the altitude is `ALTITUDE_STEP` from the one it was baked for. A sky without a sun
+ /// bakes here (`apply_sky`).
+ pub(super) fn move_altitude(&mut self, world: &World) -> Result<bool> {
+ let crate::desc::Sky::Atmosphere { altitude: Some(altitude), sun, .. } = &world.environment.sky else { return Ok(true) };
+ let altitude = if altitude.is_finite() { altitude.max(0.0) } else { return Ok(true) };
+ if !altitude_moved(self.env.sky.altitude, altitude) {
+ return Ok(true);
+ }
+ self.env.sky.altitude = altitude;
+ if sun.is_some() && scene::atmosphere_sun(world).is_some() {
+ self.move_sun(world);
+ return Ok(true);
+ }
+ self.apply_sky(world)
+ }
+
/// Another sky (its kind, its parameters, its sun), as a build takes it: baked here, its environment map and CDF
/// put in place (of another size: a new texture, the scene bound again), the parameters that say how it is read,
/// and the lights it owns: the atmosphere's sun takes its colour from the bake, a light that is the sun no longer
/// its own again. False, with nothing changed, when the map's CDF cannot grow in place (`Gpu::put_env`).
pub(super) fn apply_sky(&mut self, world: &World) -> Result<bool> {
let (sky, sun) = scene::sky_data(world, &self.assets, &|id| world.world_matrix(id))?;
- let altitude = world.settings.camera.map_or(self.env.sky.altitude, |id| world.world_matrix(id).w_axis.y.max(0.0));
+ let altitude = super::load::sky_altitude(&sky).unwrap_or_else(|| world.settings.camera.map_or(self.env.sky.altitude, |id| world.world_matrix(id).w_axis.y.max(0.0)));
let cover = self.env.settings.cloud_cover;
let baked = crate::bake_sky(&sky, cover, altitude);
if !self.g.put_env(&mut self.sc.up, &baked.env, &crate::build_env_cdf(&baked.env)) {
@@ -1261,11 +1282,13 @@ impl LiveCore {
}
}
- pub(super) fn put_sky(&mut self, (env, cdf, max): (gpu::EnvMap, Vec<f32>, f32)) {
+ pub(super) fn put_sky(&mut self, (env, cdf, max, horizon_v): super::load::SkyBaked) {
// (The worker bakes at the map's size: written in place.)
if self.env.sky.worker.is_none() || !self.g.put_env(&mut self.sc.up, &env, &cdf) {
return;
}
+ // (A planet's limb row moves with the altitude it was baked for: `aerial_light` reads the map's own.)
+ self.sc.base.sky_color[3] = horizon_v;
// As the load decides it: the sky is light-sampled unless it is negligible next to the emitters (night), or a
// baked sky is not light-sampled at all (`sky_sampled`).
self.sc.base.counts2[1] = crate::sky_sampled(max, self.env.sky.floor, true) as u32;
@@ -3346,3 +3369,12 @@ impl LiveCore {
}
}
+
+/// How far a planet's viewer altitude moves before the sky is baked again (`LiveCore::move_altitude`): 5 % of it, and
+/// at least 250 m (the sky from the street and from 250 m up differ by less than the bake's own steps).
+pub(super) const ALTITUDE_STEP: (f32, f32) = (0.05, 250.0);
+
+/// Whether the sky baked at `baked` m is stale at `now` m.
+pub(super) fn altitude_moved(baked: f32, now: f32) -> bool {
+ (now - baked).abs() > (ALTITUDE_STEP.0 * baked.max(now)).max(ALTITUDE_STEP.1)
+}
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index 8eb0699..477ee9f 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -43,6 +43,14 @@ fn atmosphere(dynamic: bool) -> serde_json::Value {
serde_json::json!({ "type": "atmosphere", "sun": 20, "groundAlbedo": [0.3, 0.3, 0.3], "rayleighScale": 1, "mieScale": 1, "mieAnisotropy": 0.8, "skyLightIntensity": 1, "dynamic": dynamic })
}
+/// The dynamic atmosphere of a planet seen from `altitude` m, with aerial perspective.
+fn planet(altitude: f32) -> serde_json::Value {
+ let mut a = atmosphere(true);
+ a["altitude"] = serde_json::json!(altitude);
+ a["aerial"] = serde_json::json!(1.0);
+ a
+}
+
fn manual(ev: f32) -> serde_json::Value {
serde_json::json!({ "mode": "manual", "ev100": ev })
}
@@ -815,6 +823,8 @@ fn edits_in_place_leave_what_a_build_does() {
("an atmosphere with its sun", true, Box::new(|w| w.set_environment(crate::desc::Environment { sky: sky(atmosphere(false)), ..w.environment.clone() }))),
("the atmosphere as a dynamic sky (a map of another size)", false, Box::new(|w| w.set_environment(crate::desc::Environment { sky: sky(atmosphere(true)), ..w.environment.clone() }))),
("the sun turned (a sun's move)", true, Box::new(|w| w.set_transform(20, Vec3::ZERO, glam::Quat::from_rotation_x(-0.9) * glam::Quat::from_rotation_y(-0.3), Vec3::ONE).unwrap())),
+ ("a planet's sky (an altitude, aerial perspective)", true, Box::new(|w| w.set_environment(crate::desc::Environment { sky: sky(planet(400_000.0)), ..w.environment.clone() }))),
+ ("the planet's altitude moved (re-baked in place)", true, Box::new(|w| w.set_environment(crate::desc::Environment { sky: sky(planet(12_000.0)), ..w.environment.clone() }))),
("one colour again (the sun is a light of its own)", true, Box::new(|w| w.set_environment(crate::desc::Environment { sky: sky(serde_json::json!({ "type": "color", "color": [1.0, 1.0, 1.0], "intensity": 0.2, "skyLightIntensity": 1 })), ..w.environment.clone() }))),
("the light turned and made an atmosphere's sun at once", true, Box::new(|w| {
w.set_transform(20, Vec3::ZERO, glam::Quat::from_rotation_x(-0.3) * glam::Quat::from_rotation_y(0.8), Vec3::ONE).unwrap();
@@ -4965,3 +4975,26 @@ fn the_first_pass_leaves_the_camera_hits() {
let missed = hits.iter().filter(|h| tri(h) == u32::MAX).count();
assert!(missed > 200 && hits.iter().filter(|h| tri(h) == u32::MAX).all(|h| inst(h) == u32::MAX), "{missed} pixels of nothing, each a miss whole");
}
+
+/// A planet's altitude alone is not another sky: the world says so apart (`Changes::altitude`), and the view bakes
+/// again only past its step (5 %, at least 250 m).
+#[test]
+fn a_planets_altitude_is_not_another_sky() {
+ let mut w = world();
+ w.set_environment(crate::desc::Environment { sky: sky(planet(400_000.0)), ..w.environment.clone() });
+ let c = w.take_changes();
+ assert!(c.sky && !c.altitude, "a planet's sky where there was none: another sky");
+ w.set_environment(crate::desc::Environment { sky: sky(planet(380_000.0)), ..w.environment.clone() });
+ let c = w.take_changes();
+ assert!(c.altitude && !c.sky && c.environment, "the altitude alone");
+ w.set_environment(crate::desc::Environment { sky: sky(planet(380_000.0)), ..w.environment.clone() });
+ assert!(!w.take_changes().altitude, "the same altitude");
+ let mut other = planet(380_000.0);
+ other["rayleighScale"] = serde_json::json!(2.0);
+ w.set_environment(crate::desc::Environment { sky: sky(other), ..w.environment.clone() });
+ let c = w.take_changes();
+ assert!(c.sky && !c.altitude, "the altitude and another parameter: another sky");
+ use super::edits::altitude_moved;
+ assert!(!altitude_moved(400_000.0, 381_000.0) && altitude_moved(400_000.0, 379_000.0));
+ assert!(!altitude_moved(2.0, 200.0) && altitude_moved(2.0, 260.0) && altitude_moved(260.0, 2.0));
+}
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index 87d4936..45efde3 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -66,6 +66,14 @@ pub(super) struct LoadedScene {
pub(super) codes_sent: Vec<u32>,
}
+/// A planet's viewer altitude, when the sky has one (`desc::Sky::Atmosphere::altitude`).
+pub(super) fn sky_altitude(sky: &scene::SkyData) -> Option<f32> {
+ match sky {
+ scene::SkyData::Atmosphere { altitude, .. } => *altitude,
+ _ => None,
+ }
+}
+
/// Cores the sky's worker thread bakes with: the rest stay with the frame (scripts, uploads, the GPU's driver).
pub(super) const SKY_THREADS: usize = 3;
@@ -76,19 +84,26 @@ pub(super) const SKY_THREADS: usize = 3;
/// trails the sun by one bake (~10–40 ms at `sky::DYNAMIC_SKY`). Lockstep runs wait for it, so they repeat.
pub(super) struct DynamicSky {
pub(super) atm: Arc<crate::sky::Atmosphere>,
- /// (sun direction, sun illuminance above the atmosphere, cloud cover)
- pub(super) ask: mpsc::Sender<(glam::Vec3, glam::Vec3, f32)>,
- pub(super) done: mpsc::Receiver<(gpu::EnvMap, Vec<f32>, f32)>,
+ pub(super) ask: mpsc::Sender<SkyAsk>,
+ pub(super) done: mpsc::Receiver<SkyBaked>,
}
+/// A bake asked of the worker: the sun's direction, its illuminance above the atmosphere, the cloud cover, the
+/// viewer's altitude (m: a planet's, `SkyAtmosphere.altitude`, or the camera's when the sky was built).
+pub(super) type SkyAsk = (glam::Vec3, glam::Vec3, f32, f32);
+
+/// What the worker baked: the environment map, its CDF, its brightest texel, the limb's row (`sky::SkyBake::horizon_v`).
+pub(super) type SkyBaked = (gpu::EnvMap, Vec<f32>, f32, f32);
+
impl DynamicSky {
- pub(super) fn new(world: &World, (w, h): (u32, u32), altitude: f32) -> Option<DynamicSky> {
- let crate::desc::Sky::Atmosphere { rayleigh_scale, mie_scale, mie_anisotropy, ground_albedo, glow, horizon_glow, sun: Some(_), .. } = &world.environment.sky else {
+ pub(super) fn new(world: &World, (w, h): (u32, u32)) -> Option<DynamicSky> {
+ let crate::desc::Sky::Atmosphere { rayleigh_scale, mie_scale, mie_anisotropy, ground_albedo, glow, horizon_glow, sun: Some(_), altitude, .. } = &world.environment.sky else {
return None;
};
+ let horizon = if altitude.is_some() { crate::sky::Horizon::Planet } else { crate::sky::Horizon::Level };
let atm = Arc::new(crate::sky::Atmosphere::earth(*rayleigh_scale, *mie_scale, *mie_anisotropy, glam::Vec3::from(*ground_albedo)));
let glow = crate::sky::glow_of(glow, horizon_glow);
- let (ask, asked) = mpsc::channel::<(glam::Vec3, glam::Vec3, f32)>();
+ let (ask, asked) = mpsc::channel::<SkyAsk>();
let (tx, done) = mpsc::channel();
let a = atm.clone();
std::thread::Builder::new()
@@ -99,12 +114,12 @@ impl DynamicSky {
Some(p) => p.install(|| crate::sky::SkyTables::new(&a)),
None => crate::sky::SkyTables::new(&a),
};
- let bake = |sun: (glam::Vec3, glam::Vec3, f32)| {
- let b = crate::sky::bake_atmosphere_tables(&a, &tables, sun.0, sun.1, altitude, w, h, glow, sun.2);
+ let bake = |sun: SkyAsk| {
+ let b = crate::sky::bake_atmosphere_tables(&a, &tables, sun.0, sun.1, sun.3, w, h, glow, sun.2, horizon);
let env = gpu::EnvMap { width: b.width, height: b.height, texels: b.texels };
let cdf = crate::build_env_cdf(&env);
let max = env.texels.iter().map(|t| 0.2126 * t[0] + 0.7152 * t[1] + 0.0722 * t[2]).fold(0.0f32, f32::max);
- (env, cdf, max)
+ (env, cdf, max, b.horizon_v)
};
// The newest sun only: bakes asked for while one ran are stale.
while let Ok(mut sun) = asked.recv() {
@@ -255,7 +270,7 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
let _ = g.kernel_pass(&up.kernel, "media_composite");
}
let env = Environment {
- sky: SkyState { map: (prep.env.width, prep.env.height), altitude: sc.camera.position.y.max(0.0), floor: prep.env_nee_floor, cover: sc.environment.cloud_cover, worker: None },
+ sky: SkyState { map: (prep.env.width, prep.env.height), altitude: sky_altitude(&sc.sky).unwrap_or(sc.camera.position.y.max(0.0)), floor: prep.env_nee_floor, cover: sc.environment.cloud_cover, worker: None },
settings: sc.environment.clone(),
};
let view = ViewState::new(&sc.camera, Arc::new(sc.preset.clone()));
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index 9f1f951..7bb23a8 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -561,8 +561,9 @@ impl EnvSettings {
pub enum SkyData {
None,
Color(Vec3),
- /// `dynamic`: baked at `sky::DYNAMIC_SKY` (the live view re-bakes it as the sun moves); `glow`: night-sky radiance.
- Atmosphere { sun_dir: Vec3, sun_lux: Vec3, rayleigh: f32, mie: f32, g: f32, ground: Vec3, dynamic: bool, glow: crate::sky::Glow },
+ /// `dynamic`: baked at `sky::DYNAMIC_SKY` (the live view re-bakes it as the sun moves); `glow`: night-sky radiance;
+ /// `altitude`: a planet's viewer altitude (m, `desc::Sky::Atmosphere::altitude`), or a flat world's sky.
+ Atmosphere { sun_dir: Vec3, sun_lux: Vec3, rayleigh: f32, mie: f32, g: f32, ground: Vec3, dynamic: bool, glow: crate::sky::Glow, altitude: Option<f32> },
Gradient(crate::sky::Gradient),
}
@@ -1390,7 +1391,7 @@ pub const MEDIUM_HIDDEN: u32 = 2;
pub fn sky_data(w: &World, assets: &Path, matrix: &dyn Fn(u32) -> Mat4) -> Result<(SkyData, Option<u32>)> {
let mut sun_id = None;
let sky = match &w.environment.sky {
- Sky::Atmosphere { sun, ground_albedo, rayleigh_scale, mie_scale, mie_anisotropy, dynamic, glow, horizon_glow, .. } => {
+ Sky::Atmosphere { sun, ground_albedo, rayleigh_scale, mie_scale, mie_anisotropy, dynamic, glow, horizon_glow, altitude, .. } => {
let sun_light = sun.and_then(|s| w.objects.get(&s).map(|o| (s, o)));
let (sun_dir, sun_lux) = match sun_light.map(|(s, o)| (matrix(s), &o.kind)) {
Some((m, Kind::Light(Light::Directional { color, intensity, .. }))) => (-m.transform_vector3(Vec3::NEG_Z).normalize(), Vec3::from(*color) * *intensity),
@@ -1406,6 +1407,7 @@ pub fn sky_data(w: &World, assets: &Path, matrix: &dyn Fn(u32) -> Mat4) -> Resul
ground: Vec3::from(*ground_albedo),
dynamic: *dynamic,
glow: crate::sky::glow_of(glow, horizon_glow),
+ altitude: altitude.filter(|a| a.is_finite()).map(|a| a.max(0.0)),
}
}
Sky::Color { color, intensity, .. } if *intensity > 0.0 => SkyData::Color(Vec3::from(*color) * *intensity),
@@ -2142,11 +2144,14 @@ pub fn camera_data(m: Mat4, c: &desc::Camera) -> CameraData {
}
}
-/// `Params::aerial` for a sky: [density multiple, Rayleigh scale, Mie scale, 0] for an atmosphere with aerial perspective,
-/// zeros otherwise (no F_AERIAL).
+/// `Params::aerial` for a sky: [density multiple, Rayleigh scale, Mie scale, a planet's viewer altitude] for an
+/// atmosphere with aerial perspective, zeros otherwise (no F_AERIAL). The altitude (m, at least 1 mm) turns the
+/// kernel's haze to the planet's sphere (pathtrace.wgsl `aerial_planet`); 0: a flat world's.
pub fn aerial_params(sky: &Sky) -> [f32; 4] {
match sky {
- Sky::Atmosphere { aerial, rayleigh_scale, mie_scale, .. } if *aerial > 0.0 => [*aerial, *rayleigh_scale, *mie_scale, 0.0],
+ Sky::Atmosphere { aerial, rayleigh_scale, mie_scale, altitude, .. } if *aerial > 0.0 => {
+ [*aerial, *rayleigh_scale, *mie_scale, altitude.filter(|a| a.is_finite()).map_or(0.0, |a| a.max(1e-3))]
+ }
_ => [0.0; 4],
}
}
diff --git a/renderer/src/sky.rs b/renderer/src/sky.rs
index 90a34a2..3f2f7aa 100644
--- a/renderer/src/sky.rs
+++ b/renderer/src/sky.rs
@@ -560,10 +560,25 @@ impl Luts {
/// The sky's radiance per unit of the sun's illuminance above the atmosphere (sr^-1, RGB), seen from
/// `altitude_km` above the ground in direction `dir`, the sun in direction `sun` (both unit, planet frame: Z up);
/// without the sun's disk, with multiple scattering and the ground's bounce.
+ /// A viewer above the atmosphere's top sees the air from where the ray enters it, and black space where it does
+ /// not.
fn sky(&self, a: &Atmosphere, altitude_km: f32, dir: Vec3, sun: Vec3) -> Vec3 {
- let r = (R_GROUND + altitude_km.max(0.0) as f64).min(R_TOP - 1e-3);
- let (mu, mu_sun) = ((dir.z as f64).clamp(-1.0, 1.0), (sun.z as f64).clamp(-1.0, 1.0));
+ let r0 = R_GROUND + altitude_km.max(0.0) as f64;
+ let (mu0, mu_sun0) = ((dir.z as f64).clamp(-1.0, 1.0), (sun.z as f64).clamp(-1.0, 1.0));
let nu = (dir.dot(sun) as f64).clamp(-1.0, 1.0);
+ let top = R_TOP - 1e-3;
+ let (r, mu, mu_sun) = if r0 <= top {
+ (r0, mu0, mu_sun0)
+ } else {
+ // The near crossing of the top's sphere; the ray's zenith cosines (its own, the sun's) there.
+ let disc = r0 * r0 * (mu0 * mu0 - 1.0) + top * top;
+ if mu0 >= 0.0 || disc <= 0.0 {
+ return Vec3::ZERO;
+ }
+ let t = -r0 * mu0 - disc.sqrt();
+ let r = (r0 * r0 + t * t + 2.0 * r0 * mu0 * t).sqrt();
+ (r, ((r0 * mu0 + t) / r).clamp(-1.0, 1.0), ((r0 * mu_sun0 + t * nu) / r).clamp(-1.0, 1.0))
+ };
let (ray, lands) = Ray::new(r, mu, mu_sun, nu);
let (by_air, by_haze) = (Atmosphere::phase_rayleigh(nu), a.phase_mie(nu) * a.mie_scattering);
// Equation 11 of Hillaire 2020: at each point the sun's light scattered once toward the viewer, by the air's
@@ -594,6 +609,20 @@ pub struct SkyBake {
pub texels: Vec<[f32; 4]>,
/// Sun illuminance reaching the ground (lux, RGB), i.e. E_sun * T(ground -> sun).
pub sun_illuminance: Vec3,
+ /// A planet's bake (`Horizon::Planet`): the texture's v at the centre of the row the dipped horizon crosses, the
+ /// limb's row, where the aerial perspective reads the air's light (pathtrace.wgsl `aerial_light`); 0 otherwise.
+ pub horizon_v: f32,
+}
+
+/// Where the bake's sky ends below.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Horizon {
+ /// A flat world's (a scene's ground plane): the level direction, faded as UE's sky light cube fades it.
+ Level,
+ /// A planet's (`SkyAtmosphere.altitude`: the scene's ground is the globe): the horizon dips with the viewer's
+ /// altitude (19.8 degrees at 400 km), black below it, the texel row it crosses covered in proportion (its alpha:
+ /// the share, so that the limb's own radiance can be read back, `SkyBake::horizon_v`).
+ Planet,
}
/// The sky's size when its sun moves (`desc::Sky::Atmosphere::dynamic`): a bake takes ~1.5 ms of all cores here (~8 ms
@@ -612,7 +641,7 @@ const SKY_LIGHT_CUBE: f32 = 128.0;
/// sky fades to black across one texel row of the side faces at the horizon (0.9 deg at a face's centre, 0.63 at its
/// edges). UE's path tracer shows that fade below every horizon (Khronos layer B: the band beyond a 2 km ground plane).
pub fn bake_atmosphere(a: &Atmosphere, sun_dir: Vec3, sun_lux: Vec3, altitude_m: f32, width: u32, height: u32) -> SkyBake {
- bake_atmosphere_with(a, &Luts::build(a), sun_dir, sun_lux, altitude_m, width, height, Glow::default(), 0.0)
+ bake_atmosphere_with(a, &Luts::build(a), sun_dir, sun_lux, altitude_m, width, height, Glow::default(), 0.0, Horizon::Level)
}
/// The atmosphere's transmittance and multiple-scattering tables: they depend on the atmosphere alone, so a sky whose
@@ -653,11 +682,11 @@ impl Glow {
}
}
-/// `bake_atmosphere` with tables built once (`SkyTables`), plus the night sky's `glow` above the horizon and a cloud
-/// `cover` (0..1, `overcast`).
+/// `bake_atmosphere` with tables built once (`SkyTables`), plus the night sky's `glow` above the horizon, a cloud
+/// `cover` (0..1, `overcast`) and where the sky ends below (`Horizon`).
#[allow(clippy::too_many_arguments)]
-pub fn bake_atmosphere_tables(a: &Atmosphere, t: &SkyTables, sun_dir: Vec3, sun_lux: Vec3, altitude_m: f32, width: u32, height: u32, glow: Glow, cover: f32) -> SkyBake {
- bake_atmosphere_with(a, &t.0, sun_dir, sun_lux, altitude_m, width, height, glow, cover)
+pub fn bake_atmosphere_tables(a: &Atmosphere, t: &SkyTables, sun_dir: Vec3, sun_lux: Vec3, altitude_m: f32, width: u32, height: u32, glow: Glow, cover: f32, horizon: Horizon) -> SkyBake {
+ bake_atmosphere_with(a, &t.0, sun_dir, sun_lux, altitude_m, width, height, glow, cover, horizon)
}
/// The sun's illuminance at the ground (lux, RGB) for a sun of `sun_lux` above the atmosphere under a cloud `cover`,
@@ -690,11 +719,13 @@ pub fn cie_overcast(e_h: Vec3, e: f32) -> Vec3 {
/// illuminance is OVERCAST_TRANSMITTANCE of what the clear sky and sun give the ground (their luminance, white), the
/// glow at OVERCAST_GLOW x.
#[allow(clippy::too_many_arguments)]
-fn bake_atmosphere_with(a: &Atmosphere, luts: &Luts, sun_dir: Vec3, sun_lux: Vec3, altitude_m: f32, width: u32, height: u32, glow: Glow, cover: f32) -> SkyBake {
+fn bake_atmosphere_with(a: &Atmosphere, luts: &Luts, sun_dir: Vec3, sun_lux: Vec3, altitude_m: f32, width: u32, height: u32, glow: Glow, cover: f32, horizon: Horizon) -> SkyBake {
// Planet frame: Z up. Map Y-up world -> planet frame (x, z, y).
let to_planet = |d: Vec3| Vec3::new(d.x, d.z, d.y);
let sun_p = to_planet(sun_dir).normalize();
let altitude_km = (altitude_m / 1000.0).max(0.005);
+ let row = PI / height as f32;
+ let dip = horizon_elevation(altitude_km);
let texels: Vec<[f32; 4]> = (0..(width * height) as usize)
.into_par_iter()
.map(|i| {
@@ -702,6 +733,20 @@ fn bake_atmosphere_with(a: &Atmosphere, luts: &Luts, sun_dir: Vec3, sun_lux: Vec
let theta = y / height as f32 * PI;
let phi = (x / width as f32 - 0.5) * 2.0 * PI;
let d = Vec3::new(theta.sin() * phi.sin(), theta.cos(), -theta.sin() * phi.cos());
+ if horizon == Horizon::Planet {
+ // The share of the texel's row above the dipped horizon; the sky at the row's centre, or just above
+ // the horizon where that is below it (the limb: the air seen edge on, its brightest).
+ let k = ((PI / 2.0 - theta + 0.5 * row - dip) / row).clamp(0.0, 1.0);
+ if k <= 0.0 {
+ return [0.0, 0.0, 0.0, 0.0];
+ }
+ let e = (PI / 2.0 - theta).max(dip + 1e-4);
+ let flat = Vec3::new(phi.sin(), 0.0, -phi.cos());
+ let dir = flat * e.cos() + Vec3::Y * e.sin();
+ let l = luts.sky(a, altitude_km, to_planet(dir), sun_p);
+ let l = (l * sun_lux + glow.at(e)) * k;
+ return [l.x, l.y, l.z, k];
+ }
// Texel rows above the horizon on the side face this direction falls on; within half a row of it the
// value blends the first row's centre with the black row below.
let side = d.x.abs().max(d.z.abs()).max(1e-6);
@@ -742,10 +787,86 @@ fn bake_atmosphere_with(a: &Atmosphere, luts: &Luts, sun_dir: Vec3, sun_lux: Vec
*t = [l.x, l.y, l.z, t[3]];
}
}
+ // (A planet's limb row keeps its share in alpha, `Horizon::Planet`.)
+ let planet = horizon == Horizon::Planet;
for t in &mut texels {
- t[3] = 1.0;
+ t[3] = if planet && t[3] > 0.0 { t[3] } else { 1.0 };
}
- SkyBake { width, height, texels, sun_illuminance: sun_illuminance(a, sun_dir, sun_lux, cover) }
+ // (The row the horizon's zenith angle falls in; on a row's edge, the row above it, wholly sky.)
+ let horizon_v = if planet { ((((PI / 2.0 - dip) / row).ceil() - 1.0).clamp(0.0, height as f32 - 1.0) + 0.5) / height as f32 } else { 0.0 };
+ SkyBake { width, height, texels, sun_illuminance: sun_illuminance(a, sun_dir, sun_lux, cover), horizon_v }
+}
+
+// ------------------------------------------------------------------------------------------------ aerial perspective
+//
+// The kernel's aerial perspective on a planet (pathtrace.wgsl `aerial_planet`, F_AERIAL with an altitude): the air's
+// columns along a segment over a sphere of radius R_GROUND, the viewer `altitude` above it and its centre straight
+// below the camera. This is its reference, line by line in single precision, which the tests hold to a quadrature.
+//
+// The column of a density exp(-h / H) from a point at altitude h, radius r = R + h, along a ray of zenith cosine
+// mu >= 0 to infinity is H exp(-h / H) Ch(x, mu), x = r / H, with Ch Chapman's grazing-incidence function (Chapman
+// 1931, "The absorption and ionising effect of monochromatic radiation in an atmosphere on a rotating earth"). With
+// the altitude along the ray to second order, h(s) = h + mu s + s^2 / (2 r), the integral is Gaussian:
+// Ch(x, mu) = sqrt(pi x / 2) erfcx(mu sqrt(x / 2)), erfcx(y) = exp(y^2) erfc(y) (1 at mu = 0, sqrt(pi x / 2) there,
+// and 1 / mu for a steep ray). erfcx is the bound of Abramowitz & Stegun 1964, 7.1.13, 2 / sqrt(pi) / (y +
+// sqrt(y^2 + 4 / pi)), with a term a y under the root that makes its slope at 0 exact (a = 4 (4 / pi - 1) / sqrt(pi):
+// a level ray's column then changes along it as the density, so that short level segments at the ground are right)
+// and a factor 1 + b y^2 / (1 + c y^3) (own fit, b = 0.0295, c = 0.312): within 0.42 % for y >= 0, where the bound
+// itself is 5.8 % off.
+// A segment from a to b is a difference of such columns: both ends' columns onward when the ray climbs all along it,
+// both ends' columns backward when it descends all along it, and when it passes its lowest point p between them,
+// twice p's level column less the two ends' outward ones.
+
+/// erfcx(y) = exp(y^2) erfc(y), y >= 0 (above).
+fn erfcx_approx(y: f32) -> f32 {
+ 1.128_379_2 / (y + (y * y + 0.616_635_6 * y + 1.273_239_5).sqrt()) * (1.0 + 0.0295 * y * y / (1.0 + 0.312 * y * y * y))
+}
+
+/// The column (m at sea-level density) from altitude `h` m along zenith cosine `mu` (>= 0) to infinity, scale height
+/// `scale` m.
+fn aerial_column(h: f32, mu: f32, scale: f32) -> f32 {
+ let x = (R_GROUND as f32 * 1000.0 + h) / scale;
+ scale * (-h.max(-500.0) / scale).exp() * (0.5 * PI * x).sqrt() * erfcx_approx(mu.max(0.0) * (0.5 * x).sqrt())
+}
+
+/// A point's altitude and the zenith cosine of direction `d` there: `q` the point less the camera, `h0` the camera's
+/// altitude (the planet's centre at (0, -(R + h0), 0) from the camera). Small terms first, so that the altitude keeps
+/// its precision a planet's radius from the centre.
+fn aerial_at(q: Vec3, d: Vec3, h0: f32) -> (f32, f32) {
+ let r0 = R_GROUND as f32 * 1000.0;
+ let up = q.y + h0;
+ let s2 = q.x * q.x + q.z * q.z;
+ let y = up + r0;
+ let r = (y * y + s2).sqrt();
+ (up + s2 / (r + y), (q.x * d.x + y * d.y + q.z * d.z) / r)
+}
+
+/// The air's and the haze's columns (m at sea-level density; scale heights 8 km and 1.2 km) from `q` (the point less
+/// the camera) along `d` for `t` m, the camera `h0` m above the planet.
+pub fn aerial_columns(q: Vec3, d: Vec3, t: f32, h0: f32) -> [f32; 2] {
+ let (ha, ma) = aerial_at(q, d, h0);
+ let (hb, mb) = aerial_at(q + d * t, d, h0);
+ // How far along the ray its lowest point is.
+ let r0 = R_GROUND as f32 * 1000.0;
+ let lowest = -(q.x * d.x + (q.y + h0 + r0) * d.y + q.z * d.z);
+ let (hp, _) = aerial_at(q + d * lowest.clamp(0.0, t), d, h0);
+ [8000.0, 1200.0].map(|scale| {
+ let od = if lowest <= 0.0 {
+ aerial_column(ha, ma, scale) - aerial_column(hb, mb, scale)
+ } else if lowest >= t {
+ aerial_column(hb, -mb, scale) - aerial_column(ha, -ma, scale)
+ } else {
+ 2.0 * aerial_column(hp, 0.0, scale) - aerial_column(ha, -ma, scale) - aerial_column(hb, mb, scale)
+ };
+ od.max(0.0)
+ })
+}
+
+/// The elevation of a planet's horizon (radians, negative: it dips) for a viewer `altitude_km` above the ground's
+/// sphere: -acos(R / (R + h)), as an arcsine that keeps its precision near the ground.
+pub fn horizon_elevation(altitude_km: f32) -> f32 {
+ let (r, h) = (R_GROUND, altitude_km.max(0.0) as f64);
+ (-(h * (2.0 * r + h)).sqrt() / (r + h)).asin() as f32
}
/// Analytic dome for night / overcast scenes (UE session: gradient + light-pollution glow + clouds as a sky light).
@@ -872,7 +993,7 @@ pub fn bake_gradient(g: &Gradient, width: u32, height: u32) -> SkyBake {
[l.x, l.y, l.z, 1.0]
})
.collect();
- SkyBake { width, height, texels, sun_illuminance: Vec3::ZERO }
+ SkyBake { width, height, texels, sun_illuminance: Vec3::ZERO, horizon_v: 0.0 }
}
#[cfg(test)]
@@ -885,8 +1006,8 @@ mod overcast_tests {
let t = SkyTables::new(&a);
let (sun, lux) = (Vec3::new(0.3, 0.5, -0.8).normalize(), Vec3::splat(100_000.0));
let (w, h) = (256u32, 128u32);
- let clear = bake_atmosphere_tables(&a, &t, sun, lux, 10.0, w, h, Glow::default(), 0.0);
- let oc = bake_atmosphere_tables(&a, &t, sun, lux, 10.0, w, h, Glow::default(), 1.0);
+ let clear = bake_atmosphere_tables(&a, &t, sun, lux, 10.0, w, h, Glow::default(), 0.0, Horizon::Level);
+ let oc = bake_atmosphere_tables(&a, &t, sun, lux, 10.0, w, h, Glow::default(), 1.0, Horizon::Level);
let lum = |v: [f32; 4]| 0.2126 * v[0] + 0.7152 * v[1] + 0.0722 * v[2];
// Horizontal illuminance of a bake (+ its sun).
let e_h = |b: &SkyBake| -> f32 {
@@ -915,7 +1036,7 @@ mod overcast_tests {
assert!((c[0] - c[2]).abs() < 1e-3 * c[1], "{c:?}");
}
// Half cover: halfway in every texel, the sun at half.
- let half = bake_atmosphere_tables(&a, &t, sun, lux, 10.0, w, h, Glow::default(), 0.5);
+ let half = bake_atmosphere_tables(&a, &t, sun, lux, 10.0, w, h, Glow::default(), 0.5, Horizon::Level);
assert!((half.sun_illuminance - clear.sun_illuminance * 0.5).length() < 1e-3 * clear.sun_illuminance.length());
let k = (ten * w + 7) as usize;
assert!((lum(half.texels[k]) - 0.5 * (lum(clear.texels[k]) + lum(oc.texels[k]))).abs() < 1e-3 * lum(clear.texels[k]));
@@ -942,6 +1063,151 @@ mod atmosphere_tests {
0.2126 * v.x + 0.7152 * v.y + 0.0722 * v.z
}
+ /// From above the atmosphere (`SkyAtmosphere.altitude` up to low orbit): space is black, up and below the limb; the
+ /// limb, the air seen edge on just above the dipped horizon, is lit and blue by day; and the sky does not jump as the
+ /// viewer crosses the atmosphere's top.
+ #[test]
+ fn sky_from_space() {
+ let (a, luts) = (earth(), Luts::build(&earth()));
+ let sun = planet(40.0, 0.0);
+ let dip = horizon_elevation(400.0).to_degrees();
+ assert!((dip + 19.83).abs() < 0.05, "{dip}");
+ // The top's tangent from 400 km: acos(6460 / 6760) = 17.1 degrees down.
+ let top = -(R_TOP / (R_GROUND + 400.0)).acos().to_degrees() as f32;
+ for az in [0.0, 90.0, 180.0] {
+ assert_eq!(luts.sky(&a, 400.0, planet(90.0, az), sun), Vec3::ZERO);
+ assert_eq!(luts.sky(&a, 400.0, planet(top + 0.2, az), sun), Vec3::ZERO);
+ // Below the horizon the ray ends on the globe (the bake blacks it out: `Horizon::Planet`).
+ let limb = luts.sky(&a, 400.0, planet(dip + 0.1, az), sun);
+ assert!(luminance(limb) > 0.01 && limb.z > limb.x, "{az}: {limb:?}");
+ // Thinner higher up the limb.
+ let high = luts.sky(&a, 400.0, planet(dip + 1.5, az), sun);
+ assert!(luminance(high) < 0.5 * luminance(limb), "{az}: {high:?} {limb:?}");
+ }
+ // Across the top: 99.9 and 100.1 km see the same sky (within the change 200 m of height makes).
+ for (e, az) in [(90.0, 0.0), (10.0, 0.0), (-5.0, 180.0), (-10.2, 90.0)] {
+ let (below, above) = (luts.sky(&a, 99.9, planet(e, az), sun), luts.sky(&a, 100.1, planet(e, az), sun));
+ let tol = 0.03 * luminance(below).max(luminance(above)) + 1e-6;
+ assert!((luminance(below) - luminance(above)).abs() <= tol, "{e} {az}: {below:?} {above:?}");
+ }
+ }
+
+ /// A planet's bake: black below the dipped horizon and in space above the limb, the limb's row covered in
+ /// proportion with its share in alpha (`SkyBake::horizon_v`), so that the air's light reads back whole.
+ #[test]
+ fn planet_bake_dips_its_horizon() {
+ let a = earth();
+ let t = SkyTables::new(&a);
+ let (w, h) = DYNAMIC_SKY;
+ for altitude_km in [0.002f32, 10.0, 400.0, 2000.0] {
+ let b = bake_atmosphere_tables(&a, &t, sun_at(30.0), Vec3::splat(120_000.0), altitude_km * 1000.0, w, h, Glow::default(), 0.0, Horizon::Planet);
+ let dip = horizon_elevation(altitude_km.max(0.005));
+ let row_of = |v: f32| (v * h as f32).floor() as u32;
+ let limb = row_of(b.horizon_v);
+ let elevation = |y: u32| PI / 2.0 - (y as f32 + 0.5) / h as f32 * PI;
+ assert!(elevation(limb) - 0.5 * PI / h as f32 <= dip + 1e-5 && dip < elevation(limb) + 0.5 * PI / h as f32 + 1e-5, "{altitude_km}: row {limb}");
+ for y in 0..h {
+ let row = &b.texels[(y * w) as usize..((y + 1) * w) as usize];
+ let lum: f32 = row.iter().map(|t| 0.2126 * t[0] + 0.7152 * t[1] + 0.0722 * t[2]).sum::<f32>() / w as f32;
+ if y > limb {
+ assert_eq!(lum, 0.0, "{altitude_km}: row {y} below the horizon");
+ } else if y == limb {
+ assert!(lum > 0.0 && row.iter().all(|t| t[3] > 0.0 && t[3] <= 1.0), "{altitude_km}: the limb's row");
+ } else {
+ assert!(row.iter().all(|t| t[3] == 1.0));
+ }
+ // Above the top's tangent from orbit: space.
+ if altitude_km > 100.0 && elevation(y) > -(R_TOP / (R_GROUND + altitude_km as f64)).acos() as f32 + 0.03 {
+ assert_eq!(lum, 0.0, "{altitude_km}: row {y} in space");
+ }
+ }
+ // Read back whole: the limb row's light over its share is the sky just above the horizon.
+ let i = (limb * w + w / 2) as usize;
+ let back = Vec3::new(b.texels[i][0], b.texels[i][1], b.texels[i][2]) / b.texels[i][3];
+ assert!(back.z > 0.0, "{altitude_km}: {back:?}");
+ }
+ // The flat world's bake is as it was: alpha 1, black from just under the level horizon.
+ let flat = bake_atmosphere_tables(&a, &t, sun_at(30.0), Vec3::ONE, 400_000.0, w, h, Glow::default(), 0.0, Horizon::Level);
+ assert!(flat.horizon_v == 0.0 && flat.texels.iter().all(|t| t[3] == 1.0));
+ }
+
+ /// The kernel's haze on a planet (pathtrace.wgsl `aerial_light`): (1 - T) of the limb's radiance in the ray's
+ /// azimuth (the bake's limb row), against the medium's own light scattered toward a viewer 10-400 km up along rays
+ /// that end on the ground (the sky's march over a black ground): within 0.5-1.8 x (in luminance): over where the limb is
+ /// toward the sun (the haze's forward peak) and the ray steep, under for rays that graze the globe near its horizon from orbit.
+ #[test]
+ fn planet_haze_is_the_airs_light() {
+ let a = Atmosphere::earth(1.0, 1.0, 0.8, Vec3::ZERO);
+ let luts = Luts::build(&a);
+ let sun = planet(30.0, 0.0);
+ for h in [10.0f32, 100.0, 400.0] {
+ let dip = horizon_elevation(h).to_degrees();
+ for az in [0.0f32, 90.0, 180.0] {
+ let limb = luts.sky(&a, h, planet(dip + 0.05, az), sun);
+ for e in [-90.0f32, -60.0, -30.0, dip - 2.0] {
+ let d = planet(e, az);
+ let air = luts.sky(&a, h, d, sun);
+ let r = (R_GROUND + h as f64).min(R_TOP - 1e-3);
+ let (_, t) = Luts::march(&a, Ray::new(r, d.z as f64, sun.z as f64, d.dot(sun) as f64).0, 64, |_, _, _| [0.0; 3]);
+ let haze = Vec3::new(1.0 - t[0] as f32, 1.0 - t[1] as f32, 1.0 - t[2] as f32) * limb;
+ let ratio = luminance(haze) / luminance(air);
+ assert!((0.5..1.8).contains(&ratio), "{h} km, azimuth {az}, elevation {e}: {haze:?} against {air:?}");
+ }
+ }
+ }
+ }
+
+ /// The air's columns along a path over the planet (`aerial_columns`, the kernel's `aerial_planet`) against a
+ /// quadrature of the densities over the exact sphere: from the street to 2,000 km up, segments of 10 m to the
+ /// globe's far side, climbing, descending and passing their lowest point.
+ #[test]
+ fn aerial_columns_over_the_planet() {
+ let r = R_GROUND * 1000.0;
+ let exact = |h0: f64, q: glam::DVec3, d: glam::DVec3, t: f64| -> [f64; 2] {
+ let c = glam::DVec3::new(0.0, -(r + h0), 0.0);
+ let n = 200_000;
+ [8000.0, 1200.0].map(|scale| {
+ let f = |s: f64| (-(((q + d * s) - c).length() - r).max(-500.0) / scale).exp();
+ let hstep = t / n as f64;
+ let mut sum = f(0.0) + f(t);
+ for i in 1..n {
+ sum += f(i as f64 * hstep) * if i % 2 == 1 { 4.0 } else { 2.0 };
+ }
+ sum * hstep / 3.0
+ })
+ };
+ // Blue Rayleigh and Mie extinction at sea level (per m).
+ let tr = |c: [f64; 2]| (-(33.1e-6 * c[0] + 4.44e-6 * c[1])).exp();
+ let mut worst = 0.0f64;
+ for h0 in [2.0f64, 300.0, 3000.0, 12_000.0, 100_000.0, 400_000.0, 2_000_000.0] {
+ for elevation in [-90.0f64, -60.0, -30.0, -10.0, -3.0, -1.0, 0.0, 1.0, 5.0, 30.0] {
+ let e = elevation.to_radians();
+ let d = glam::DVec3::new(e.cos() * 0.6, e.sin(), -e.cos() * 0.8);
+ for q in [glam::DVec3::ZERO, glam::DVec3::new(3000.0, -h0.min(2000.0) * 0.5, 1000.0)] {
+ // To the ground, or this far.
+ let c = glam::DVec3::new(0.0, -(r + h0), 0.0);
+ let oc = q - c;
+ let b = oc.dot(d);
+ let disc = b * b - (oc.length_squared() - r * r);
+ let ground = if disc > 0.0 && -b - disc.sqrt() > 0.0 { Some(-b - disc.sqrt()) } else { None };
+ for t in [10.0f64, 1000.0, 10_000.0, 100_000.0, 1_000_000.0, 3_000_000.0] {
+ let t = ground.map_or(t, |g| t.min(g));
+ let (want, got) = (exact(h0, q, d, t), aerial_columns(q.as_vec3(), d.as_vec3(), t as f32, h0 as f32));
+ let got = [got[0] as f64, got[1] as f64];
+ let err = (tr(want) - tr(got)).abs();
+ worst = worst.max(err);
+ assert!(err < 0.005, "h0 {h0} e {elevation} q {q} t {t}: exact {want:?} model {got:?} (transmittance {} / {})", tr(want), tr(got));
+ }
+ }
+ }
+ }
+ println!("aerial columns: transmittance within {worst:.4}");
+ // From 400 km the air thins out: straight down, three quarters of the blue light comes through (the flat
+ // model with the camera at y = 0 has the whole 400 km at sea-level density: none).
+ let down = aerial_columns(Vec3::ZERO, Vec3::NEG_Y, 400_000.0, 400_000.0);
+ assert!((0.7..0.8).contains(&tr([down[0] as f64, down[1] as f64])), "{down:?}");
+ }
+
#[test]
fn fast_exponential() {
let mut worst = (0.0f64, 0.0f64);
@@ -1160,7 +1426,7 @@ mod atmosphere_tests {
let t = SkyTables::new(&a);
let (w, h) = DYNAMIC_SKY;
for elevation in [60.0f32, 10.0, 2.0, -3.0] {
- let bake = bake_atmosphere_tables(&a, &t, sun_at(elevation), Vec3::ONE, 0.0, w, h, Glow::default(), 0.0);
+ let bake = bake_atmosphere_tables(&a, &t, sun_at(elevation), Vec3::ONE, 0.0, w, h, Glow::default(), 0.0, Horizon::Level);
assert!(bake.texels.iter().all(|t| t.iter().all(|v| v.is_finite() && *v >= 0.0)));
// (The sun is at u = 0.75: the meridians a quarter turn from it and opposite it.)
for column in [0, w / 4, w / 2] {
@@ -1473,14 +1739,14 @@ mod atmosphere_tests {
println!("{name}: tables (SkyTables::new) {:.1} ms", best(15, &|| { SkyTables::new(&a); }));
let t = SkyTables::new(&a);
for e in [60.0, 10.0, -3.0] {
- println!("{name}: bake_atmosphere_tables, sun at {e:3}: 256 x 128 {:.1} ms, 1024 x 512 {:.1} ms", best(15, &|| { bake_atmosphere_tables(&a, &t, sun_at(e), Vec3::ONE, 0.0, 256, 128, Glow::default(), 0.0); }), best(5, &|| { bake_atmosphere_tables(&a, &t, sun_at(e), Vec3::ONE, 0.0, 1024, 512, Glow::default(), 0.0); }));
+ println!("{name}: bake_atmosphere_tables, sun at {e:3}: 256 x 128 {:.1} ms, 1024 x 512 {:.1} ms", best(15, &|| { bake_atmosphere_tables(&a, &t, sun_at(e), Vec3::ONE, 0.0, 256, 128, Glow::default(), 0.0, Horizon::Level); }), best(5, &|| { bake_atmosphere_tables(&a, &t, sun_at(e), Vec3::ONE, 0.0, 1024, 512, Glow::default(), 0.0, Horizon::Level); }));
}
};
run("all cores");
rayon::ThreadPoolBuilder::new().num_threads(3).build().unwrap().install(|| run("3 threads"));
rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap().install(|| {
let t = SkyTables::new(&a);
- let small = best(300, &|| { bake_atmosphere_tables(&a, &t, sun_at(10.0), Vec3::ONE, 0.0, 64, 32, Glow::default(), 0.0); });
+ let small = best(300, &|| { bake_atmosphere_tables(&a, &t, sun_at(10.0), Vec3::ONE, 0.0, 64, 32, Glow::default(), 0.0, Horizon::Level); });
println!("one thread: 64 x 32 {small:.3} ms, so 256 x 128 is {:.1} ms of one core and 1024 x 512 {:.0} ms; tables {:.0} ms of one core", small * 16.0, small * 256.0, best(5, &|| { SkyTables::new(&a); }));
});
}
diff --git a/renderer/src/world.rs b/renderer/src/world.rs
index 6a3608f..a20a0ea 100644
--- a/renderer/src/world.rs
+++ b/renderer/src/world.rs
@@ -304,6 +304,9 @@ pub struct Changes {
pub sun: bool,
/// Another sky (its kind or its parameters): baked and put in place (live/edits.rs `apply_sky`). With `environment`.
pub sky: bool,
+ /// A planet's viewer altitude, the sky otherwise the same (`desc::Sky::Atmosphere::altitude`): re-baked in place
+ /// past a step (live/edits.rs `move_altitude`). With `environment`.
+ pub altitude: bool,
/// The scene camera's depth of field or exposure changed: the view's state, taken again in place (live/edits.rs
/// `apply_view`). Not `camera`: a view its host moved stays where it is.
pub view: bool,
@@ -342,7 +345,7 @@ pub struct Changes {
impl Changes {
pub fn any(&self) -> bool {
- self.structural || !self.shown.is_empty() || !self.new_materials.is_empty() || !self.materials.is_empty() || !self.textures.is_empty() || self.functions || self.volume_functions || self.media || !self.lights.is_empty() || !self.powers.is_empty() || !self.customs.is_empty() || self.environment || self.camera || self.sun || self.view || self.settings || !self.poses.is_empty() || !self.moved.is_empty() || !self.instanced.is_empty() || self.edits()
+ self.structural || !self.shown.is_empty() || !self.new_materials.is_empty() || !self.materials.is_empty() || !self.textures.is_empty() || self.functions || self.volume_functions || self.media || !self.lights.is_empty() || !self.powers.is_empty() || !self.customs.is_empty() || self.environment || self.altitude || self.camera || self.sun || self.view || self.settings || !self.poses.is_empty() || !self.moved.is_empty() || !self.instanced.is_empty() || self.edits()
}
/// Geometry edits are pending (`geometries`, `added`, `removed`).
pub fn edits(&self) -> bool {
@@ -1113,7 +1116,22 @@ impl World {
pub fn set_environment(&mut self, e: desc::Environment) {
// Fog appearing, turning volumetric or going, and a background appearing or going, are kernel features: another
// variant of the kernel, not another scene. Another sky is another environment map.
- self.changes.sky |= self.environment.sky != e.sky;
+ // (A planet's viewer altitude alone re-bakes in place: live/edits.rs `move_altitude`.)
+ let same_but_altitude = match (&self.environment.sky, &e.sky) {
+ (desc::Sky::Atmosphere { altitude: Some(_), .. }, desc::Sky::Atmosphere { altitude: Some(now), .. }) => {
+ let mut was = self.environment.sky.clone();
+ if let desc::Sky::Atmosphere { altitude, .. } = &mut was {
+ *altitude = Some(*now);
+ }
+ was == e.sky
+ }
+ _ => false,
+ };
+ if same_but_altitude {
+ self.changes.altitude |= self.environment.sky != e.sky;
+ } else {
+ self.changes.sky |= self.environment.sky != e.sky;
+ }
self.changes.environment = true;
self.environment = e;
}