Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(verse): real Earth in orbit outside the ship's viewports (#976)

Ruben Lütke932641f35f3d
diff --git a/docs/verse/realtime.md b/docs/verse/realtime.md
index a9346ba1e8..0c10bc2822 100644
--- a/docs/verse/realtime.md
+++ b/docs/verse/realtime.md
@@ -171,6 +171,7 @@ Code: `src/components/society/verse/engine/realtime/`.
| `orbitInput.ts` | Mouse: a click on the view takes the mouse (pointer lock); then movement turns the view and the left button works what the crosshair is on; Esc gives it back (the HUD's buttons work again). A drag still turns the view where the lock is refused. Touch and pen: drag turns, pinch zooms, a tap picks. The wheel zooms through the stage, which hands over between third and first person. |
| `viewSettings.ts` | The person's settings, kept in this browser: sensitivity, inverted look, field of view per person, quality, and the view they last chose. |
| `eyePick.ts` | Pointer picking at eye level: bodies as upright cylinders (only in front of the deck's geometry), stations near the deck point hit, floor points to walk to. |
+| `spaceView.ts`, `spaceShader.ts` | Outside the hull: the Earth, the sun and the stars behind the deck (below). |
The first-person viewmodel (the commander's own arms and, in a duel, the
blaster) lives in `src/components/society/verse/viewmodel/` (below).
@@ -227,6 +228,41 @@ measures it (read every frame; unset, the built-in values apply). Tune
against Cycles renders from the same camera (`SHOULDER` numbers; ceiling
ghosts visible), then move the values into the code.
+### Outside the hull
+
+The deck's baked star cards (`*Starfield` materials) are hidden at eye level;
+every viewport looks into real space instead, drawn first into the same HDR
+target (`SpacePass` before the deck's `RenderPass`, which then keeps the
+colour and clears only depth), so bloom and AgX treat it like the deck.
+
+- **Camera.** Its own camera at the origin turns with the deck camera and
+ never moves: the planet is thousands of kilometres away, so walking past a
+ window changes the angle, never the parallax. Lengths are Earth radii.
+- **Earth.** One full-screen triangle (`spaceShader.ts`): per pixel the view
+ ray is intersected with the true spheres of the ground, the cloud layer
+ (11 km up, so clouds float over the ground and stand out on the limb) and
+ the atmosphere. Ground: Blue Marble colour (July), terrain slope from GEBCO
+ elevation, sun glint (GGX) on open water, Black Marble city lights on the
+ night side, cloud shadows. Atmosphere: single scattering, Rayleigh + Mie,
+ 12 + 12 view samples crowded towards the ray's lowest point and 6 towards
+ the sun; it reddens the terminator and draws the blue limb and the haze over
+ the ground by itself. Sunlight is white-balanced to the zenith sun, as a
+ camera on the ship would see it. Output is premultiplied: the ground is
+ opaque, the thin air over open space only dims the stars.
+- **Placement.** `outwardOf` takes the viewports' direction from the deck's
+ middle, weighted by window area (the bridge's forward band, not its aft
+ portholes). The Earth sits below and ahead of it, turned so the chosen
+ place faces the windows, and turns under the ship at twice orbital speed.
+- **Look.** `SPACE_LOOK` (altitude, how far below the horizon, horizon tilt,
+ place, sun direction, gains, speed). QA hook: `window.__verseSpace =
+ { ...SpaceLook }` overrides it per frame (`planet: 0` drops the planet
+ pass; `outward: [x, z]` forces the direction);
+ `window.__verseSpaceState` says whether the textures arrived.
+- **Textures** (`public/verse/space/`, 11 MB, NASA imagery in the public
+ domain) are baked by `python scripts/verse/earth.py --src <dir> --fetch`:
+ day 8192 (sRGB), clouds 8192 (single channel), night lights and relief
+ 4096. A GPU with a smaller texture limit gets them scaled down on load.
+
### Views
Three views (`viewMode.ts`), switched on the tool rail's three-part control
diff --git a/dodaios/ui/web/frontend/public/verse/space/earth_clouds.webp b/dodaios/ui/web/frontend/public/verse/space/earth_clouds.webp
new file mode 100644
index 0000000000..bf11bd0241
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/space/earth_clouds.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/space/earth_day.webp b/dodaios/ui/web/frontend/public/verse/space/earth_day.webp
new file mode 100644
index 0000000000..b89fe7e511
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/space/earth_day.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/space/earth_night.webp b/dodaios/ui/web/frontend/public/verse/space/earth_night.webp
new file mode 100644
index 0000000000..22b915d45f
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/space/earth_night.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/space/earth_relief.webp b/dodaios/ui/web/frontend/public/verse/space/earth_relief.webp
new file mode 100644
index 0000000000..838b6331c3
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/space/earth_relief.webp differ
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/RealtimeBackdrop.tsx b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/RealtimeBackdrop.tsx
index 1530c3aa82..56610a00da 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/RealtimeBackdrop.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/RealtimeBackdrop.tsx
@@ -8,6 +8,9 @@
* commander's own arms (`runtime.viewmodel`) are drawn last, into the same
* target with depth cleared.
*
+ * Behind the deck: the Earth, the sun and the stars (`spaceView`), drawn
+ * first into the same target, so every viewport looks into real space.
+ *
* Quality tiers: "high" (bloom, 4x MSAA, full resolution) by default; when
* frames stay slower than ~45 fps the view drops to "low" (no post chain,
* pixel ratio at most 1) for weak GPUs. The person can pin either tier in
@@ -33,6 +36,7 @@ import { loadRealtimeScene, type RealtimeScene } from "./realtimeScene";
import { DECK_SHARED } from "./deckMaterial";
import { verticalFov, type SegmentTest } from "./shoulderRig";
import type { QualityChoice } from "./viewSettings";
+import { SpacePass, SpaceView, spaceTextureUrls } from "./spaceView";
import { viewmodelVisibility } from "../../viewmodel/motion";
import { drawViewmodel, ViewmodelPass } from "../../viewmodel/viewmodelPass";
@@ -149,10 +153,33 @@ export function RealtimeBackdrop({ runtime, deck, active, commanderId, quality =
return c;
}, []);
+ // Space outside the hull: one view for the stage's life, the Earth's textures load in the background.
+ const space = useMemo(() => new SpaceView(12), []);
+ useEffect(() => {
+ const abort = new AbortController();
+ space.load(gl, spaceTextureUrls(import.meta.env.BASE_URL), abort.signal).catch((error: unknown) => {
+ // Without its textures the view keeps the stars and the sun; the deck is unaffected.
+ if (abort.signal.aborted) return;
+ space.state.error = String(error);
+ console.warn("Verse space textures unavailable", error);
+ });
+ // Read by QA runs against built bundles.
+ Object.assign(window, { __verseSpaceState: space.state });
+ return () => { abort.abort(); space.dispose(); };
+ }, [gl, space]);
+ useEffect(() => {
+ if (loaded?.outward) space.setOutward(loaded.outward);
+ }, [loaded, space]);
+
const { composer, bloom, viewmodelPass } = useMemo(() => {
const target = new WebGLRenderTarget(1, 1, { type: HalfFloatType, samples: 4 });
const c = new EffectComposer(gl, target);
- c.addPass(new RenderPass(scene, camera));
+ const spacePass = new SpacePass();
+ spacePass.view = space;
+ c.addPass(spacePass);
+ const deckPass = new RenderPass(scene, camera);
+ deckPass.clear = false;
+ c.addPass(deckPass);
// First person: the commander's arms over the deck, before bloom and tone mapping like everything else.
const vm = new ViewmodelPass();
c.addPass(vm);
@@ -160,7 +187,7 @@ export function RealtimeBackdrop({ runtime, deck, active, commanderId, quality =
c.addPass(pass);
c.addPass(new OutputPass());
return { composer: c, bloom: pass, viewmodelPass: vm };
- }, [gl, scene, camera]);
+ }, [gl, scene, camera, space]);
useEffect(() => () => composer.dispose(), [composer]);
useEffect(() => {
@@ -246,6 +273,7 @@ export function RealtimeBackdrop({ runtime, deck, active, commanderId, quality =
if (Math.abs(camera.fov - fov) > 1e-3) { camera.fov = fov; camera.updateProjectionMatrix(); }
}
camera.updateMatrixWorld();
+ space.update(camera, dt, gl.getPixelRatio());
const vm = runtime.viewmodel;
vm?.prepare(camera, dt, scene.environment as Texture | null);
viewmodelPass.draw = vm;
@@ -264,7 +292,10 @@ export function RealtimeBackdrop({ runtime, deck, active, commanderId, quality =
composer.render(dt);
} else {
gl.setRenderTarget(null);
+ space.render(gl);
+ gl.autoClear = false;
gl.render(scene, camera);
+ gl.autoClear = true;
if (vm?.visible) drawViewmodel(gl, vm, null);
}
gl.setClearColor(clearColour, clearAlpha);
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/realtimeScene.ts b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/realtimeScene.ts
index a58e7ab8d4..3b0cbdb954 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/realtimeScene.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/realtimeScene.ts
@@ -11,7 +11,7 @@
* into a half-float equirect and prefiltered with PMREM.
*/
import {
- BufferAttribute, BufferGeometry, Group, HalfFloatType, LinearFilter, LinearMipmapLinearFilter, Mesh, NoColorSpace,
+ Box3, BufferAttribute, BufferGeometry, Group, HalfFloatType, LinearFilter, LinearMipmapLinearFilter, Mesh, NoColorSpace,
OrthographicCamera, PlaneGeometry, PMREMGenerator, RGBAFormat, Scene, ShaderMaterial, Texture, Vector3, WebGLRenderTarget,
type Material, type WebGLRenderer,
} from "three";
@@ -29,6 +29,11 @@ export interface RealtimeScene {
materials: readonly Material[];
/** World-space collision of the solid chunks, or null when there are none. */
collider: MeshBVH | null;
+ /**
+ * Which way the deck's viewports look out (world, horizontal, from the
+ * deck's middle), or null for a deck without any.
+ */
+ outward: Vector3 | null;
/** Draw chunks and triangles, for the stats. */
chunks: number;
triangles: number;
@@ -155,6 +160,44 @@ function buildCollider(meshes: readonly Mesh[]): MeshBVH | null {
return new MeshBVH(geometry);
}
+/** Area of a mesh's triangles, world space. */
+function meshArea(mesh: Mesh): number {
+ const position = mesh.geometry.getAttribute("position");
+ const index = mesh.geometry.index;
+ const count = index ? index.count : position.count;
+ const a = new Vector3();
+ const b = new Vector3();
+ const c = new Vector3();
+ let area = 0;
+ for (let i = 0; i + 2 < count; i += 3) {
+ a.fromBufferAttribute(position, index ? index.getX(i) : i).applyMatrix4(mesh.matrixWorld);
+ b.fromBufferAttribute(position, index ? index.getX(i + 1) : i + 1).applyMatrix4(mesh.matrixWorld);
+ c.fromBufferAttribute(position, index ? index.getX(i + 2) : i + 2).applyMatrix4(mesh.matrixWorld);
+ area += b.sub(a).cross(c.sub(a)).length() / 2;
+ }
+ return area;
+}
+
+/**
+ * Where the viewports look out, level: from the middle of the deck towards
+ * each window, weighted by its area, so the big forward viewports win over a
+ * small porthole at the back.
+ */
+export function outwardOf(group: Group, windows: readonly Mesh[]): Vector3 | null {
+ if (!windows.length) return null;
+ const deck = new Box3().setFromObject(group).getCenter(new Vector3());
+ const out = new Vector3();
+ const centre = new Vector3();
+ for (const mesh of windows) {
+ new Box3().setFromObject(mesh).getCenter(centre).sub(deck);
+ centre.y = 0;
+ if (centre.lengthSq() < 1e-6) continue;
+ out.addScaledVector(centre.normalize(), meshArea(mesh));
+ }
+ out.y = 0;
+ return out.lengthSq() > 1e-9 ? out.normalize() : null;
+}
+
export async function loadRealtimeScene(gl: WebGLRenderer, content: RealtimeContent, signal: AbortSignal): Promise<RealtimeScene> {
const loader = new GLTFLoader();
loader.setMeshoptDecoder(MeshoptDecoder);
@@ -191,6 +234,8 @@ export async function loadRealtimeScene(gl: WebGLRenderer, content: RealtimeCont
group.name = "verse-realtime";
const unused: Material[] = [];
const order = depthOrder(Object.keys(content.materials));
+ // The baked star cards behind the viewports give way to the real sky (spaceView); the glass shows where they are.
+ const windows: Record<"stars" | "viewport" | "clear", Mesh[]> = { stars: [], viewport: [], clear: [] };
group.traverse((object) => {
const mesh = object as Mesh;
if (!mesh.isMesh) return;
@@ -201,6 +246,13 @@ export async function loadRealtimeScene(gl: WebGLRenderer, content: RealtimeCont
mesh.visible = false;
return;
}
+ if (/Starfield/.test(info.material)) {
+ windows.stars.push(mesh);
+ mesh.visible = false;
+ return;
+ }
+ if (/Glass_Viewport/.test(info.material)) windows.viewport.push(mesh);
+ else if (/Glass_Clear/.test(info.material)) windows.clear.push(mesh);
const key = `${info.material}|${info.room}|${info.page}`;
let material = materials.get(key);
if (!material) {
@@ -221,6 +273,7 @@ export async function loadRealtimeScene(gl: WebGLRenderer, content: RealtimeCont
const collider = buildCollider(solid);
return {
group,
+ outward: outwardOf(group, windows.stars.length ? windows.stars : windows.viewport.length ? windows.viewport : windows.clear),
materials: [...materials.values()],
collider,
chunks,
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/spaceShader.ts b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/spaceShader.ts
new file mode 100644
index 0000000000..a5dadca51f
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/spaceShader.ts
@@ -0,0 +1,234 @@
+/**
+ * The planet behind the viewports, drawn per pixel on a full-screen triangle
+ * (docs/verse/realtime.md, "Outside the hull"). The camera sits at the origin
+ * of a space where the Earth's radius is 1; every ray is intersected with the
+ * true spheres of the ground, the cloud layer and the atmosphere, so the limb
+ * is exact at any zoom and the clouds float above the ground.
+ *
+ * Light: the sun's radiance reaches each point through the atmosphere
+ * (Rayleigh + Mie, marched), which reddens the terminator by itself; the
+ * view ray gathers the same in-scattering on its way, which gives the blue
+ * limb and the haze over the ground. Output is premultiplied: the ground is
+ * opaque, the thin atmosphere over open space only dims the stars behind it.
+ */
+
+export const SPACE_VERTEX = /* glsl */ `
+uniform mat4 verseInvViewProj;
+varying vec3 vDir;
+void main() {
+ vec4 far = verseInvViewProj * vec4( position.xy, 1.0, 1.0 );
+ vDir = far.xyz / far.w;
+ gl_Position = vec4( position.xy, 1.0, 1.0 );
+}
+`;
+
+export const SPACE_FRAGMENT = /* glsl */ `
+precision highp float;
+uniform vec3 earthCentre;
+uniform mat3 worldToEarth;
+uniform float spin;
+uniform float cloudSpin;
+uniform vec3 sunDir;
+uniform float sunRadiance;
+uniform float nightGain;
+uniform float hazeGain;
+uniform float ready;
+uniform sampler2D dayMap;
+uniform sampler2D nightMap;
+uniform sampler2D cloudMap;
+uniform sampler2D reliefMap;
+varying vec3 vDir;
+
+#ifndef VIEW_STEPS
+#define VIEW_STEPS 12
+#endif
+#define LIGHT_STEPS 6
+const float PI = 3.141592653589793;
+const float R_GROUND = 1.0;
+const float R_CLOUD = 1.0018;
+const float R_TOP = 1.0165;
+// Scale heights in Earth radii, a little taller than real so the limb reads at a glance.
+const float H_RAY = 0.00145;
+const float H_MIE = 0.00025;
+// Scattering per Earth radius (per-metre values x 6.371e6).
+const vec3 BETA_RAY = vec3( 36.9, 86.0, 210.9 );
+const float BETA_MIE = 133.8;
+const float MIE_EXT = 1.11;
+const float MIE_G = 0.76;
+
+vec2 sphere( vec3 d, float r ) {
+ float b = dot( earthCentre, d );
+ float c = dot( earthCentre, earthCentre ) - r * r;
+ float h = b * b - c;
+ if ( h < 0.0 ) return vec2( 1e9, -1e9 );
+ h = sqrt( h );
+ return vec2( b - h, b + h );
+}
+
+vec2 density( vec3 p ) {
+ float alt = max( length( p - earthCentre ) - R_GROUND, 0.0 );
+ return vec2( exp( -alt / H_RAY ), exp( -alt / H_MIE ) );
+}
+
+vec3 extinction( vec2 depth ) {
+ return exp( -( BETA_RAY * depth.x + BETA_MIE * MIE_EXT * depth.y ) );
+}
+
+// Optical depth from p towards the sun; the ground in the way puts it in shadow.
+vec2 sunDepth( vec3 p ) {
+ vec3 o = p - earthCentre;
+ float b = dot( o, sunDir );
+ float c = dot( o, o ) - R_TOP * R_TOP;
+ float far = -b + sqrt( max( b * b - c, 0.0 ) );
+ float cg = dot( o, o ) - R_GROUND * R_GROUND * 0.9995;
+ if ( b < 0.0 && b * b - cg > 0.0 ) return vec2( 1e4 );
+ vec2 depth = vec2( 0.0 );
+ float prev = 0.0;
+ for ( int i = 1; i <= LIGHT_STEPS; i++ ) {
+ float s = float( i ) / float( LIGHT_STEPS );
+ float t = far * s * s;
+ depth += density( p + sunDir * ( 0.5 * ( prev + t ) ) ) * ( t - prev );
+ prev = t;
+ }
+ return depth;
+}
+
+// White balance: sunlight through the atmosphere straight down reads neutral, as a camera on the ship would see it.
+vec3 sunAt( vec3 p ) {
+ vec3 zenith = extinction( vec2( H_RAY, H_MIE ) );
+ return extinction( sunDepth( p ) ) / zenith * sunRadiance;
+}
+
+vec2 equirect( vec3 local, float turn ) {
+ float lon = atan( -local.z, local.x ) - turn;
+ float u = lon / ( 2.0 * PI ) + 0.5;
+ float v = 0.5 - asin( clamp( local.y, -1.0, 1.0 ) ) / PI;
+ return vec2( u, v );
+}
+
+// Mip-safe sample across the longitude seam.
+vec4 seamless( sampler2D map, vec2 uv ) {
+ vec2 uv2 = vec2( fract( uv.x + 0.5 ) - 0.5, uv.y );
+ vec2 dx = dFdx( uv ), dy = dFdy( uv );
+ vec2 dx2 = dFdx( uv2 ), dy2 = dFdy( uv2 );
+ if ( abs( dx2.x ) + abs( dy2.x ) < abs( dx.x ) + abs( dy.x ) ) { dx = dx2; dy = dy2; }
+ return textureGrad( map, uv, dx, dy );
+}
+
+// A point on the sphere of radius r: the ray's hit, or where it passes closest (keeps derivatives smooth).
+vec3 onSphere( vec3 d, float r, vec2 hit ) {
+ vec3 p = hit.x < 1e8 ? d * hit.x : d * dot( earthCentre, d );
+ return earthCentre + normalize( p - earthCentre ) * r;
+}
+
+void main() {
+ vec3 d = normalize( vDir );
+ vec2 top = sphere( d, R_TOP );
+ vec2 ground = sphere( d, R_GROUND );
+ vec2 cloud = sphere( d, R_CLOUD );
+ bool hitGround = ground.x < 1e8 && ground.x > 0.0;
+ bool hitCloud = cloud.x < 1e8 && cloud.x > 0.0;
+
+ // Texture lookups on every pixel so the derivatives stay defined.
+ vec3 gp = onSphere( d, R_GROUND, ground );
+ vec3 gn = normalize( gp - earthCentre );
+ vec3 gLocal = worldToEarth * gn;
+ vec2 guv = equirect( gLocal, spin );
+ vec3 day = seamless( dayMap, guv ).rgb;
+ vec3 lights = seamless( nightMap, guv ).rgb;
+ vec4 relief = seamless( reliefMap, guv );
+ vec3 cp = onSphere( d, R_CLOUD, cloud );
+ vec3 cn = normalize( cp - earthCentre );
+ vec2 cuv = equirect( worldToEarth * cn, cloudSpin );
+ float cover = seamless( cloudMap, cuv ).r;
+
+ // The sun's disc and glare (behind everything else).
+ float cosSun = dot( d, sunDir );
+ float disc = smoothstep( 0.999955, 0.99997, cosSun );
+ float glare = pow( max( cosSun, 0.0 ), 2200.0 ) * 0.35 + pow( max( cosSun, 0.0 ), 120.0 ) * 0.012;
+ vec3 colour = vec3( 1.0, 0.97, 0.92 ) * ( disc * 60.0 + glare ) * sunRadiance;
+ float alpha = 0.0;
+
+ float far = hitGround ? ground.x : top.y;
+ float near = max( top.x, 0.0 );
+ vec3 transmit = vec3( 1.0 );
+ vec3 inscatter = vec3( 0.0 );
+
+ if ( top.x < 1e8 && top.y > 0.0 ) {
+ float mu = cosSun;
+ float pivot = clamp( dot( earthCentre, d ), near, far );
+ vec3 ray = vec3( 0.0 );
+ vec3 mie = vec3( 0.0 );
+ // Then both halves in order from the camera, with the depth so far.
+ vec2 depth = vec2( 0.0 );
+ float prevT = near;
+ for ( int half_ = 0; half_ < 2; half_++ ) {
+ float span = half_ == 0 ? pivot - near : far - pivot;
+ if ( span <= 0.0 ) continue;
+ for ( int i = 1; i <= VIEW_STEPS; i++ ) {
+ // Near half from the camera towards the pivot: crowd the samples at the pivot.
+ float s = float( i ) / float( VIEW_STEPS );
+ float t = half_ == 0 ? near + span * ( 1.0 - ( 1.0 - s ) * ( 1.0 - s ) ) : pivot + span * s * s;
+ float ds = t - prevT;
+ vec3 p = d * ( 0.5 * ( prevT + t ) );
+ vec2 dens = density( p ) * ds;
+ depth += dens * 0.5;
+ vec3 att = extinction( sunDepth( p ) + depth );
+ depth += dens * 0.5;
+ ray += dens.x * att;
+ mie += dens.y * att;
+ prevT = t;
+ }
+ }
+ float rayPhase = 3.0 / ( 16.0 * PI ) * ( 1.0 + mu * mu );
+ float g2 = MIE_G * MIE_G;
+ float miePhase = 3.0 / ( 8.0 * PI ) * ( ( 1.0 - g2 ) * ( 1.0 + mu * mu ) ) / ( ( 2.0 + g2 ) * pow( 1.0 + g2 - 2.0 * MIE_G * mu, 1.5 ) );
+ inscatter = ( ray * BETA_RAY * rayPhase + mie * BETA_MIE * miePhase ) / extinction( vec2( H_RAY, H_MIE ) ) * sunRadiance * hazeGain;
+ transmit = extinction( depth );
+ }
+
+ if ( hitGround || hitCloud ) {
+ // Ground: terrain slope from the relief map, in the local east/north frame.
+ vec3 north = normalize( transpose( worldToEarth ) * vec3( 0.0, 1.0, 0.0 ) );
+ vec3 east = normalize( cross( north, gn ) );
+ vec3 up = cross( gn, east );
+ vec2 slope = ( relief.rg - 0.5 ) * 2.0;
+ float water = relief.b;
+ vec3 n = normalize( gn + ( east * slope.x + up * slope.y ) * ( 1.0 - water ) * 0.6 );
+ float muG = dot( n, sunDir );
+ vec3 sunAtGround = sunAt( gp );
+ // Cloud shadow: the cover a little towards the sun.
+ vec3 shadowP = gp + ( sunDir - gn * dot( sunDir, gn ) ) * ( ( R_CLOUD - R_GROUND ) / max( dot( sunDir, gn ), 0.15 ) );
+ float shade = 1.0 - 0.6 * seamless( cloudMap, equirect( worldToEarth * normalize( shadowP - earthCentre ), cloudSpin ) ).r;
+ vec3 albedo = day * mix( 1.0, 0.85, water );
+ // Lambertian: radiance = albedo / pi x irradiance.
+ vec3 groundColour = albedo / PI * max( muG, 0.0 ) * sunAtGround * shade;
+ // Sun glint on open water.
+ vec3 h = normalize( sunDir - d );
+ float nh = max( dot( gn, h ), 0.0 );
+ float a2 = 0.045;
+ float dn = nh * nh * ( a2 - 1.0 ) + 1.0;
+ float ggx = a2 / ( PI * dn * dn );
+ float fresnel = 0.02 + 0.98 * pow( 1.0 - max( dot( -d, h ), 0.0 ), 5.0 );
+ groundColour += water * ggx * fresnel * max( dot( gn, sunDir ), 0.0 ) * sunAtGround * shade * 0.25;
+ // City lights on the night side.
+ float night = smoothstep( 0.04, -0.12, dot( gn, sunDir ) );
+ groundColour += lights * lights * nightGain * night * ( 1.0 - 0.8 * cover );
+
+ // Cloud layer over it.
+ float muC = dot( cn, sunDir );
+ vec3 sunAtCloud = sunAt( cp );
+ float ca = smoothstep( 0.08, 0.75, cover ) * 0.97;
+ vec3 cloudColour = vec3( 0.92 / PI ) * ( max( muC, 0.0 ) * 0.9 + 0.1 * smoothstep( -0.1, 0.2, muC ) ) * sunAtCloud * mix( 0.75, 1.0, cover );
+ vec3 surface = hitGround ? mix( groundColour, cloudColour, ca ) : cloudColour;
+ float cover01 = hitGround ? 1.0 : ca;
+ colour = colour * ( 1.0 - cover01 ) + surface * cover01;
+ alpha = cover01;
+ }
+
+ vec3 premul = colour * transmit + inscatter;
+ float behind = 1.0 - dot( transmit, vec3( 0.333 ) );
+ alpha = alpha + ( 1.0 - alpha ) * behind;
+ gl_FragColor = vec4( premul * ready, alpha * ready );
+}
+`;
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/spaceView.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/spaceView.test.ts
new file mode 100644
index 0000000000..8d8422482f
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/spaceView.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from "vitest";
+import { BoxGeometry, Group, Matrix3, Mesh, PerspectiveCamera, PlaneGeometry, Vector3 } from "three";
+import { SPACE_LOOK, SpaceView, spaceTextureUrls, starField } from "./spaceView";
+import { outwardOf } from "./realtimeScene";
+
+describe("star field", () => {
+ it("is the same sky on every visit, on the sphere, mostly faint", () => {
+ const a = starField(2000);
+ const b = starField(2000);
+ expect(Array.from(a.positions)).toEqual(Array.from(b.positions));
+ const p = new Vector3();
+ let faint = 0;
+ for (let i = 0; i < 2000; i++) {
+ p.fromArray(a.positions, i * 3);
+ expect(p.length()).toBeCloseTo(50, 3);
+ if (a.colours[i * 3 + 1] < 0.3) faint++;
+ }
+ expect(faint / 2000).toBeGreaterThan(0.5);
+ });
+});
+
+describe("viewport direction", () => {
+ it("follows the big forward viewport, not a small porthole at the back", () => {
+ const group = new Group();
+ group.add(new Mesh(new BoxGeometry(40, 6, 40)));
+ const hero = new Mesh(new PlaneGeometry(30, 5));
+ hero.position.set(0, 3, -19);
+ const porthole = new Mesh(new PlaneGeometry(2, 1));
+ porthole.position.set(0, 3, 19);
+ group.add(hero, porthole);
+ group.updateMatrixWorld(true);
+ const out = outwardOf(group, [hero, porthole])!;
+ expect(out.z).toBeLessThan(-0.99);
+ expect(out.y).toBe(0);
+ expect(outwardOf(group, [])).toBeNull();
+ });
+});
+
+describe("space view", () => {
+ it("puts the Earth below the windows, with the chosen place facing them", () => {
+ const view = new SpaceView(4);
+ view.setOutward(new Vector3(0, 0, -1));
+ const camera = new PerspectiveCamera(50, 16 / 9, 0.05, 500);
+ camera.lookAt(0, 0, -1);
+ camera.updateMatrixWorld();
+ view.update(camera, 0, 1);
+ const uniforms = (view as unknown as { planet: { uniforms: Record<string, { value: unknown }> } }).planet.uniforms;
+ const centre = uniforms.earthCentre.value as Vector3;
+ expect(centre.y).toBeLessThan(0);
+ expect(centre.z).toBeLessThan(0);
+ expect(centre.length()).toBeCloseTo(1 + SPACE_LOOK.altitudeKm / 6371, 5);
+ // The ground point straight out of the windows maps to the chosen latitude and longitude.
+ const out = new Vector3(0, 0, -1);
+ const b = centre.dot(out);
+ const h = b * b - (centre.lengthSq() - 1);
+ expect(h).toBeGreaterThan(0);
+ const normal = out.multiplyScalar(b - Math.sqrt(h)).sub(centre).normalize();
+ const local = normal.applyMatrix3(uniforms.worldToEarth.value as Matrix3);
+ const lat = (Math.asin(local.y) * 180) / Math.PI;
+ const lon = (Math.atan2(-local.z, local.x) * 180) / Math.PI;
+ expect(lat).toBeCloseTo(SPACE_LOOK.latDeg, 3);
+ expect(lon).toBeCloseTo(SPACE_LOOK.lonDeg, 3);
+ view.dispose();
+ });
+
+ it("serves its textures next to the decks", () => {
+ expect(spaceTextureUrls("/").day).toBe("/verse/space/earth_day.webp");
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/spaceView.ts b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/spaceView.ts
new file mode 100644
index 0000000000..99ddbb08c8
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/spaceView.ts
@@ -0,0 +1,394 @@
+/**
+ * Outside the hull (docs/verse/realtime.md): the Earth in low orbit, the sun
+ * and the stars, drawn behind the deck in the eye-level view. The deck's own
+ * star cards are hidden (realtimeScene), so every viewport looks into this.
+ *
+ * The space has its own camera at the origin that turns with the deck camera
+ * but never moves: the planet is thousands of kilometres away, so walking
+ * past a window changes the angle, never the parallax, as it would for real.
+ * Lengths are in Earth radii.
+ *
+ * The Earth sits below and ahead of the deck's viewports (`outward`, from the
+ * deck), turned so a chosen place faces the windows, and turns under the ship
+ * at about orbital speed.
+ */
+import {
+ AdditiveBlending, BufferAttribute, BufferGeometry, Color, CustomBlending, DataTexture, LinearFilter,
+ LinearMipmapLinearFilter, Matrix3, Matrix4, Mesh, OneFactor, OneMinusSrcAlphaFactor, PerspectiveCamera, Points,
+ Quaternion, RedFormat, RepeatWrapping, ClampToEdgeWrapping, RGBAFormat, Scene, ShaderMaterial, SRGBColorSpace, NoColorSpace,
+ Texture, Vector3, type WebGLRenderer,
+} from "three";
+import { Pass } from "three/examples/jsm/postprocessing/Pass.js";
+import { fetchImageBitmap } from "../imageFetch";
+import { SPACE_FRAGMENT, SPACE_VERTEX } from "./spaceShader";
+
+/** The look of the view; QA runs override it through `window.__verseSpace`. */
+export interface SpaceLook {
+ /** Height of the orbit above the ground, km. */
+ altitudeKm: number;
+ /** How far below the horizon the Earth's centre lies, degrees (0: straight ahead). */
+ centreDownDeg: number;
+ /** Tilt of the horizon, degrees. */
+ rollDeg: number;
+ /** The place under the windows at the start, degrees. */
+ latDeg: number;
+ lonDeg: number;
+ /** Sun direction relative to the windows: azimuth (right +), elevation, degrees. */
+ sunAzimuthDeg: number;
+ sunElevationDeg: number;
+ sunRadiance: number;
+ nightGain: number;
+ hazeGain: number;
+ starGain: number;
+ /** Ground speed as a multiple of the real one (7.7 km/s). */
+ orbitSpeed: number;
+ /** QA: 0 leaves the planet pass out. */
+ planet: number;
+ /** QA: the windows' direction [x, z] instead of the deck's. */
+ outward?: readonly [number, number];
+}
+
+export const SPACE_LOOK: SpaceLook = {
+ altitudeKm: 900,
+ centreDownDeg: 56,
+ rollDeg: -9,
+ // Looking north-west over the Atlantic towards North America.
+ latDeg: 40,
+ lonDeg: -68,
+ // Sun ahead and high: its glint runs down the ocean towards the windows.
+ sunAzimuthDeg: 15,
+ sunElevationDeg: 32,
+ sunRadiance: 8,
+ nightGain: 3.0,
+ hazeGain: 0.6,
+ starGain: 1.0,
+ orbitSpeed: 2.0,
+ planet: 1,
+};
+
+const EARTH_KM = 6371;
+const ORBIT_RAD_PER_S = 7.7 / EARTH_KM;
+const STAR_COUNT = 9000;
+const STAR_RADIUS = 50;
+
+export interface SpaceTextures {
+ day: string;
+ night: string;
+ clouds: string;
+ relief: string;
+}
+
+export function spaceTextureUrls(base: string): SpaceTextures {
+ const root = `${base}verse/space/`;
+ return {
+ day: `${root}earth_day.webp`,
+ night: `${root}earth_night.webp`,
+ clouds: `${root}earth_clouds.webp`,
+ relief: `${root}earth_relief.webp`,
+ };
+}
+
+function look(): SpaceLook {
+ const override = (window as unknown as { __verseSpace?: Partial<SpaceLook> }).__verseSpace;
+ return override ? { ...SPACE_LOOK, ...override } : SPACE_LOOK;
+}
+
+/** A small deterministic generator, so the sky is the same on every visit. */
+function random(seed: number): () => number {
+ let s = seed >>> 0;
+ return () => {
+ s = (s + 0x6d2b79f5) >>> 0;
+ let t = s;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+/** Stars over the whole sky, crowded along a tilted galactic band; brightness falls off like real magnitudes. */
+export function starField(count: number, seed = 7): { positions: Float32Array; colours: Float32Array; sizes: Float32Array } {
+ const rand = random(seed);
+ const positions = new Float32Array(count * 3);
+ const colours = new Float32Array(count * 3);
+ const sizes = new Float32Array(count);
+ const pole = new Vector3(0.35, 0.82, -0.45).normalize();
+ const v = new Vector3();
+ const temps = [
+ [0.62, 0.72, 1.0], [0.8, 0.86, 1.0], [1.0, 1.0, 1.0], [1.0, 0.95, 0.82], [1.0, 0.82, 0.6], [1.0, 0.7, 0.5],
+ ];
+ for (let i = 0; i < count; i++) {
+ // Half the stars hug the band: pull them towards the plane perpendicular to the pole.
+ for (;;) {
+ const z = rand() * 2 - 1;
+ const a = rand() * Math.PI * 2;
+ const r = Math.sqrt(1 - z * z);
+ v.set(r * Math.cos(a), z, r * Math.sin(a));
+ const band = Math.abs(v.dot(pole));
+ if (i % 2 === 0 || rand() > band * 1.6) break;
+ }
+ positions.set([v.x * STAR_RADIUS, v.y * STAR_RADIUS, v.z * STAR_RADIUS], i * 3);
+ // Magnitudes: many faint, few bright.
+ const m = Math.pow(rand(), 5.5);
+ const brightness = 0.06 + m * 3.5;
+ const t = temps[Math.min(temps.length - 1, Math.floor(Math.pow(rand(), 0.8) * temps.length))];
+ colours.set([t[0] * brightness, t[1] * brightness, t[2] * brightness], i * 3);
+ sizes[i] = 1.0 + m * 2.2;
+ }
+ return { positions, colours, sizes };
+}
+
+const STAR_VERTEX = /* glsl */ `
+attribute vec3 colour;
+attribute float size;
+uniform float pixelRatio;
+uniform float gain;
+varying vec3 vColour;
+void main() {
+ vColour = colour * gain;
+ gl_PointSize = size * pixelRatio;
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
+}
+`;
+
+const STAR_FRAGMENT = /* glsl */ `
+varying vec3 vColour;
+void main() {
+ vec2 c = gl_PointCoord * 2.0 - 1.0;
+ float f = max( 1.0 - dot( c, c ), 0.0 );
+ gl_FragColor = vec4( vColour * f * f, 1.0 );
+}
+`;
+
+function placeholder(format: typeof RGBAFormat | typeof RedFormat, value: number): DataTexture {
+ const data = new Uint8Array(format === RedFormat ? [value] : [value, value, value, 255]);
+ const t = new DataTexture(data, 1, 1, format);
+ t.needsUpdate = true;
+ return t;
+}
+
+async function loadTexture(gl: WebGLRenderer, url: string, signal: AbortSignal, srgb: boolean, red: boolean): Promise<Texture> {
+ let bitmap = await fetchImageBitmap(url, signal, "none");
+ const max = gl.capabilities.maxTextureSize;
+ if (bitmap.width > max) {
+ const smaller = await createImageBitmap(bitmap, { resizeWidth: max, resizeHeight: Math.round((bitmap.height * max) / bitmap.width), resizeQuality: "high" });
+ bitmap.close();
+ bitmap = smaller;
+ }
+ const texture = new Texture(bitmap);
+ texture.flipY = false;
+ texture.colorSpace = srgb ? SRGBColorSpace : NoColorSpace;
+ texture.format = red ? RedFormat : RGBAFormat;
+ texture.wrapS = RepeatWrapping;
+ texture.wrapT = ClampToEdgeWrapping;
+ texture.generateMipmaps = true;
+ texture.minFilter = LinearMipmapLinearFilter;
+ texture.magFilter = LinearFilter;
+ texture.anisotropy = Math.min(8, gl.capabilities.getMaxAnisotropy());
+ texture.needsUpdate = true;
+ return texture;
+}
+
+export class SpaceView {
+ readonly scene = new Scene();
+ readonly camera = new PerspectiveCamera(50, 1, 0.01, 200);
+ private readonly planet: ShaderMaterial;
+ private readonly planetMesh: Mesh;
+ /** For QA runs: whether the textures arrived, and where the windows look. */
+ readonly state = { ready: false, error: "", outward: [0, 0, 1] };
+ private readonly stars: ShaderMaterial;
+ private readonly owned: Texture[] = [];
+ private readonly outward = new Vector3(0, 0, 1);
+ private elapsed = 0;
+ private readonly m3 = new Matrix3();
+ private readonly m4 = new Matrix4();
+ private readonly q = new Quaternion();
+ private readonly v = Array.from({ length: 10 }, () => new Vector3());
+ private readonly local = new Matrix3();
+
+ constructor(steps: number) {
+ const placeholders = [placeholder(RGBAFormat, 0), placeholder(RGBAFormat, 0), placeholder(RedFormat, 0), placeholder(RGBAFormat, 128)];
+ this.owned.push(...placeholders);
+ this.planet = new ShaderMaterial({
+ vertexShader: SPACE_VERTEX,
+ fragmentShader: SPACE_FRAGMENT,
+ defines: { VIEW_STEPS: steps },
+ uniforms: {
+ verseInvViewProj: { value: new Matrix4() },
+ earthCentre: { value: new Vector3() },
+ worldToEarth: { value: new Matrix3() },
+ spin: { value: 0 },
+ cloudSpin: { value: 0 },
+ sunDir: { value: new Vector3(0, 1, 0) },
+ sunRadiance: { value: 1 },
+ nightGain: { value: 1 },
+ hazeGain: { value: 1 },
+ ready: { value: 0 },
+ dayMap: { value: placeholders[0] },
+ nightMap: { value: placeholders[1] },
+ cloudMap: { value: placeholders[2] },
+ reliefMap: { value: placeholders[3] },
+ },
+ depthTest: false,
+ depthWrite: false,
+ transparent: true,
+ blending: CustomBlending,
+ blendSrc: OneFactor,
+ blendDst: OneMinusSrcAlphaFactor,
+ premultipliedAlpha: true,
+ });
+ const tri = new BufferGeometry();
+ tri.setAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0, 3, -1, 0, -1, 3, 0]), 3));
+ const quad = new Mesh(tri, this.planet);
+ quad.frustumCulled = false;
+ quad.renderOrder = 2;
+ this.planetMesh = quad;
+
+ const field = starField(STAR_COUNT);
+ const starGeometry = new BufferGeometry();
+ starGeometry.setAttribute("position", new BufferAttribute(field.positions, 3));
+ starGeometry.setAttribute("colour", new BufferAttribute(field.colours, 3));
+ starGeometry.setAttribute("size", new BufferAttribute(field.sizes, 1));
+ this.stars = new ShaderMaterial({
+ vertexShader: STAR_VERTEX,
+ fragmentShader: STAR_FRAGMENT,
+ uniforms: { pixelRatio: { value: 1 }, gain: { value: 1 } },
+ depthTest: false,
+ depthWrite: false,
+ transparent: true,
+ blending: AdditiveBlending,
+ });
+ const points = new Points(starGeometry, this.stars);
+ points.frustumCulled = false;
+ points.renderOrder = 1;
+ this.scene.add(points, quad);
+ this.scene.background = new Color(0, 0, 0);
+ }
+
+ /** Loads the Earth's textures; until then only the stars and the sun show. */
+ async load(gl: WebGLRenderer, urls: SpaceTextures, signal: AbortSignal): Promise<void> {
+ const [day, night, clouds, relief] = await Promise.all([
+ loadTexture(gl, urls.day, signal, true, false),
+ loadTexture(gl, urls.night, signal, true, false),
+ loadTexture(gl, urls.clouds, signal, false, true),
+ loadTexture(gl, urls.relief, signal, false, false),
+ ]);
+ if (signal.aborted) {
+ for (const t of [day, night, clouds, relief]) t.dispose();
+ signal.throwIfAborted();
+ }
+ this.owned.push(day, night, clouds, relief);
+ const u = this.planet.uniforms;
+ u.dayMap.value = day;
+ u.nightMap.value = night;
+ u.cloudMap.value = clouds;
+ u.reliefMap.value = relief;
+ u.ready.value = 1;
+ this.state.ready = true;
+ }
+
+ /** The direction the deck's viewports look out of (world, horizontal). */
+ setOutward(direction: Vector3): void {
+ this.outward.set(direction.x, 0, direction.z);
+ if (this.outward.lengthSq() < 1e-6) this.outward.set(0, 0, 1);
+ this.outward.normalize();
+ this.state.outward = this.outward.toArray();
+ }
+
+ update(deckCamera: PerspectiveCamera, dt: number, pixelRatio: number): void {
+ const l = look();
+ this.elapsed += dt;
+ const cam = this.camera;
+ cam.fov = deckCamera.fov;
+ cam.aspect = deckCamera.aspect;
+ cam.updateProjectionMatrix();
+ deckCamera.getWorldQuaternion(this.q);
+ cam.quaternion.copy(this.q);
+ cam.position.set(0, 0, 0);
+ cam.updateMatrixWorld();
+
+ const [out, up, side, centre, target, tmp, north, pL, eL, nL] = this.v;
+ const rad = Math.PI / 180;
+ if (l.outward) out.set(l.outward[0], 0, l.outward[1]).normalize();
+ else out.copy(this.outward);
+ up.set(0, 1, 0);
+ side.crossVectors(out, up).normalize(); // to the right when looking out
+ // Horizon tilt: the whole frame turns about the outward axis.
+ up.applyAxisAngle(out, l.rollDeg * rad);
+ side.applyAxisAngle(out, l.rollDeg * rad);
+
+ const distance = 1 + l.altitudeKm / EARTH_KM;
+ const down = l.centreDownDeg * rad;
+ centre.copy(out).multiplyScalar(Math.cos(down)).addScaledVector(up, -Math.sin(down)).multiplyScalar(distance);
+ // The ground point facing the windows: where the outward ray meets the sphere, else the limb.
+ const b = centre.dot(out);
+ const h = b * b - (centre.lengthSq() - 1);
+ target.copy(out).multiplyScalar(h > 0 ? b - Math.sqrt(h) : b).sub(centre).normalize();
+ // World basis at that point: normal, east (right), north (up the view).
+ const nW = target;
+ const eW = tmp.copy(side).addScaledVector(nW, -side.dot(nW)).normalize();
+ north.crossVectors(nW, eW);
+ // Local basis of the chosen place (texture space: y north, longitude 0 at +x, east towards -z).
+ const lat = l.latDeg * rad;
+ const lon = l.lonDeg * rad;
+ pL.set(Math.cos(lat) * Math.cos(lon), Math.sin(lat), -Math.cos(lat) * Math.sin(lon));
+ eL.set(-Math.sin(lon), 0, -Math.cos(lon));
+ nL.crossVectors(pL, eL);
+ // worldToEarth = L * W^T (columns east, north, normal).
+ const L = this.local.set(eL.x, nL.x, pL.x, eL.y, nL.y, pL.y, eL.z, nL.z, pL.z);
+ const W = this.m3.set(eW.x, north.x, nW.x, eW.y, north.y, nW.y, eW.z, north.z, nW.z).transpose();
+ const u = this.planet.uniforms;
+ (u.worldToEarth.value as Matrix3).multiplyMatrices(L, W);
+ (u.earthCentre.value as Vector3).copy(centre);
+ // Ground moving under the ship towards the right of the windows.
+ const turn = this.elapsed * ORBIT_RAD_PER_S * l.orbitSpeed;
+ u.spin.value = -turn;
+ u.cloudSpin.value = -turn * 1.04 + 0.35;
+ const az = l.sunAzimuthDeg * rad;
+ const el = l.sunElevationDeg * rad;
+ (u.sunDir.value as Vector3)
+ .copy(out).multiplyScalar(Math.cos(el) * Math.cos(az))
+ .addScaledVector(side, Math.cos(el) * Math.sin(az))
+ .addScaledVector(up, Math.sin(el))
+ .normalize();
+ this.planetMesh.visible = l.planet !== 0;
+ u.sunRadiance.value = l.sunRadiance;
+ u.nightGain.value = l.nightGain;
+ u.hazeGain.value = l.hazeGain;
+ this.stars.uniforms.pixelRatio.value = pixelRatio;
+ this.stars.uniforms.gain.value = l.starGain;
+ this.m4.multiplyMatrices(cam.matrixWorld, cam.projectionMatrixInverse);
+ (u.verseInvViewProj.value as Matrix4).copy(this.m4);
+ }
+
+ /** Clears the bound target and draws space into it, then clears depth for the deck. */
+ render(gl: WebGLRenderer): void {
+ const autoClear = gl.autoClear;
+ gl.autoClear = true;
+ gl.render(this.scene, this.camera);
+ gl.autoClear = autoClear;
+ gl.clearDepth();
+ }
+
+ dispose(): void {
+ this.planet.dispose();
+ this.stars.dispose();
+ for (const t of this.owned) t.dispose();
+ this.scene.traverse((o) => (o as Mesh).geometry?.dispose());
+ }
+}
+
+/** First pass of the post chain: space into the read buffer; the deck's RenderPass then draws over it without clearing. */
+export class SpacePass extends Pass {
+ view: SpaceView | null = null;
+
+ constructor() {
+ super();
+ this.needsSwap = false;
+ }
+
+ render(renderer: WebGLRenderer, _writeBuffer: unknown, readBuffer: Parameters<WebGLRenderer["setRenderTarget"]>[0]): void {
+ renderer.setRenderTarget(readBuffer);
+ if (this.view) this.view.render(renderer);
+ else renderer.clear();
+ }
+}
diff --git a/scripts/verse/earth.py b/scripts/verse/earth.py
new file mode 100644
index 0000000000..9213923125
--- /dev/null
+++ b/scripts/verse/earth.py
@@ -0,0 +1,118 @@
+"""Bake the textures of the Earth seen through the Verse's viewports.
+
+Sources are NASA imagery in the public domain (NASA Visible Earth):
+
+* day: Blue Marble Next Generation, topography + bathymetry, July 2004
+* night: Black Marble 2016 (city lights)
+* clouds: Blue Marble cloud composite
+* relief: GEBCO 08 elevation (land) and bathymetry (water mask)
+
+Usage::
+
+ python scripts/verse/earth.py --src <dir with the downloads> [--size 8192]
+
+``--fetch`` downloads the sources into ``--src`` first. Writes WebP files to
+dodaios/ui/web/frontend/public/verse/space/ (equirectangular, longitude -180
+at the left edge, north at the top):
+
+* earth_day.webp RGB colour (sRGB)
+* earth_night.webp RGB city lights (sRGB), half size
+* earth_clouds.webp cloud cover in R (linear), full size
+* earth_relief.webp R,G = tangent-space slope of the terrain (0.5 = flat),
+ B = water (255 = open water), half size
+"""
+
+from __future__ import annotations
+
+import argparse
+import urllib.request
+from pathlib import Path
+
+import numpy as np
+from PIL import Image
+
+Image.MAX_IMAGE_PIXELS = None
+
+ROOT = Path(__file__).resolve().parents[2]
+OUT = ROOT / "dodaios/ui/web/frontend/public/verse/space"
+
+SOURCES = {
+ "day.jpg": "https://eoimages.gsfc.nasa.gov/images/imagerecords/73000/73751/world.topo.bathy.200407.3x21600x10800.jpg",
+ "night.jpg": "https://eoimages.gsfc.nasa.gov/images/imagerecords/144000/144898/BlackMarble_2016_3km.jpg",
+ "clouds.tif": "https://eoimages.gsfc.nasa.gov/images/imagerecords/57000/57747/cloud_combined_8192.tif",
+ "topo.png": "https://eoimages.gsfc.nasa.gov/images/imagerecords/73000/73934/gebco_08_rev_elev_21600x10800.png",
+ "water.png": "https://eoimages.gsfc.nasa.gov/images/imagerecords/73000/73963/gebco_08_rev_bath_21600x10800.png",
+}
+
+
+def fetch(src: Path) -> None:
+ src.mkdir(parents=True, exist_ok=True)
+ for name, url in SOURCES.items():
+ target = src / name
+ if not target.exists():
+ print(f"[earth] fetch {name}", flush=True)
+ urllib.request.urlretrieve(url, target) # noqa: S310 (fixed https URLs)
+
+
+def resized(path: Path, size: int, mode: str) -> Image.Image:
+ image = Image.open(path).convert(mode)
+ return image.resize((size, size // 2), Image.Resampling.LANCZOS)
+
+
+def save(image: Image.Image, name: str, quality: int) -> None:
+ OUT.mkdir(parents=True, exist_ok=True)
+ target = OUT / name
+ image.save(target, "WEBP", quality=quality, method=6)
+ mb = target.stat().st_size / 1e6
+ print(f"[earth] {name} {image.size[0]}x{image.size[1]} {mb:.2f} MB", flush=True)
+
+
+def relief(src: Path, size: int) -> Image.Image:
+ """Terrain slope from the elevation (R, G) and the water mask (B)."""
+ height = np.asarray(resized(src / "topo.png", size, "L"), dtype=np.float32) / 255.0
+ # The source spans 0-6400 m in 255 steps; this is about how steep the
+ # mountains read under a low sun, not a physical scale.
+ strength = 6.0 * size / 4096
+ dx = (np.roll(height, -1, axis=1) - np.roll(height, 1, axis=1)) * strength
+ dy = (np.roll(height, -1, axis=0) - np.roll(height, 1, axis=0)) * strength
+ dy[0, :] = 0
+ dy[-1, :] = 0
+ # Longitude shrinks towards the poles: the same step east is shorter there.
+ lat = (0.5 - (np.arange(height.shape[0]) + 0.5) / height.shape[0]) * np.pi
+ dx /= np.maximum(np.cos(lat), 0.05)[:, None]
+ red = np.clip(0.5 - dx * 0.5, 0, 1)
+ green = np.clip(0.5 + dy * 0.5, 0, 1)
+ bath = np.asarray(resized(src / "water.png", size, "L"), dtype=np.float32) / 255.0
+ # The bathymetry is white over land and darker with depth over water.
+ water = np.clip((0.995 - bath) * 60.0, 0, 1)
+ rgb = np.stack([red, green, water], axis=-1)
+ return Image.fromarray((rgb * 255 + 0.5).astype(np.uint8), "RGB")
+
+
+def city_lights(src: Path, size: int) -> Image.Image:
+ """Only the lights of Black Marble: its moonlit blue land and sea drop out."""
+ night = np.asarray(resized(src / "night.jpg", size, "RGB"), dtype=np.float32) / 255.0
+ # The moonlit ground is blue (blue above red); lights are warm and bright.
+ light = np.clip((night[..., 0] - 0.85 * night[..., 2] + 0.02) * 2.2, 0, 1) ** 1.3
+ tint = np.array([1.0, 0.78, 0.5], dtype=np.float32)
+ rgb = light[..., None] * tint
+ return Image.fromarray((rgb * 255 + 0.5).astype(np.uint8), "RGB")
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--src", type=Path, required=True)
+ parser.add_argument("--size", type=int, default=8192)
+ parser.add_argument("--fetch", action="store_true")
+ args = parser.parse_args()
+ if args.fetch:
+ fetch(args.src)
+ size = args.size
+ save(resized(args.src / "day.jpg", size, "RGB"), "earth_day.webp", 88)
+ save(city_lights(args.src, size // 2), "earth_night.webp", 85)
+ save(resized(args.src / "clouds.tif", size, "L").convert("RGB"), "earth_clouds.webp", 72)
+ save(relief(args.src, size // 2), "earth_relief.webp", 90)
+
+
+if __name__ == "__main__":
+ main()