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): the city in the singularity outside the agents floor (#671)

Ruben Lütkefde832f3af55
diff --git a/art/studies/singularity-city-study/brief.md b/art/studies/singularity-city-study/brief.md
new file mode 100644
index 0000000000..3d97ee9f63
--- /dev/null
+++ b/art/studies/singularity-city-study/brief.md
@@ -0,0 +1,47 @@
+# Art study brief: the city in the singularity
+
+## Intent
+
+The world outside the agents floor and the Level Hall: the Dodaios tower
+stands in a megacity at night, built round a singularity. Seen from the
+floor it should read as a high-end game world: depth and vertigo, a city
+that lives (windows, traffic, light), and one unmistakable landmark.
+
+## Viewing conditions
+
+- The camera orbits the floor and always looks down (polar 20° to 72°);
+ at its flattest the horizon just shows. Normal distances: 2.5 m (walking)
+ to about 140 m (overview). The city is composed to be seen from above:
+ roofs, avenues and traffic lanes read at every zoom.
+- The floor itself stays the subject: nothing outside rises into it or
+ stands between it and the camera (plaza, roof limit, lane headroom, all
+ enforced by `cityPlan.test.ts`).
+
+## Direction
+
+- Shape language: glass towers of four classes (block, setback, tapering
+ prism, spire) on a 36 m street grid, avenues every second line; a crater
+ round the singularity ringed by gold-crowned spires.
+- Palette: deep indigo night and violet haze; windows cool white, warm
+ amber and a little cyan; gold as the one accent (seams, crowns, the
+ singularity's rings), matching the brand's charcoal and gold.
+- Light: everything outside is self-lit by its own shaders (the scene's sun
+ never reaches it); exponential aerial perspective into the sky's colour;
+ mist over the street level.
+- Motion: lit offices switch now and then, pulses climb the light seams,
+ street and flying traffic move, the accretion disc turns, the orbital
+ rings rotate. With reduced motion the clock stands still.
+
+## Production approach
+
+The city is procedural runtime geometry and shaders (instanced towers,
+GPU-animated traffic), not authored meshes, because it is a distant
+backdrop of hundreds of objects whose look is light, not form. There is
+therefore no Blender source or GLB export in this study; the runtime
+components are `SingularityCity.tsx`, `cityShaders.ts` and `cityPlan.ts`
+under `jarvis/ui/web/frontend/src/components/society/office/`.
+
+## Budgets
+
+About twenty draw calls for the whole city, nothing in the shadow pass,
+no per-frame CPU work beyond one clock and three rotations.
diff --git a/art/studies/singularity-city-study/review.md b/art/studies/singularity-city-study/review.md
new file mode 100644
index 0000000000..cc1779ee05
--- /dev/null
+++ b/art/studies/singularity-city-study/review.md
@@ -0,0 +1,8 @@
+# Reference review
+
+Decision: pending.
+
+Separate visual judgement from technical results. Record defects and revisions.
+After actual user approval, record its date, scope and an English summary here;
+keep private conversation content and personal identifiers outside the repository.
+A passing check or an agent's own opinion is not user approval.
diff --git a/art/studies/singularity-city-study/study.json b/art/studies/singularity-city-study/study.json
new file mode 100644
index 0000000000..37c679ca92
--- /dev/null
+++ b/art/studies/singularity-city-study/study.json
@@ -0,0 +1,16 @@
+{
+ "schema": 1,
+ "study": "singularity-city-study",
+ "brief": "brief.md",
+ "assets": [],
+ "runtime_evidence": [
+ "evidence/overview.jpg",
+ "evidence/flat-angle-skyline.jpg"
+ ],
+ "technical_report": "evidence/technical-report.md",
+ "approval": {
+ "status": "pending",
+ "record": "review.md",
+ "evidence_sha256": ""
+ }
+}
diff --git a/docs/agent-society/office-map.md b/docs/agent-society/office-map.md
index 2c1bb1bcc2..08e2d03459 100644
--- a/docs/agent-society/office-map.md
+++ b/docs/agent-society/office-map.md
@@ -39,7 +39,7 @@ never moves an agent, starts work or invents activity (world-behaviour-manual
| Furniture | A contemporary workplace built from rounded primitives: light-oak bench desks on black steel T-legs with a white pedestal and a felt privacy screen, slim monitors on arms, ergonomic chairs with a mesh back on a five-star base, open oak-and-steel shelving, low modular sofas on slim legs, tall charcoal planters with full crowns. Department back walls are fluted acoustic felt with a charcoal name plate in white type and oak ledges with small plants. |
| Materials | Mostly matte; black steel and chrome arms carry a little metalness. Light microcement floor, a rounded felt rug per department whose colour also dyes that department's felt screens and seat fabric (`DEPARTMENT_ZONES`). Rooms: slate felt (team), terrazzo (wardrobe), pale stone (reception), light oak (break room). Glass walls and the outer balustrade have slim black frames. |
| Light | Cool sky / neutral ground hemisphere light plus one soft, slightly warm directional sun with PCF shadows. Always bright enough to read, never moody. |
-| Setting | The agents floor and the Level Hall are floors of a tower in a city at night: a window wall on the far sides, the tower's body below, lit towers outside (§5h). The coding floor still floats in its own violet night behind glass railings. |
+| Setting | The agents floor and the Level Hall are floors of a tower in the city in the singularity: a window wall on the far sides, the tower's glass body falling away below, a megacity and the singularity outside (§5h). The coding floor still floats in its own violet night behind glass railings. |
| Camera | Perspective, 35° FOV, three-quarter view from the south-east about 40° below the horizon. Orbit, pan and zoom within limits (20°–72° polar, from 2.5 m out to wherever the overview needs: 140 m at least, more on a large campus). The overview frames the whole floor (§5i). |
| Labels | From across the floor an agent is one small state dot. The dark translucent plate (hexagon badge with the initial or the lead's star, name, rank chip, state dot and activity) fades in over the dot when the camera or the person is near, when the pointer or keyboard focus rests on the agent, or when it is selected (§5g). Scale is clamped by distance. |
| State language | Green = working (pulsing floor ring, code on the monitor), amber = waiting for the person, grey = idle (smiley monitor) or paused (dark monitor). |
@@ -599,15 +599,33 @@ street of team rooms round an atrium, with commons people use in between.
window wall with steel mullions and a ceiling edge. The floor is shown like
a cut-open model: a side's window wall stands only while the camera is on
the opposite side of the floor; the other sides keep the glass balustrade.
- Outside lies a city at night that stays a backdrop: a few dozen unlit
- towers a shade lighter than the deep navy sky, the first 62 m from the
- building, every roof at least 24 m below the floor and the nearest ones
- lowest. About one window in twenty is dimly lit, from one small tiling
- texture; a tower sinks into the sky's colour towards its foot and with its
- distance, the scene's sun never reaches it, and the faintest glow lies
- over the streets where detail would be. Apart from the sparse windows
- nothing outside is brighter than a dark navy (#1a2233). The office is
- always the brightest and most detailed thing on screen.
+ Outside lies the city in the singularity (`SingularityCity.tsx`, plan in
+ `cityPlan.ts`, shaders in `cityShaders.ts`): a megacity 330 m below the
+ floor, seen from high above. Several hundred glass towers of four kinds
+ (block, setback, tapering prism, spire) stand on a 36 m street grid; their
+ windows are drawn in world metres, lit in office runs that switch now and
+ then, and fade to their average glow once a window is smaller than a
+ pixel or two. Some towers carry gold, cyan or white light seams with
+ pulses climbing them, a lit crown, a lit parapet or a landing ring; tall
+ roofs carry aviation lights. The streets glow with kerb lamps, avenues
+ carry a cyan centre line and traffic both ways, and flying traffic circles
+ the tower in seven lanes high over the rooftops. Beams of light rise from
+ the tallest far roofs; mist drifts between the roofs. Off to the north
+ hovers the singularity: a black core with its photon ring, a turning
+ accretion disc, polar jets and three gold orbital rings, inside a crater
+ ringed by eighteen gold-crowned spires. The building's own tower is the
+ same glass with gold seams.
+ The floor stays the subject: an empty plaza of 70 m round the slab, every
+ roof within 330 m at least 70 m below the floor (about 170 m below beside
+ the plaza), and every tower under a traffic lane kept below it; at the
+ camera's flattest angle the far towers form a skyline at the horizon.
+ Everything outside is self-lit (the scene's sun never reaches it) and
+ sinks with distance into the sky's own colour; the scene's background and
+ fog take the haze's colour, and the coding floor alone keeps the starry
+ night. The whole city is about twenty draw calls, nothing casts or
+ receives a shadow, traffic is computed on the GPU, and with reduced motion
+ its clock stands still. Measured 2026-10-14 on an RTX 5070 Ti at
+ 2560 × 1217 px: the city adds about 0.4 ms per frame in the overview.
- **One material language** from the studios to the last room: light plank
oak, limestone and felt on the floor; light oak for timber; dark steel for
metal, with bronze as the one accent; steel-framed clear glass with a
@@ -905,6 +923,14 @@ by a rebuilt floor plan is put on the nearest free ground.
free plot) is covered by unit tests for the plan (the stand and its
standing place, the arch at the desk, 1.2 m or more to walk along both
windows) and was then checked in a browser by the orchestrator.
+- City (2026-10-14): `cityPlan.test.ts` holds the plan for a hall-sized, a
+ typical and a large floor: deterministic, the plaza empty, every roof
+ within the roof limit, no two towers on one spot, the crater clear with
+ its ring of spires and the disc and rings inside it, every lane below the
+ floor, outside the plaza and above the roofs under it.
+ `CampusScene.test.tsx` mounts the city without a GPU (draw calls, no
+ shadows, towers on the street level). Checked in Chrome against the dev
+ build: overview, walking view and the flattest angle.
- Floors (2026-10-12): `progression/verseFloors.test.ts` reads
`VERSE_FLOORS` from jarvis/progression/service.py and holds it equal to the
client's `METERED_FLOORS` and the elevator's `OFFICE_FLOORS`; a world
diff --git a/jarvis/ui/web/frontend/src/components/society/office/BuildingShell.tsx b/jarvis/ui/web/frontend/src/components/society/office/BuildingShell.tsx
index 4e8403ecf8..881edf8bdc 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/BuildingShell.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/BuildingShell.tsx
@@ -1,40 +1,28 @@
/**
* What makes the agents floor (and the Level Hall above it) a floor of a
- * building instead of a plate in space: the tower's body under the slab, a
- * window wall with steel mullions and a ceiling edge on the far sides, the
- * glass balustrade on the sides the camera looks in through, and a city at
- * night far below.
+ * building instead of a plate in space: a window wall with steel mullions and
+ * a ceiling edge on the far sides, the glass balustrade on the sides the
+ * camera looks in through, and outside the city in the singularity
+ * (SingularityCity.tsx), the building's own glass tower falling away under
+ * the slab into it.
*
* The floor is shown like a cut-open model: a side's window wall stands only
* while the camera is on the opposite side of the floor, so it is always the
* backdrop and never in the way; the other sides keep the low balustrade.
*
- * The city is a backdrop and stays one: a few dozen unlit towers a shade
- * lighter than the deep navy night, a long way off and far below the floor,
- * the near ones lowest. One window in twenty is lit, dimly; every tower sinks
- * into the sky's own colour towards its foot and with its distance from the
- * building, and the faintest glow lies over the streets where detail would
- * be. The scene's sun never reaches them. Apart from the sparse windows
- * nothing out there is brighter than a dark navy (#1a2233): the office is
- * always the brightest and most detailed thing on screen.
- *
* Purely visual and out of reach: everything stands on or beyond the slab's
- * edge, outside the walkable floor. The city is four draw calls (three tower
- * classes and the haze), the shell about two dozen, at any floor size.
- * Nothing casts a shadow.
+ * edge, outside the walkable floor. Nothing here casts a shadow.
*/
-import { useEffect, useMemo, useRef } from "react";
+import { useMemo, useRef } from "react";
import { useFrame } from "@react-three/fiber";
-import { AdditiveBlending, BufferGeometry, Float32BufferAttribute, Group, MeshBasicMaterial, MeshStandardMaterial, RepeatWrapping, RingGeometry } from "three";
-import { cachedCanvasTexture } from "./canvasMaterials";
+import { Group, MeshStandardMaterial } from "three";
import { Instances, type Placement } from "./CodingFloorAmbience";
import { Box, GEO, matte, Railing } from "./OfficeFurniture";
import type { OfficeLayout, Rect } from "./officeLayout";
+import { SingularityCity } from "./SingularityCity";
/** The window wall: its height, the mullion pitch, and how far the ceiling edge reaches into the floor. */
export const FACADE = { h: 3.4, pitch: 2.9, soffit: 1.1 } as const;
-/** Metres of façade one repeat of the window texture covers (four windows across, four storeys up). */
-const WINDOW_TILE_M = 12;
/** A side's window wall changes only once the camera is this far past the floor's middle, so it never flickers. */
const SIDE_DEAD_BAND_M = 4;
@@ -42,168 +30,8 @@ const SHELL = {
steel: matte("#23262b", { roughness: 0.45, metalness: 0.4 }),
soffit: matte("#f1ede6", { roughness: 0.9 }),
glass: new MeshStandardMaterial({ color: "#cfe6f7", transparent: true, opacity: 0.16, roughness: 0.08, metalness: 0.1, depthWrite: false }),
- roof: matte("#0f1420", { roughness: 0.95 }),
-};
-
-function lcg(seed: number): () => number {
- let state = seed >>> 0;
- return () => {
- state = (state * 1664525 + 1013904223) >>> 0;
- return state / 0x1_0000_0000;
- };
-}
-
-/** A tower's cladding at night: a shade lighter than the sky (#0d1320), so a near tower reads against it. */
-const CLADDING = "#141b2b";
-
-let windows: MeshBasicMaterial | null = null;
-/**
- * A tower's face at night, unlit so the scene's sun never touches it: cladding a shade off the sky and rows of
- * windows of which about one in twenty is lit, dimly and mostly warm. One 128 px tile for the whole city; a
- * tower's own colour (towards the sky's with distance) and its vertex colours (towards the foot) multiply it.
- */
-function windowMaterial(): MeshBasicMaterial {
- if (!windows) {
- const map = cachedCanvasTexture("shell:windows:night", 128, 128, (ctx, w, h) => {
- const rand = lcg(0xc17e);
- ctx.fillStyle = CLADDING;
- ctx.fillRect(0, 0, w, h);
- const cols = 8, rows = 8, cw = w / cols, rh = h / rows;
- for (let r = 0; r < rows; r += 1) {
- for (let c = 0; c < cols; c += 1) {
- const roll = rand();
- ctx.fillStyle = roll < 0.04 ? "#6f5b3c" : roll < 0.055 ? "#3c475c" : "#101726";
- ctx.fillRect(c * cw + 4, r * rh + 5, cw - 8, rh - 11);
- }
- }
- });
- if (map) { map.wrapS = map.wrapT = RepeatWrapping; map.anisotropy = 4; }
- windows = new MeshBasicMaterial({ color: map ? "#ffffff" : CLADDING, map, vertexColors: true });
- }
- return windows;
-}
-
-/** How dark a tower's foot is against its roof line (in linear light): at the foot the cladding is about the sky's colour. */
-const FOOT_SHADE = 0.72;
-
-/**
- * A tower w × h × d, its roof at y = 0: four faces with texture coordinates
- * in metres of façade (every tower shows windows of the same size) and the
- * roof, which takes the cladding's colour from the tile's margin. The vertex
- * colours darken the faces towards the foot.
- */
-function towerGeometry(w: number, h: number, d: number): BufferGeometry {
- const positions: number[] = [], normals: number[] = [], uvs: number[] = [], colours: number[] = [], index: number[] = [];
- const face = (ax: number, az: number, bx: number, bz: number, nx: number, nz: number) => {
- const at = positions.length / 3, run = Math.hypot(bx - ax, bz - az) / WINDOW_TILE_M, rise = h / WINDOW_TILE_M;
- positions.push(ax, -h, az, bx, -h, bz, bx, 0, bz, ax, 0, az);
- for (let i = 0; i < 4; i += 1) normals.push(nx, 0, nz);
- uvs.push(0, 0, run, 0, run, rise, 0, rise);
- colours.push(FOOT_SHADE, FOOT_SHADE, FOOT_SHADE, FOOT_SHADE, FOOT_SHADE, FOOT_SHADE, 1, 1, 1, 1, 1, 1);
- index.push(at, at + 1, at + 2, at, at + 2, at + 3);
- };
- const x = w / 2, z = d / 2;
- face(-x, z, x, z, 0, 1);
- face(x, z, x, -z, 1, 0);
- face(x, -z, -x, -z, 0, -1);
- face(-x, -z, -x, z, -1, 0);
- // The roof: every corner samples the tile's margin, which is plain cladding.
- const at = positions.length / 3;
- positions.push(-x, 0, z, x, 0, z, x, 0, -z, -x, 0, -z);
- for (let i = 0; i < 4; i += 1) { normals.push(0, 1, 0); uvs.push(0.008, 0.008); colours.push(1, 1, 1); }
- index.push(at, at + 1, at + 2, at, at + 2, at + 3);
- const geometry = new BufferGeometry();
- geometry.setAttribute("position", new Float32BufferAttribute(positions, 3));
- geometry.setAttribute("normal", new Float32BufferAttribute(normals, 3));
- geometry.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
- geometry.setAttribute("color", new Float32BufferAttribute(colours, 3));
- geometry.setIndex(index);
- return geometry;
-}
-
-/** Tower sizes of the city: every tower of a class shares one geometry, so each class is one draw call. */
-const TOWER_CLASSES = [{ w: 14, d: 14, h: 110 }, { w: 22, d: 16, h: 110 }, { w: 30, d: 20, h: 110 }] as const;
-/**
- * The city's reserve. `clear`: empty air round the building before the first tower. `reach`: how far the city
- * goes on from there. `roofTop`: the highest any roof comes, metres below the floor; the towers nearest the
- * building lie `nearDrop` lower still, and each a random share of `roofDrop` below that. `near`/`far`: a
- * tower's tint beside the clear air and at the city's far end, where the cladding comes out at the sky's colour.
- */
-const CITY = { clear: 62, reach: 170, towers: 60, roofTop: -24, nearDrop: 22, roofDrop: 56, near: 1, far: 0.8, haze: -64 } as const;
-
-const grey = (v: number): string => {
- const c = Math.round(Math.min(1, Math.max(0, v)) * 255).toString(16).padStart(2, "0");
- return `#${c}${c}${c}`;
};
-/** How bright the haze is at each of its rings, from the building outwards: nothing, rising, full, fading, nothing. */
-const HAZE_RINGS = [0, 0.55, 1, 0.45, 0] as const;
-/**
- * The glow of streets too far down to see, added over the night. In LINEAR light, where the sky itself is about
- * (0.004, 0.007, 0.014): at its brightest the haze lifts the navy to about #181b27 and no further.
- */
-const HAZE_TONE = [0.005, 0.0045, 0.006] as const;
-const HAZE_MATERIAL = new MeshBasicMaterial({
- vertexColors: true, transparent: true, blending: AdditiveBlending, depthWrite: false, fog: false, toneMapped: false,
-});
-
-/** A flat ring of haze from `inner` to `outer` metres, brightest a third of the way out. */
-function hazeGeometry(inner: number, outer: number): BufferGeometry {
- const rings = HAZE_RINGS.length - 1, segments = 48;
- const geometry = new RingGeometry(inner, outer, segments, rings).rotateX(-Math.PI / 2);
- const colours: number[] = [];
- for (let ring = 0; ring <= rings; ring += 1) {
- for (let s = 0; s <= segments; s += 1) colours.push(HAZE_TONE[0] * HAZE_RINGS[ring], HAZE_TONE[1] * HAZE_RINGS[ring], HAZE_TONE[2] * HAZE_RINGS[ring]);
- }
- geometry.setAttribute("color", new Float32BufferAttribute(colours, 3));
- return geometry;
-}
-
-/**
- * The city: a thin field of towers whose roofs all lie far below the floor,
- * the nearest lowest, so none ever rises into the view or stands in front of
- * the office, and a ring of haze over their feet.
- */
-function Skyline({ bounds }: { bounds: Rect }) {
- const cx = (bounds.minX + bounds.maxX) / 2, cz = (bounds.minZ + bounds.maxZ) / 2;
- const halfW = (bounds.maxX - bounds.minX) / 2, halfD = (bounds.maxZ - bounds.minZ) / 2;
- const geometries = useMemo(() => TOWER_CLASSES.map((c) => towerGeometry(c.w, c.h, c.d)), []);
- useEffect(() => () => { for (const g of geometries) g.dispose(); }, [geometries]);
- const haze = useMemo(() => hazeGeometry(Math.hypot(halfW, halfD) + 6, Math.hypot(halfW, halfD) + CITY.clear + CITY.reach + 80), [halfW, halfD]);
- useEffect(() => () => haze.dispose(), [haze]);
- const towers = useMemo(() => {
- const rand = lcg(0x51a7e);
- const towers: Placement[][] = TOWER_CLASSES.map(() => []);
- const taken: { x: number; z: number; r: number }[] = [];
- for (let i = 0; i < CITY.towers; i += 1) {
- const angle = rand() * Math.PI * 2, far = rand(), reach = CITY.clear + far * CITY.reach;
- const x = cx + Math.cos(angle) * (halfW + reach), z = cz + Math.sin(angle) * (halfD + reach);
- const kind = Math.floor(rand() * TOWER_CLASSES.length);
- const top = CITY.roofTop - (1 - far) * CITY.nearDrop - rand() * rand() * CITY.roofDrop;
- // Wide gaps: the city is a few silhouettes, never a wall.
- const size = TOWER_CLASSES[kind], r = Math.hypot(size.w, size.d) / 2 + 9;
- if (taken.some((t) => Math.hypot(t.x - x, t.z - z) < t.r + r)) continue;
- taken.push({ x, z, r });
- towers[kind].push({ position: [x, top, z], scale: [1, 1, 1], color: grey(CITY.near + (CITY.far - CITY.near) * far) });
- }
- return towers;
- }, [cx, cz, halfW, halfD]);
- return (
- <group>
- {geometries.map((geometry, i) => <Instances key={i} geometry={geometry} material={windowMaterial()} items={towers[i]} cast={false} />)}
- <mesh geometry={haze} material={HAZE_MATERIAL} position={[cx, CITY.haze, cz]} renderOrder={1} />
- </group>
- );
-}
-
-/** The building's own body under the slab: the tower this floor belongs to, dark and plain so the floor above it carries. */
-function TowerBody({ bounds }: { bounds: Rect }) {
- const w = bounds.maxX - bounds.minX - 1.2, d = bounds.maxZ - bounds.minZ - 1.2;
- const geometry = useMemo(() => towerGeometry(w, 140, d), [w, d]);
- useEffect(() => () => geometry.dispose(), [geometry]);
- return <mesh geometry={geometry} material={SHELL.roof} position={[(bounds.minX + bounds.maxX) / 2, -0.6, (bounds.minZ + bounds.maxZ) / 2]} />;
-}
-
type Side = "north" | "south" | "west" | "east";
/** One side's window wall, in its own frame: it runs along +x, the floor lies towards +z. */
@@ -273,11 +101,10 @@ function Edges({ bounds }: { bounds: Rect }) {
);
}
-export function BuildingShell({ layout }: { layout: OfficeLayout }) {
+export function BuildingShell({ layout, reduced = false }: { layout: OfficeLayout; reduced?: boolean }) {
return (
<group>
- <Skyline bounds={layout.bounds} />
- <TowerBody bounds={layout.bounds} />
+ <SingularityCity bounds={layout.bounds} reduced={reduced} />
<Edges bounds={layout.bounds} />
</group>
);
diff --git a/jarvis/ui/web/frontend/src/components/society/office/CampusScene.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/CampusScene.test.tsx
index b4d7223b95..9ec23d1c2c 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/CampusScene.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/CampusScene.test.tsx
@@ -7,11 +7,13 @@ import { AgentsDepartment, AgentsSlab } from "./AgentsFloorLook";
import { AgentsFloorAmbience } from "./AgentsFloorAmbience";
import { BuildingShell, FACADE } from "./BuildingShell";
import { CampusGround } from "./CampusGround";
+import { GROUND_Y } from "./cityPlan";
import { DeskDressing } from "./DeskDressing";
import { DeskInstances } from "./DeskInstances";
import { buildHallLayout } from "./hallFloorLayout";
import { buildOfficeLayout, type OfficeAgentInput, type OfficeLayout, type OfficeTeamInput } from "./officeLayout";
import { FurniturePiece, MeetingChairs } from "./OfficeProps";
+import { SingularityCity } from "./SingularityCity";
import { StaticBatch } from "./StaticBatch";
import { ToyFigure } from "./ToyFigure";
import { loadProfile, playerLook } from "./playerProfile";
@@ -229,6 +231,30 @@ describe("campus scene", () => {
expect(visible).toHaveLength(2);
});
+ it("draws the city outside in a couple of dozen draw calls, none of them in the shadow pass, its towers on the street level far below", async () => {
+ const layout = buildOfficeLayout(staff(5));
+ const city = await mount(<SingularityCity bounds={layout.bounds} />);
+ city.updateMatrixWorld(true);
+ let draws = 0, instances = 0;
+ city.traverse((child) => {
+ const mesh = child as Mesh;
+ if (!(mesh as { isMesh?: boolean; isPoints?: boolean }).isMesh && !(child as { isPoints?: boolean }).isPoints) return;
+ draws += 1;
+ expect(mesh.castShadow, child.type).toBe(false);
+ expect(mesh.receiveShadow, child.type).toBe(false);
+ if ((child as InstancedMesh).isInstancedMesh) instances += (child as InstancedMesh).count;
+ });
+ expect(draws).toBeLessThanOrEqual(24);
+ // Hundreds of towers, every one of them instanced.
+ expect(instances).toBeGreaterThan(400);
+ // The tower classes stand on the street level, far under the floor.
+ city.traverse((child) => {
+ if (!child.userData.cityTowers) return;
+ const box = new Box3().setFromObject(child);
+ expect(box.min.y).toBeCloseTo(GROUND_Y, 0);
+ });
+ });
+
it("tags every room wall run for the camera's cutaway", async () => {
const layout = buildOfficeLayout(staff(5));
const group = await mount(<RoomWalls walls={layout.walls} />);
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx
index d9a51ccb03..155563396b 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx
@@ -1,5 +1,6 @@
/**
- * The office floors: an oak-floored plate floating in a starry night behind
+ * The office floors: an oak-floored plate high over the city in the
+ * singularity (the coding floor in a starry violet night of its own) behind
* frameless glass, walled rooms in the north and south and the desks in
* between — and everybody in it. The agents floor is a team campus (a studio
* per team round an atrium, boulevards, planted courts), the coding floor has
@@ -24,6 +25,7 @@ import { AgentsFloorAmbience } from "./AgentsFloorAmbience";
import { CampusGround } from "./CampusGround";
import { StaticBatch } from "./StaticBatch";
import { BuildingShell } from "./BuildingShell";
+import { CITY_BACKDROP } from "./SingularityCity";
import { ExecutiveDesks, LeadOfficeLight } from "./LeadSuite";
import { LiveMonitors } from "./LiveMonitors";
import { TerminalMonitors } from "./TerminalMonitors";
@@ -50,7 +52,7 @@ import { PlayerBubble } from "./OfficeBubbles";
import { OfficeCameraRig } from "./OfficeCameraRig";
import { allDesks, leadDesks, type FurnitureKind, type OfficeLayout, type Point } from "./officeLayout";
import { isWalkable, nearestWalkable, type NavGrid } from "./officeNav";
-import { CODING_SCENE, OFFICE } from "./officePalette";
+import { CODING_SCENE } from "./officePalette";
import { officeSession, player as playerBody, useOfficeStore, type OfficeFloor, type Selection } from "./officeStore";
import { arrivalPose } from "./officeFloors";
import { ProgressionLayer } from "../progression/ProgressionLayer";
@@ -191,8 +193,8 @@ function OfficeFloorDressing({ floor, occupants, layout, agents, newcomers, awak
const teamRoom = layout.rooms.find((r) => r.kind === "team");
const breakRoom = layout.rooms.find((r) => r.kind === "break");
const coding = floor === "coding";
- // The coding floor floats in a violet night of its own, so a glance tells the floors apart.
- const space = coding ? CODING_SCENE.space : OFFICE.space;
+ // The coding floor floats in a violet night of its own, so a glance tells the floors apart; the others stand in the city's haze.
+ const space = coding ? CODING_SCENE.space : CITY_BACKDROP;
const background = useMemo(() => new Color(space), [space]);
const { minX, maxX, minZ, maxZ } = layout.bounds;
const span = Math.max(maxX - minX, maxZ - minZ);
@@ -219,7 +221,8 @@ function OfficeFloorDressing({ floor, occupants, layout, agents, newcomers, awak
<>
<primitive attach="background" object={background} />
<fog attach="fog" args={[space, span * 2.2, span * 4.5]} />
- <Stars radius={span * 3} depth={span} count={2500} factor={4} saturation={0} fade speed={reduced ? 0 : 0.3} />
+ {/* The city's sky has its own stars, above a horizon the camera never shows; the coding floor's night is all stars. */}
+ {coding && <Stars radius={span * 3} depth={span} count={2500} factor={4} saturation={0} fade speed={reduced ? 0 : 0.3} />}
<hemisphereLight args={coding ? [CODING_SCENE.sky, CODING_SCENE.ground, 0.95] : [AGENTS_SCENE.sky, AGENTS_SCENE.ground, 0.95]} />
<ambientLight intensity={0.25} />
{/* The campus is twice as long as the other floors: its sun keeps the same shadow detail with a larger map. */}
@@ -230,7 +233,7 @@ function OfficeFloorDressing({ floor, occupants, layout, agents, newcomers, awak
{coding ? <CodingSlab layout={layout} onFloorClick={onFloorClick} /> : <AgentsSlab layout={layout} onFloorClick={onFloorClick} />}
{coding ? <CodingFloorAmbience layout={layout} /> : <AgentsFloorAmbience layout={layout} />}
{/* The agents floor and the Level Hall are floors of a building: window walls, the tower below, the city outside. */}
- {!coding && <BuildingShell layout={layout} />}
+ {!coding && <BuildingShell layout={layout} reduced={reduced} />}
<RoomFloors rooms={layout.rooms} campus={!coding} />
<RoomWalls walls={layout.walls} />
{!batch && signs}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
index 485e681ff5..17c67cb02a 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
@@ -605,7 +605,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
{webgl ? (
<RenderBoundary key={generation} fallbackText={t("society.office.no_graphics")}>
<Suspense fallback={<div className="office-fallback" role="status">{t("society.office.loading")}</div>}>
- <Canvas shadows="percentage" camera={{ fov: CAMERA_FOV, near: 0.2, far: 800, position: [30, 30, 30] }} dpr={dpr}
+ <Canvas shadows="percentage" camera={{ fov: CAMERA_FOV, near: 0.2, far: 1400, position: [30, 30, 30] }} dpr={dpr}
gl={{ antialias: true, alpha: true, preserveDrawingBuffer: import.meta.env.DEV }}
frameloop={!awake ? "never" : compact ? "demand" : "always"}
onPointerMissed={() => select(null)}>
diff --git a/jarvis/ui/web/frontend/src/components/society/office/SingularityCity.tsx b/jarvis/ui/web/frontend/src/components/society/office/SingularityCity.tsx
new file mode 100644
index 0000000000..799e24ee5a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/SingularityCity.tsx
@@ -0,0 +1,316 @@
+/**
+ * The city outside the Dodaios tower: a megacity in the singularity, seen from
+ * high above. Hundreds of glass towers on a street grid with lit windows,
+ * light seams and crowns, avenues full of traffic, flying traffic weaving
+ * round the tower above the roofs, beams of light over the tallest roofs,
+ * drifting mist, and off to the north the singularity itself: a black core
+ * with its photon ring, a turning accretion disc, polar jets and three
+ * orbital rings, inside a crater ringed by gold-crowned spires.
+ *
+ * The plan is pure (cityPlan.ts), every surface a shader of its own
+ * (cityShaders.ts). Everything is instanced or computed on the GPU: about
+ * twenty draw calls in all, nothing casts or receives a shadow, and the only
+ * per-frame work is advancing one clock, keeping the sky round the camera
+ * and turning the lens and the rings. With reduced motion the clock stands.
+ */
+import { useEffect, useLayoutEffect, useMemo, useRef } from "react";
+import { useFrame } from "@react-three/fiber";
+import {
+ BufferGeometry, Color, CylinderGeometry, Euler, Float32BufferAttribute, Group, InstancedBufferAttribute, InstancedBufferGeometry,
+ InstancedMesh, Matrix4, type Mesh, PlaneGeometry, Quaternion, RingGeometry, SphereGeometry, TorusGeometry, Vector3,
+} from "three";
+import {
+ beaconMaterial, beamMaterial, CITY_PALETTE, cityUniforms, coreMaterial, discMaterial, groundMaterial, lensMaterial, mistMaterial,
+ orbitalRingMaterial, skyMaterial, towerMaterial, trafficMaterial, type CityUniforms,
+} from "./cityShaders";
+import { CITY, GROUND_Y, lcg, planCity, SINGULARITY, TOWER_KINDS, type CityPlan, type Tower, type TowerKind } from "./cityPlan";
+import type { Rect } from "./officeLayout";
+
+/** The colour behind and below the city (the sky's deep haze): the scene's background and fog for these floors. */
+export const CITY_BACKDROP = CITY_PALETTE.below;
+
+// ---------------------------------------------------------------------------
+// Tower geometry: unit towers (foot at y = 0, top at y = 1, footprint 1 × 1)
+// ---------------------------------------------------------------------------
+
+interface Builder { positions: number[]; normals: number[]; tiers: number[]; index: number[] }
+
+function pushQuad(b: Builder, a: number[], bb: number[], c: number[], d: number[], n: number[], tier: number[]) {
+ const at = b.positions.length / 3;
+ b.positions.push(...a, ...bb, ...c, ...d);
+ for (let i = 0; i < 4; i += 1) { b.normals.push(...n); b.tiers.push(...tier); }
+ b.index.push(at, at + 1, at + 2, at, at + 2, at + 3);
+}
+
+/** A box tier from y0 to y1, half size hx × hz, with its roof; corners carry seams. */
+function boxTier(b: Builder, hx: number, hz: number, y0: number, y1: number) {
+ const tier = [hx, hz, y1, 1];
+ pushQuad(b, [-hx, y0, hz], [hx, y0, hz], [hx, y1, hz], [-hx, y1, hz], [0, 0, 1], tier);
+ pushQuad(b, [hx, y0, hz], [hx, y0, -hz], [hx, y1, -hz], [hx, y1, hz], [1, 0, 0], tier);
+ pushQuad(b, [hx, y0, -hz], [-hx, y0, -hz], [-hx, y1, -hz], [hx, y1, -hz], [0, 0, -1], tier);
+ pushQuad(b, [-hx, y0, -hz], [-hx, y0, hz], [-hx, y1, hz], [-hx, y1, -hz], [-1, 0, 0], tier);
+ pushQuad(b, [-hx, y1, hz], [hx, y1, hz], [hx, y1, -hz], [-hx, y1, -hz], [0, 1, 0], tier);
+}
+
+/** An eight-sided prism from y0 to y1, tapering from radius r0 to r1, with a flat roof (no corner seams). */
+function prismTier(b: Builder, r0: number, r1: number, y0: number, y1: number, roof: boolean) {
+ const sides = 8, tier = [r1, r1, y1, 0];
+ for (let i = 0; i < sides; i += 1) {
+ const a0 = (i / sides) * Math.PI * 2, a1 = ((i + 1) / sides) * Math.PI * 2, am = (a0 + a1) / 2;
+ const slope = (r0 - r1) / (y1 - y0);
+ const n = new Vector3(Math.cos(am), slope, Math.sin(am)).normalize();
+ pushQuad(b,
+ [Math.cos(a1) * r0, y0, Math.sin(a1) * r0], [Math.cos(a0) * r0, y0, Math.sin(a0) * r0],
+ [Math.cos(a0) * r1, y1, Math.sin(a0) * r1], [Math.cos(a1) * r1, y1, Math.sin(a1) * r1], [n.x, n.y, n.z], tier);
+ }
+ if (!roof) return;
+ const at = b.positions.length / 3;
+ b.positions.push(0, y1, 0); b.normals.push(0, 1, 0); b.tiers.push(...tier);
+ for (let i = 0; i <= sides; i += 1) {
+ const a = (i / sides) * Math.PI * 2;
+ b.positions.push(Math.cos(a) * r1, y1, Math.sin(a) * r1); b.normals.push(0, 1, 0); b.tiers.push(...tier);
+ }
+ for (let i = 0; i < sides; i += 1) b.index.push(at, at + 2 + i, at + 1 + i);
+}
+
+/** A needle: eight steep sides from radius r0 at y0 to a point at y1 (its faces stay façades, not roofs). */
+function needle(b: Builder, r0: number, y0: number, y1: number) {
+ prismTier(b, r0, 0.002, y0, y1, false);
+}
+
+export function towerGeometry(kind: TowerKind): BufferGeometry {
+ const b: Builder = { positions: [], normals: [], tiers: [], index: [] };
+ if (kind === "block") boxTier(b, 0.5, 0.5, 0, 1);
+ if (kind === "setback") { boxTier(b, 0.5, 0.5, 0, 0.58); boxTier(b, 0.38, 0.38, 0.58, 0.84); boxTier(b, 0.25, 0.25, 0.84, 1); }
+ if (kind === "prism") prismTier(b, 0.5, 0.42, 0, 1, true);
+ if (kind === "spire") { prismTier(b, 0.5, 0.4, 0, 0.8, true); prismTier(b, 0.22, 0.16, 0.8, 0.9, true); needle(b, 0.06, 0.9, 1); }
+ const g = new BufferGeometry();
+ g.setAttribute("position", new Float32BufferAttribute(b.positions, 3));
+ g.setAttribute("normal", new Float32BufferAttribute(b.normals, 3));
+ g.setAttribute("aTier", new Float32BufferAttribute(b.tiers, 4));
+ g.setIndex(b.index);
+ return g;
+}
+
+const _m = new Matrix4(), _q = new Quaternion(), _e = new Euler(), _p = new Vector3(), _s = new Vector3();
+
+/** One class of towers: one instanced draw call, the per-tower look in instanced attributes. */
+function TowerClass({ kind, towers, material }: { kind: TowerKind; towers: readonly Tower[]; material: CityMaterial }) {
+ const geometry = useMemo(() => {
+ const g = towerGeometry(kind);
+ const look = new Float32Array(towers.length * 4), accent = new Float32Array(towers.length);
+ towers.forEach((t, i) => { look.set([t.seed, t.lit, t.seams ? 1 : 0, t.crown ? 1 : 0], i * 4); accent[i] = t.accent; });
+ g.setAttribute("aLook", new InstancedBufferAttribute(look, 4));
+ g.setAttribute("aAccent", new InstancedBufferAttribute(accent, 1));
+ return g;
+ }, [kind, towers]);
+ useEffect(() => () => geometry.dispose(), [geometry]);
+ const ref = useRef<InstancedMesh>(null);
+ useLayoutEffect(() => {
+ const mesh = ref.current;
+ if (!mesh) return;
+ towers.forEach((t, i) => {
+ _m.compose(_p.set(t.x, GROUND_Y, t.z), _q.setFromEuler(_e.set(0, t.rot, 0)), _s.set(t.w, t.h, t.d));
+ mesh.setMatrixAt(i, _m);
+ });
+ mesh.instanceMatrix.needsUpdate = true;
+ }, [towers]);
+ if (towers.length === 0) return null;
+ return <instancedMesh ref={ref} args={[geometry, material, towers.length]} frustumCulled={false} userData={{ cityTowers: kind }} />;
+}
+
+type CityMaterial = ReturnType<typeof towerMaterial>;
+
+/** The building's own tower under the slab, in the city's glass: gold seams, more lit windows than its neighbours. */
+function OwnTower({ bounds, material }: { bounds: Rect; material: CityMaterial }) {
+ const tower = useMemo<Tower[]>(() => [{
+ kind: "block", x: (bounds.minX + bounds.maxX) / 2, z: (bounds.minZ + bounds.maxZ) / 2,
+ w: bounds.maxX - bounds.minX - 1.2, d: bounds.maxZ - bounds.minZ - 1.2, h: -0.6 - GROUND_Y,
+ rot: 0, seed: 0.37, lit: 0.24, seams: true, crown: false, accent: 2,
+ }], [bounds]);
+ return <TowerClass kind="block" towers={tower} material={material} />;
+}
+
+/** Flying traffic: one streak per car, every car of every lane in one instanced draw call. */
+function Traffic({ plan, uniforms }: { plan: CityPlan; uniforms: CityUniforms }) {
+ const material = useMemo(() => trafficMaterial(uniforms), [uniforms]);
+ const geometry = useMemo(() => {
+ const quad = new PlaneGeometry(1, 1);
+ const g = new InstancedBufferGeometry();
+ g.index = quad.index;
+ g.setAttribute("position", quad.getAttribute("position"));
+ const total = plan.lanes.reduce((n, lane) => n + lane.cars, 0);
+ const orbit = new Float32Array(total * 4), motion = new Float32Array(total * 4), look = new Float32Array(total * 4);
+ const head = new Color(CITY_PALETTE.head), tail = new Color(CITY_PALETTE.tail), cyan = new Color(CITY_PALETTE.cyan), gold = new Color(CITY_PALETTE.accents[2]);
+ const rand = lcg(0x7a11c);
+ let i = 0;
+ plan.lanes.forEach((lane, laneIndex) => {
+ for (let c = 0; c < lane.cars; c += 1, i += 1) {
+ // Cars bunch a little along the lane instead of keeping an exact spacing.
+ const phase = ((c + (rand() - 0.5) * 0.7) / lane.cars) * Math.PI * 2;
+ // Two streams per lane, side by side, a car's lights showing the way it goes.
+ const offset = (c % 2 === 0 ? 1 : -1) * 2.4;
+ const roll = rand();
+ const colour = roll < 0.06 ? cyan : roll < 0.1 ? gold : lane.omega > 0 === (c % 2 === 0) ? head : tail;
+ orbit.set([lane.cx, lane.cz, lane.rx + offset, lane.rz + offset], i * 4);
+ motion.set([lane.y + (rand() - 0.5) * 1.5, phase, lane.omega * (c % 2 === 0 ? 1 : -1) * (0.9 + rand() * 0.2), lane.bob], i * 4);
+ look.set([colour.r, colour.g, colour.b, 4.5 + rand() * 3.5 + (laneIndex >= plan.lanes.length - 3 ? 3 : 0)], i * 4);
+ }
+ });
+ g.setAttribute("aOrbit", new InstancedBufferAttribute(orbit, 4));
+ g.setAttribute("aMotion", new InstancedBufferAttribute(motion, 4));
+ g.setAttribute("aLook", new InstancedBufferAttribute(look, 4));
+ g.instanceCount = total;
+ return g;
+ }, [plan]);
+ useEffect(() => () => material.dispose(), [material]);
+ useEffect(() => () => geometry.dispose(), [geometry]);
+ return <mesh geometry={geometry} material={material} frustumCulled={false} renderOrder={3} />;
+}
+
+function Beacons({ plan, uniforms }: { plan: CityPlan; uniforms: CityUniforms }) {
+ const material = useMemo(() => beaconMaterial(uniforms), [uniforms]);
+ const geometry = useMemo(() => {
+ const g = new BufferGeometry();
+ g.setAttribute("position", new Float32BufferAttribute(plan.beacons.flatMap((b) => [b.x, b.y, b.z]), 3));
+ g.setAttribute("aBeacon", new Float32BufferAttribute(plan.beacons.flatMap((b) => [b.kind, b.phase]), 2));
+ return g;
+ }, [plan]);
+ useEffect(() => () => material.dispose(), [material]);
+ useEffect(() => () => geometry.dispose(), [geometry]);
+ return <points geometry={geometry} material={material} frustumCulled={false} renderOrder={3} />;
+}
+
+const BEAM_COLOURS = CITY_PALETTE.accents.map((hex) => new Color(hex));
+
+function Beams({ plan, uniforms }: { plan: CityPlan; uniforms: CityUniforms }) {
+ const material = useMemo(() => beamMaterial(uniforms), [uniforms]);
+ const geometry = useMemo(() => new CylinderGeometry(1, 1, 1, 16, 1, true).translate(0, 0.5, 0), []);
+ useEffect(() => () => material.dispose(), [material]);
+ useEffect(() => () => geometry.dispose(), [geometry]);
+ const s = plan.singularity;
+ // The singularity's jets: up into the night and down to the crater floor, wider and brighter than a roof beam.
+ const beams = useMemo(() => [
+ ...plan.beams.map((b) => ({ ...b, colour: BEAM_COLOURS[b.accent], flip: false })),
+ { x: s.x, y: s.y + SINGULARITY.core * 0.6, z: s.z, height: 620, radius: 3.4, colour: new Color("#bfe9ff").multiplyScalar(1.6), flip: false },
+ { x: s.x, y: s.y - SINGULARITY.core * 0.6, z: s.z, height: s.y - SINGULARITY.core * 0.6 - GROUND_Y, radius: 3.4, colour: new Color("#bfe9ff").multiplyScalar(1.3), flip: true },
+ ], [plan, s]);
+ const ref = useRef<InstancedMesh>(null);
+ useLayoutEffect(() => {
+ const mesh = ref.current;
+ if (!mesh) return;
+ beams.forEach((b, i) => {
+ _m.compose(_p.set(b.x, b.y, b.z), _q.setFromEuler(_e.set(b.flip ? Math.PI : 0, 0, 0)), _s.set(b.radius, b.height, b.radius));
+ mesh.setMatrixAt(i, _m);
+ mesh.setColorAt(i, b.colour);
+ });
+ mesh.instanceMatrix.needsUpdate = true;
+ if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
+ }, [beams]);
+ return <instancedMesh ref={ref} args={[geometry, material, beams.length]} frustumCulled={false} renderOrder={4} />;
+}
+
+/** The singularity: core, disc, lens, and the three orbital rings turning round it. */
+function Singularity({ plan, uniforms, reduced }: { plan: CityPlan; uniforms: CityUniforms; reduced: boolean }) {
+ const s = plan.singularity, size = SINGULARITY.core * 9;
+ const parts = useMemo(() => ({
+ core: coreMaterial(uniforms),
+ disc: discMaterial(uniforms, SINGULARITY.disc.inner, SINGULARITY.disc.outer),
+ lens: lensMaterial(uniforms, SINGULARITY.core, size),
+ rings: SINGULARITY.rings.map((r) => orbitalRingMaterial(uniforms, Math.sign(r.speed))),
+ }), [uniforms, size]);
+ const geometries = useMemo(() => ({
+ core: new SphereGeometry(SINGULARITY.core, 48, 32),
+ disc: new RingGeometry(SINGULARITY.disc.inner, SINGULARITY.disc.outer, 160, 1),
+ lens: new PlaneGeometry(size, size),
+ rings: SINGULARITY.rings.map((r) => new TorusGeometry(r.radius, 0.9, 8, 256)),
+ }), [size]);
+ useEffect(() => () => { parts.core.dispose(); parts.disc.dispose(); parts.lens.dispose(); for (const m of parts.rings) m.dispose(); }, [parts]);
+ useEffect(() => () => {
+ geometries.core.dispose(); geometries.disc.dispose(); geometries.lens.dispose(); for (const g of geometries.rings) g.dispose();
+ }, [geometries]);
+ const lens = useRef<Mesh>(null);
+ const rings = useRef<(Group | null)[]>([]);
+ useFrame(({ camera }, dt) => {
+ lens.current?.quaternion.copy(camera.quaternion);
+ if (reduced) return;
+ SINGULARITY.rings.forEach((r, i) => { const g = rings.current[i]; if (g) g.rotation.z += r.speed * Math.min(dt, 0.1); });
+ });
+ return (
+ <group position={[s.x, s.y, s.z]}>
+ <mesh geometry={geometries.core} material={parts.core} />
+ <mesh geometry={geometries.disc} material={parts.disc} rotation={[-Math.PI / 2 + SINGULARITY.disc.tilt, 0, 0.3]} renderOrder={2} />
+ <mesh ref={lens} geometry={geometries.lens} material={parts.lens} renderOrder={5} />
+ {SINGULARITY.rings.map((r, i) => (
+ <group key={i} rotation={[Math.PI / 2 + r.tilt[0], r.tilt[1], 0]}>
+ <group ref={(g) => { rings.current[i] = g; }}>
+ <mesh geometry={geometries.rings[i]} material={parts.rings[i]} renderOrder={3} />
+ </group>
+ </group>
+ ))}
+ </group>
+ );
+}
+
+/** Two sheets of drifting mist between the roofs. */
+const MIST_SHEETS = [{ y: GROUND_Y + 60, strength: 0.2, drift: 1 }, { y: GROUND_Y + 150, strength: 0.1, drift: -1.4 }] as const;
+
+export function SingularityCity({ bounds: given, reduced = false }: { bounds: Rect; reduced?: boolean }) {
+ // Keyed on the floor's size, not the object: every rebuilt layout passes a new one, and a new plan would mean
+ // new materials and compiling every shader again.
+ const { minX, maxX, minZ, maxZ } = given;
+ const bounds = useMemo<Rect>(() => ({ minX, maxX, minZ, maxZ }), [minX, maxX, minZ, maxZ]);
+ const plan = useMemo(() => planCity(bounds), [bounds]);
+ const plaza = Math.hypot(bounds.maxX - bounds.minX, bounds.maxZ - bounds.minZ) / 2 + CITY.clear - 6;
+ // The materials live as long as the city does; a new plan (a floor that changed size) only moves their uniforms.
+ const [uniforms, materials] = useMemo(() => {
+ const shared = cityUniforms(plan.singularity);
+ return [shared, {
+ tower: towerMaterial(shared),
+ ground: groundMaterial(shared, plan.centre, CITY.cell, CITY.avenueEvery, plaza),
+ mist: MIST_SHEETS.map((m) => mistMaterial(shared, plan.centre, plaza, m.strength, m.drift)),
+ sky: skyMaterial(shared),
+ }] as const;
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+ useEffect(() => {
+ uniforms.uSing.value.set(plan.singularity.x, plan.singularity.y, plan.singularity.z);
+ for (const m of [materials.ground, ...materials.mist]) {
+ m.uniforms.uCentre.value = [plan.centre.x, plan.centre.z];
+ m.uniforms.uPlaza.value = plaza;
+ }
+ }, [uniforms, materials, plan, plaza]);
+ const geometries = useMemo(() => ({
+ ground: new PlaneGeometry(CITY.radius * 2.8, CITY.radius * 2.8).rotateX(-Math.PI / 2),
+ mist: new PlaneGeometry(CITY.radius * 2.4, CITY.radius * 2.4).rotateX(-Math.PI / 2),
+ sky: new SphereGeometry(500, 48, 24),
+ }), []);
+ useEffect(() => () => {
+ materials.tower.dispose(); materials.ground.dispose(); materials.sky.dispose(); for (const m of materials.mist) m.dispose();
+ }, [materials]);
+ useEffect(() => () => { geometries.ground.dispose(); geometries.mist.dispose(); geometries.sky.dispose(); }, [geometries]);
+ const byKind = useMemo(() => TOWER_KINDS.map((kind) => plan.towers.filter((t) => t.kind === kind)), [plan]);
+ const sky = useRef<Mesh>(null);
+ useFrame(({ camera, size, viewport }, dt) => {
+ sky.current?.position.copy(camera.position);
+ const fov = "fov" in camera ? (camera as { fov: number }).fov : 35;
+ uniforms.uPxScale.value = (size.height * viewport.dpr) / (2 * Math.tan((fov * Math.PI) / 360));
+ // The clock wraps once a day so its precision never decays; traffic and pulses jump once at the wrap.
+ if (!reduced) uniforms.uTime.value = (uniforms.uTime.value + Math.min(dt, 0.1)) % 86_400;
+ });
+ return (
+ <group userData={{ city: "singularity" }}>
+ <mesh ref={sky} geometry={geometries.sky} material={materials.sky} renderOrder={-1000} frustumCulled={false} />
+ <mesh geometry={geometries.ground} material={materials.ground} position={[plan.centre.x, GROUND_Y, plan.centre.z]} />
+ {TOWER_KINDS.map((kind, i) => <TowerClass key={kind} kind={kind} towers={byKind[i]} material={materials.tower} />)}
+ <OwnTower bounds={bounds} material={materials.tower} />
+ {MIST_SHEETS.map((m, i) => (
+ <mesh key={i} geometry={geometries.mist} material={materials.mist[i]} position={[plan.centre.x, m.y, plan.centre.z]} renderOrder={1} />
+ ))}
+ <Traffic plan={plan} uniforms={uniforms} />
+ <Beacons plan={plan} uniforms={uniforms} />
+ <Beams plan={plan} uniforms={uniforms} />
+ <Singularity plan={plan} uniforms={uniforms} reduced={reduced} />
+ </group>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/cityPlan.test.ts b/jarvis/ui/web/frontend/src/components/society/office/cityPlan.test.ts
new file mode 100644
index 0000000000..6b6560be05
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/cityPlan.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it } from "vitest";
+import { CITY, distanceToRect, GROUND_Y, planCity, roofLimit, SINGULARITY, singularityPosition } from "./cityPlan";
+import { cityUniforms, lensMaterial } from "./cityShaders";
+import type { Rect } from "./officeLayout";
+
+/** A small floor (the Level Hall's size), a typical campus and a large one, not centred on the origin. */
+const FLOORS: Record<string, Rect> = {
+ hall: { minX: -14, maxX: 14, minZ: -10, maxZ: 10 },
+ campus: { minX: -6, maxX: 92, minZ: -4, maxZ: 64 },
+ large: { minX: -70, maxX: 70, minZ: -45, maxZ: 45 },
+};
+
+describe("the city plan", () => {
+ for (const [name, bounds] of Object.entries(FLOORS)) {
+ const plan = planCity(bounds);
+
+ it(`is a dense city and the same every time (${name})`, () => {
+ expect(plan.towers.length).toBeGreaterThan(400);
+ expect(planCity(bounds)).toEqual(plan);
+ });
+
+ it(`keeps the plaza round the building empty (${name})`, () => {
+ for (const t of plan.towers) {
+ const reach = Math.hypot(t.w, t.d) / 2;
+ expect(distanceToRect(t.x, t.z, bounds) - reach).toBeGreaterThanOrEqual(CITY.clear - 0.01);
+ }
+ });
+
+ it(`keeps every roof near the building far below the floor, the nearest lowest (${name})`, () => {
+ for (const t of plan.towers) {
+ const roof = GROUND_Y + t.h;
+ const edge = distanceToRect(t.x, t.z, bounds);
+ expect(roof).toBeLessThanOrEqual(roofLimit(edge) + 0.01);
+ if (edge < CITY.lowReach) expect(roof).toBeLessThanOrEqual(CITY.nearRoof);
+ }
+ // A roof beside the plaza lies over a hundred metres down.
+ expect(roofLimit(CITY.clear)).toBeLessThan(-150);
+ });
+
+ it(`puts no two towers on one spot (${name})`, () => {
+ const sorted = [...plan.towers].sort((a, b) => a.x - b.x);
+ for (let i = 0; i < sorted.length; i += 1) {
+ const a = sorted[i];
+ for (let j = i + 1; j < sorted.length && sorted[j].x - a.x < 40; j += 1) {
+ const b = sorted[j];
+ // Footprints as circles round their extent (rotated prisms included) for prisms, boxes for blocks.
+ const overlapX = Math.abs(a.x - b.x) < (a.w + b.w) / 2 - 0.5;
+ const overlapZ = Math.abs(a.z - b.z) < (a.d + b.d) / 2 - 0.5;
+ expect(overlapX && overlapZ, `${a.x},${a.z} / ${b.x},${b.z}`).toBe(false);
+ }
+ }
+ });
+
+ it(`clears a crater for the singularity, ringed by spires, its disc and rings inside it (${name})`, () => {
+ const s = singularityPosition(bounds);
+ expect(plan.singularity).toEqual(s);
+ const inCrater = plan.towers.filter((t) => Math.hypot(t.x - s.x, t.z - s.z) < SINGULARITY.crater);
+ expect(inCrater).toEqual([]);
+ expect(SINGULARITY.disc.outer).toBeLessThan(SINGULARITY.crater);
+ for (const r of SINGULARITY.rings) expect(r.radius).toBeLessThan(SINGULARITY.crater);
+ const spires = plan.towers.filter((t) => t.kind === "spire" && t.crown && t.accent === 2 && Math.hypot(t.x - s.x, t.z - s.z) <= SINGULARITY.spireRing[1] + 1);
+ expect(spires.length).toBe(SINGULARITY.spires);
+ // It hovers below the floor, well away from the building.
+ expect(s.y).toBeLessThan(-100);
+ expect(distanceToRect(s.x, s.z, bounds)).toBeGreaterThan(SINGULARITY.crater + CITY.clear);
+ });
+
+ it(`flies its traffic below the floor, outside the plaza and above the roofs it circles (${name})`, () => {
+ expect(plan.lanes.length).toBeGreaterThanOrEqual(8);
+ const half = Math.hypot(bounds.maxX - bounds.minX, bounds.maxZ - bounds.minZ) / 2;
+ const buildingLanes = plan.lanes.slice(0, plan.lanes.length - 3);
+ for (const lane of plan.lanes) {
+ expect(lane.y + lane.bob).toBeLessThan(-50);
+ expect(lane.cars).toBeGreaterThan(10);
+ expect(Math.abs(lane.omega)).toBeGreaterThan(0);
+ }
+ for (const lane of buildingLanes) {
+ expect(Math.min(lane.rx, lane.rz)).toBeGreaterThan(half + CITY.clear);
+ for (const t of plan.towers) {
+ // A tower under the lane's ellipse (within a tower's reach of it) stays below the lane.
+ const dx = (t.x - lane.cx) / lane.rx, dz = (t.z - lane.cz) / lane.rz;
+ const off = Math.abs(Math.hypot(dx, dz) - 1) * Math.min(lane.rx, lane.rz);
+ if (off < Math.hypot(t.w, t.d) / 2 + 3) expect(GROUND_Y + t.h, `${t.x},${t.z}`).toBeLessThan(lane.y - lane.bob - 2.4);
+ }
+ }
+ });
+
+ it(`puts beacons on the tall roofs and beams only on far towers (${name})`, () => {
+ expect(plan.beacons.length).toBeGreaterThan(20);
+ for (const b of plan.beams) expect(distanceToRect(b.x, b.z, bounds)).toBeGreaterThan(CITY.lowReach * 0.6);
+ });
+ }
+
+ it("keeps the same city round a floor that grows: only towers near the new plaza change", () => {
+ const before = FLOORS.campus, after = { ...before, maxX: before.maxX + 9, maxZ: before.maxZ + 5 };
+ const a = planCity(before), b = planCity(after);
+ expect(b.singularity).toEqual(a.singularity);
+ const key = (t: { x: number; z: number; h: number; kind: string }) => `${t.kind}@${t.x.toFixed(2)},${t.z.toFixed(2)}:${t.h.toFixed(2)}`;
+ const kept = new Set(b.towers.map(key));
+ const far = a.towers.filter((t) => distanceToRect(t.x, t.z, after) > CITY.lowReach + 20);
+ const same = far.filter((t) => kept.has(key(t)));
+ // Away from the building every tower stays exactly where and as tall as it was (lanes may trim a few).
+ expect(same.length / far.length).toBeGreaterThan(0.9);
+ });
+});
+
+describe("the singularity's lens", () => {
+ it("draws its photon ring just outside the core, wherever the sheet's size puts it", () => {
+ const size = SINGULARITY.core * 9;
+ const lens = lensMaterial(cityUniforms({ x: 0, y: 0, z: 0 }), SINGULARITY.core, size);
+ // The shader maps the sheet to -1..1; the core's share of that half width brings r = 1 to the core's edge.
+ const coreShare = lens.uniforms.uCore.value as number, sheet = lens.uniforms.uSize.value as number;
+ expect(coreShare * (sheet / 2)).toBeCloseTo(SINGULARITY.core, 6);
+ expect(lens.vertexShader).toContain("position.xy / (uSize * 0.5)");
+ lens.dispose();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/office/cityPlan.ts b/jarvis/ui/web/frontend/src/components/society/office/cityPlan.ts
new file mode 100644
index 0000000000..b1c1327e01
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/cityPlan.ts
@@ -0,0 +1,274 @@
+/**
+ * The plan of the city round the Dodaios tower: a dense megacity on a street
+ * grid far below the floor, its flying traffic, the light beams over its
+ * tallest roofs and the singularity it is built round. Pure and tested; the
+ * drawing lives in SingularityCity.tsx.
+ *
+ * The camera always looks down at the floor (the horizon never shows), so the
+ * city is composed to be seen from above: roofs, avenues and traffic lanes
+ * read at every zoom, and the singularity hovers over the rooftops off to
+ * the north where it shows beside the floor in the home view.
+ *
+ * Out of the way by construction: nothing stands within `CITY.clear` metres
+ * of the slab, every roof within `CITY.lowReach` metres lies at least
+ * `CITY.nearRoof` below the floor (lower the nearer it is), and every
+ * traffic lane flies above the roofs it circles.
+ */
+import type { Rect } from "./officeLayout";
+
+/** The city's street level, metres below the floor. */
+export const GROUND_Y = -330;
+
+export const CITY = {
+ /** The street grid: a cell per lot, an avenue every `avenueEvery` cells. */
+ cell: 36,
+ avenueEvery: 2,
+ /** Half widths of a street and an avenue, in metres from the grid line. */
+ street: 2.6,
+ avenue: 4.6,
+ /** Empty plaza round the building before the first tower, from the slab's edge. */
+ clear: 70,
+ /** How far the city reaches from the building's middle. */
+ radius: 700,
+ /** Within this distance of the slab's edge roofs stay well below the floor... */
+ lowReach: 330,
+ /** ...at least this far below at the edge of `lowReach`, `nearDrop` metres more at the plaza's edge. */
+ nearRoof: -70,
+ nearDrop: 100,
+} as const;
+
+/** The singularity: where it hovers (bearing from the building's middle, distance, height) and its parts' sizes. */
+export const SINGULARITY = {
+ bearing: [-0.3, -0.95] as const,
+ distance: 470,
+ y: -205,
+ core: 17,
+ disc: { inner: 22, outer: 112, tilt: 0.2 },
+ /** No ordinary tower within this distance of the core's foot: the disc floats over a clear crater. */
+ crater: 150,
+ /** The core district: tall spires on a ring round the crater, their crowns lit gold. */
+ spires: 18,
+ spireRing: [172, 212] as const,
+ /** Inside the crater, so no ring ever cuts a tower. */
+ rings: [
+ { radius: 84, tilt: [0.32, 0.1] as const, speed: 0.05 },
+ { radius: 102, tilt: [-0.22, 0.38] as const, speed: -0.035 },
+ { radius: 120, tilt: [0.12, -0.3] as const, speed: 0.024 },
+ ],
+} as const;
+
+/** Tower classes; the drawing has one geometry (and one draw call) per class. */
+export const TOWER_KINDS = ["block", "setback", "prism", "spire"] as const;
+export type TowerKind = (typeof TOWER_KINDS)[number];
+
+export interface Tower {
+ kind: TowerKind;
+ x: number;
+ z: number;
+ /** Footprint and height in metres; the foot stands on `GROUND_Y`. */
+ w: number;
+ d: number;
+ h: number;
+ /** Rotation about y (prisms and spires only; blocks follow the grid). */
+ rot: number;
+ /** Per-tower look: a random seed, the share of lit windows, light seams on its corners, a lit crown. */
+ seed: number;
+ lit: number;
+ seams: boolean;
+ crown: boolean;
+ /** 0 cool white, 1 cyan, 2 gold: the colour of its seams and crown. */
+ accent: 0 | 1 | 2;
+}
+
+export interface Lane {
+ /** An ellipse round (cx, cz) at height y; omega is radians per second, its sign the direction. */
+ cx: number;
+ cz: number;
+ rx: number;
+ rz: number;
+ y: number;
+ omega: number;
+ cars: number;
+ bob: number;
+}
+
+export interface Beam {
+ x: number;
+ y: number;
+ z: number;
+ height: number;
+ radius: number;
+ accent: 0 | 1 | 2;
+}
+
+export interface Beacon {
+ x: number;
+ y: number;
+ z: number;
+ /** 0 a slow red aviation light, 1 a white strobe. */
+ kind: 0 | 1;
+ phase: number;
+}
+
+export interface CityPlan {
+ /** The building's middle (the plaza's centre); the street grid runs on absolute multiples of `CITY.cell`. */
+ centre: { x: number; z: number };
+ towers: Tower[];
+ lanes: Lane[];
+ beams: Beam[];
+ beacons: Beacon[];
+ singularity: { x: number; y: number; z: number };
+}
+
+export function lcg(seed: number): () => number {
+ let state = seed >>> 0;
+ return () => {
+ state = (state * 1664525 + 1013904223) >>> 0;
+ return state / 0x1_0000_0000;
+ };
+}
+
+/** Distance from a point to a rectangle (0 inside it). */
+export function distanceToRect(x: number, z: number, r: Rect): number {
+ const dx = Math.max(r.minX - x, 0, x - r.maxX), dz = Math.max(r.minZ - z, 0, z - r.maxZ);
+ return Math.hypot(dx, dz);
+}
+
+/** The highest a roof may come at this distance from the slab's edge (metres, floor = 0); Infinity beyond `lowReach`. */
+export function roofLimit(edgeDistance: number): number {
+ if (edgeDistance >= CITY.lowReach) return Infinity;
+ const nearness = 1 - Math.max(0, edgeDistance - CITY.clear) / (CITY.lowReach - CITY.clear);
+ return CITY.nearRoof - nearness * CITY.nearDrop;
+}
+
+/**
+ * The city's anchor: the grid line nearest the building's middle. The city is laid out from it and every lot
+ * draws its own random numbers from its absolute grid cell, so a floor that grows or shrinks by a few metres
+ * keeps the same city round it (only the plaza and the roof limits follow the new edge).
+ */
+export function cityAnchor(bounds: Rect): { x: number; z: number; i: number; j: number } {
+ const i = Math.round((bounds.minX + bounds.maxX) / 2 / CITY.cell), j = Math.round((bounds.minZ + bounds.maxZ) / 2 / CITY.cell);
+ return { x: i * CITY.cell, z: j * CITY.cell, i, j };
+}
+
+/** A lot's own random numbers, from its absolute grid cell. */
+function lotRandom(i: number, j: number): () => number {
+ let h = Math.imul(i, 0x27d4eb2d) ^ Math.imul(j, 0x165667b1) ^ 0x5ec7a1;
+ h = Math.imul(h ^ (h >>> 15), 0x2c1b3c6d);
+ return lcg(h ^ (h >>> 13));
+}
+
+export function singularityPosition(bounds: Rect): { x: number; y: number; z: number } {
+ const { x: cx, z: cz } = cityAnchor(bounds);
+ const [bx, bz] = SINGULARITY.bearing, len = Math.hypot(bx, bz);
+ return { x: cx + (bx / len) * SINGULARITY.distance, y: SINGULARITY.y, z: cz + (bz / len) * SINGULARITY.distance };
+}
+
+/** The half width of the street on an (absolute) grid line: avenues on every `avenueEvery`-th line. */
+function streetHalf(line: number): number {
+ return ((line % CITY.avenueEvery) + CITY.avenueEvery) % CITY.avenueEvery === 0 ? CITY.avenue : CITY.street;
+}
+
+/** How many traffic lanes circle the building, and the room a lane keeps above the roofs beneath it. */
+const BUILDING_LANES = 7;
+const LANE_HEADROOM = 8;
+
+/** How far (metres, roughly) a point lies from a lane's ellipse. */
+function laneDistance(lane: Lane, x: number, z: number): number {
+ const dx = (x - lane.cx) / lane.rx, dz = (z - lane.cz) / lane.rz;
+ return Math.abs(Math.hypot(dx, dz) - 1) * Math.min(lane.rx, lane.rz);
+}
+
+/** The highest roof (metres, floor = 0) a tower of this reach may have here: under the roof limit and below every lane over it. */
+function roofCap(x: number, z: number, reach: number, bounds: Rect, lanes: readonly Lane[]): number {
+ let cap = roofLimit(distanceToRect(x, z, bounds));
+ for (const lane of lanes) {
+ if (laneDistance(lane, x, z) < reach + 3) cap = Math.min(cap, lane.y - lane.bob - LANE_HEADROOM);
+ }
+ return cap;
+}
+
+export function planCity(bounds: Rect): CityPlan {
+ const rand = lcg(0x5ec7a1);
+ const anchor = cityAnchor(bounds), cx = anchor.x, cz = anchor.z;
+ // The building's own middle: the plaza and the traffic circle it, the street grid hangs off the anchor.
+ const bx = (bounds.minX + bounds.maxX) / 2, bz = (bounds.minZ + bounds.maxZ) / 2;
+ const sing = singularityPosition(bounds);
+
+ // Flying traffic first, so the towers under it can stay below it: ellipses round the building, high over the
+ // rooftops where the camera sees them from every side, and fast rings round the singularity.
+ const lanes: Lane[] = [];
+ const half = Math.hypot(bounds.maxX - bounds.minX, bounds.maxZ - bounds.minZ) / 2;
+ for (let i = 0; i < BUILDING_LANES; i += 1) {
+ const r = half + CITY.clear + 18 + i * 34 + rand() * 12;
+ // An ellipse no narrower than r in either direction, so no lane cuts across the plaza.
+ const stretch = 1 + rand() * 0.3;
+ const [rx, rz] = i % 2 === 0 ? [r * stretch, r] : [r, r * stretch];
+ const y = -62 - rand() * 34;
+ const dir = i % 2 === 0 ? 1 : -1;
+ lanes.push({ cx: bx + (rand() - 0.5) * 12, cz: bz + (rand() - 0.5) * 12, rx, rz, y, omega: (dir * (16 + rand() * 10)) / r, cars: Math.round((2 * Math.PI * r) / 18), bob: 1 + rand() * 2.5 });
+ }
+ const buildingLanes = [...lanes];
+ for (let i = 0; i < 3; i += 1) {
+ const r = SINGULARITY.crater - 8 - i * 14;
+ lanes.push({ cx: sing.x, cz: sing.z, rx: r, rz: r, y: sing.y - 30 - i * 9, omega: ((i % 2 === 0 ? 1 : -1) * (30 + i * 6)) / r, cars: Math.round((2 * Math.PI * r) / 11), bob: 0.6 });
+ }
+
+ const towers: Tower[] = [];
+ const cell = CITY.cell, span = Math.ceil(CITY.radius / cell) + 1;
+ // Ordinary towers keep clear of the crater and of the ring of spires round it.
+ const districtClear = SINGULARITY.spireRing[1] + 16;
+ for (let i = -span; i < span; i += 1) {
+ for (let j = -span; j < span; j += 1) {
+ // The lot between grid lines i..i+1 and j..j+1, less the streets round it and a pavement.
+ const gi = anchor.i + i, gj = anchor.j + j;
+ const x0 = gi * cell + streetHalf(gi) + 1.5, x1 = (gi + 1) * cell - streetHalf(gi + 1) - 1.5;
+ const z0 = gj * cell + streetHalf(gj) + 1.5, z1 = (gj + 1) * cell - streetHalf(gj + 1) - 1.5;
+ const mx = (x0 + x1) / 2, mz = (z0 + z1) / 2;
+ const fromCentre = Math.hypot(mx - cx, mz - cz);
+ const lot = lotRandom(gi, gj);
+ const roll = lot(), sizeA = lot(), sizeB = lot(), heightRoll = lot(), kindRoll = lot(), lookRoll = lot(), seed = lot(), slideX = lot(), slideZ = lot(), turn = lot();
+ if (fromCentre > CITY.radius) continue;
+ const lotW = x1 - x0, lotD = z1 - z0;
+ // The tower must clear the plaza with all of its lot, not just its middle.
+ if (distanceToRect(mx, mz, bounds) - Math.hypot(lotW, lotD) / 2 < CITY.clear) continue;
+ if (Math.hypot(mx - sing.x, mz - sing.z) - Math.hypot(lotW, lotD) / 2 < districtClear) continue;
+ // Thinner towards the city's rim, where a gap reads as distance.
+ if (roll > 0.9 - (fromCentre / CITY.radius) * 0.25) continue;
+ const far = Math.min(1, fromCentre / CITY.radius);
+ let h = 70 + heightRoll * heightRoll * (130 + far * 170);
+ const kind: TowerKind = h > 220 && kindRoll < 0.45 ? "spire" : kindRoll < 0.42 ? "block" : kindRoll < 0.75 ? "setback" : "prism";
+ const w = Math.min(lotW, 13 + sizeA * 16), d = kind === "prism" || kind === "spire" ? w : Math.min(lotD, 13 + sizeB * 16);
+ const x = x0 + w / 2 + (lotW - w) * slideX, z = z0 + d / 2 + (lotD - d) * slideZ;
+ h = Math.min(h, roofCap(x, z, Math.hypot(w, d) / 2, bounds, buildingLanes) - GROUND_Y);
+ if (h < 30) continue;
+ towers.push({
+ kind, x, z, w, d, h,
+ rot: kind === "prism" || kind === "spire" ? turn * Math.PI : 0,
+ seed, lit: 0.1 + lookRoll * 0.16, seams: lookRoll > 0.62, crown: h > 170 && lookRoll > 0.35,
+ accent: lookRoll > 0.86 ? 2 : lookRoll > 0.72 ? 1 : 0,
+ });
+ }
+ }
+ // The core district: a ring of gold-crowned spires round the crater.
+ for (let i = 0; i < SINGULARITY.spires; i += 1) {
+ const angle = (i / SINGULARITY.spires) * Math.PI * 2 + rand() * 0.12;
+ const r = SINGULARITY.spireRing[0] + rand() * (SINGULARITY.spireRing[1] - SINGULARITY.spireRing[0]);
+ const x = sing.x + Math.cos(angle) * r, z = sing.z + Math.sin(angle) * r;
+ const w = 16 + rand() * 8;
+ const h = Math.min(230 + rand() * 120, roofCap(x, z, w / 2, bounds, buildingLanes) - GROUND_Y);
+ towers.push({ kind: "spire", x, z, w, d: w, h, rot: rand() * Math.PI, seed: rand(), lit: 0.3, seams: true, crown: true, accent: 2 });
+ }
+
+ // Light beams over the tallest far roofs (the singularity's jets are drawn with them).
+ const tallest = [...towers].sort((a, b) => b.h - a.h).filter((t) => distanceToRect(t.x, t.z, bounds) > CITY.lowReach * 0.6).slice(0, 9);
+ const beams: Beam[] = tallest.map((t) => ({ x: t.x, y: GROUND_Y + t.h, z: t.z, height: 340, radius: 1.1, accent: t.accent === 0 ? 1 : t.accent }));
+
+ // Aviation lights on every tall roof, a strobe on some.
+ const beacons: Beacon[] = [];
+ for (const t of towers) {
+ if (t.h < 150) continue;
+ beacons.push({ x: t.x, y: GROUND_Y + t.h + 1.5, z: t.z, kind: t.seed > 0.82 ? 1 : 0, phase: t.seed });
+ }
+ return { centre: { x: bx, z: bz }, towers, lanes, beams, beacons, singularity: sing };
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/cityShaders.ts b/jarvis/ui/web/frontend/src/components/society/office/cityShaders.ts
new file mode 100644
index 0000000000..83cd65b137
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/cityShaders.ts
@@ -0,0 +1,677 @@
+/**
+ * The city's materials: every surface out there is a small shader instead of
+ * a lit material, so the scene's sun never reaches the city and its light is
+ * its own (windows, streets, traffic, the singularity). All of them share one
+ * set of uniforms (time, the singularity's place, the palette), fade into the
+ * same sky with their distance from the camera, and go through the renderer's
+ * tone mapping like every other material, so the brightest cores roll off
+ * softly instead of clipping.
+ */
+import { AdditiveBlending, BackSide, Color, DoubleSide, ShaderMaterial, Vector3 } from "three";
+import { GROUND_Y } from "./cityPlan";
+
+/** The palette, in sRGB hex (Color converts to linear light for the shaders). */
+export const CITY_PALETTE = {
+ /** The sky straight up, at the horizon, and the deep haze below it that far streets sink into. */
+ zenith: "#03040b",
+ horizon: "#241a46",
+ below: "#0c0a1e",
+ horizonGlow: "#33225f",
+ /** The glow the singularity throws into the haze round it. */
+ singularityGlow: "#ffb45e",
+ /** Tower glass: the cladding and the sheen of the sky on it, cool away from the singularity and warm towards it. */
+ cladding: "#06080f",
+ sheenCool: "#2a3a6e",
+ sheenWarm: "#6e5442",
+ /** Lit windows. */
+ windowCool: "#cfe2ff",
+ windowWarm: "#ffbf7a",
+ windowCyan: "#7fe9ff",
+ /** Seams and crowns: cool white, cyan and gold. */
+ accents: ["#e8f4ff", "#3fe6ff", "#ffc35a"],
+ /** Low mist over the streets. */
+ mist: "#16123a",
+ /** Streets: the amber of the lamps, the cyan centre line of the avenues, headlights and tail lights. */
+ amber: "#ff9d47",
+ cyan: "#38d9ff",
+ head: "#f2f6ff",
+ tail: "#ff3b4e",
+} as const;
+
+export const colour = (hex: string): Color => new Color(hex);
+
+export interface CityUniforms {
+ uTime: { value: number };
+ uSing: { value: Vector3 };
+ uZenith: { value: Color };
+ uHorizon: { value: Color };
+ uBelow: { value: Color };
+ uHorizonGlow: { value: Color };
+ uSingGlow: { value: Color };
+ /** Drawing-buffer height in px over 2·tan(fov/2): turns metres at a distance into pixels. */
+ uPxScale: { value: number };
+ [key: string]: { value: unknown };
+}
+
+export function cityUniforms(singularity: { x: number; y: number; z: number }): CityUniforms {
+ return {
+ uTime: { value: 0 },
+ uSing: { value: new Vector3(singularity.x, singularity.y, singularity.z) },
+ uZenith: { value: colour(CITY_PALETTE.zenith) },
+ uHorizon: { value: colour(CITY_PALETTE.horizon) },
+ uBelow: { value: colour(CITY_PALETTE.below) },
+ uHorizonGlow: { value: colour(CITY_PALETTE.horizonGlow) },
+ uSingGlow: { value: colour(CITY_PALETTE.singularityGlow) },
+ uPxScale: { value: 800 },
+ };
+}
+
+/** Shared GLSL: hashing, the sky in a direction, and the fade of anything at a distance into that sky. */
+const COMMON = /* glsl */ `
+uniform float uTime;
+uniform vec3 uSing;
+uniform vec3 uZenith;
+uniform vec3 uHorizon;
+uniform vec3 uBelow;
+uniform vec3 uHorizonGlow;
+uniform vec3 uSingGlow;
+float hash12(vec2 p) {
+ vec3 p3 = fract(vec3(p.xyx) * 0.1031);
+ p3 += dot(p3, p3.yzx + 33.33);
+ return fract((p3.x + p3.y) * p3.z);
+}
+float noise2(vec2 p) {
+ vec2 i = floor(p), f = fract(p);
+ vec2 u = f * f * (3.0 - 2.0 * f);
+ return mix(mix(hash12(i), hash12(i + vec2(1.0, 0.0)), u.x), mix(hash12(i + vec2(0.0, 1.0)), hash12(i + vec2(1.0, 1.0)), u.x), u.y);
+}
+vec3 skyAt(vec3 dir) {
+ float h = dir.y;
+ vec3 col = h > 0.0 ? mix(uHorizon, uZenith, pow(min(h * 1.6, 1.0), 0.6)) : mix(uHorizon, uBelow, smoothstep(0.0, 0.32, -h));
+ col += uHorizonGlow * exp(-abs(h) * 11.0) * 0.55;
+ vec3 toSing = normalize(uSing - cameraPosition);
+ float s = max(dot(dir, toSing), 0.0);
+ col += uSingGlow * (pow(s, 6.0) * 0.025 + pow(s, 60.0) * 0.25);
+ return col;
+}
+/** Anything far from the camera sinks into the sky behind it: clear for 150 m, then an exponential haze. */
+vec3 aerial(vec3 col, vec3 world) {
+ vec3 ray = world - cameraPosition;
+ float f = 1.0 - exp(-max(length(ray) - 150.0, 0.0) / 560.0);
+ return mix(col, skyAt(normalize(ray)), f);
+}
+float aerialFade(vec3 world) {
+ return 1.0 - smoothstep(300.0, 950.0, length(world - cameraPosition));
+}
+`;
+
+const OUTPUT = /* glsl */ `
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+`;
+
+function material(uniforms: CityUniforms, own: Record<string, { value: unknown }>, vertexShader: string, fragmentShader: string, extra: Partial<ShaderMaterial> = {}): ShaderMaterial {
+ const m = new ShaderMaterial({ uniforms: { ...uniforms, ...own }, vertexShader, fragmentShader: COMMON + fragmentShader });
+ m.fog = false;
+ Object.assign(m, extra);
+ return m;
+}
+
+const INSTANCED_WORLD = /* glsl */ `
+ mat4 m = modelMatrix;
+ #ifdef USE_INSTANCING
+ m = m * instanceMatrix;
+ #endif
+`;
+
+/**
+ * Towers. Windows are drawn in world metres on every face (every tower shows windows of the same size, whatever
+ * its scale), lit by a hash per window and re-rolled now and then so the city lives. Up close a window is a pane
+ * in a frame; once a window is smaller than a pixel or two the face shows the lit share's average instead, so a
+ * far tower never shimmers. Glass picks up the sky's sheen at grazing angles, warmer on faces turned to the
+ * singularity. Some towers carry light seams on their corners with pulses running up them, some a lit crown;
+ * roofs get a lit parapet, a landing ring or rooftop plant. Mist lies over the street level.
+ */
+export function towerMaterial(uniforms: CityUniforms): ShaderMaterial {
+ return material(uniforms, {
+ uClad: { value: colour(CITY_PALETTE.cladding) },
+ uSheenCool: { value: colour(CITY_PALETTE.sheenCool) },
+ uSheenWarm: { value: colour(CITY_PALETTE.sheenWarm) },
+ uWinCool: { value: colour(CITY_PALETTE.windowCool) },
+ uWinWarm: { value: colour(CITY_PALETTE.windowWarm) },
+ uWinCyan: { value: colour(CITY_PALETTE.windowCyan) },
+ uAccents: { value: CITY_PALETTE.accents.map(colour) },
+ uMist: { value: colour(CITY_PALETTE.mist) },
+ uGround: { value: GROUND_Y },
+ }, /* glsl */ `
+ attribute vec4 aLook; // seed, lit share, seams (0/1), crown (0/1)
+ attribute vec4 aTier; // this tier's half width and depth and its top (unit tower), corners usable (0/1)
+ attribute float aAccent;
+ varying vec3 vWorld;
+ varying vec3 vNormalW;
+ varying vec3 vLocal;
+ flat varying vec3 vScale;
+ flat varying vec4 vLook;
+ flat varying vec4 vTier;
+ flat varying float vAccent;
+ void main() {
+ ${INSTANCED_WORLD}
+ vScale = vec3(length(m[0].xyz), length(m[1].xyz), length(m[2].xyz));
+ vec4 world = m * vec4(position, 1.0);
+ vWorld = world.xyz;
+ // Inverse-transpose for a rotation times a scale.
+ vNormalW = normalize(mat3(m) * (normal / (vScale * vScale)));
+ vLocal = position;
+ vLook = aLook;
+ vTier = aTier;
+ vAccent = aAccent;
+ gl_Position = projectionMatrix * viewMatrix * world;
+ }
+ `, /* glsl */ `
+ uniform vec3 uClad, uSheenCool, uSheenWarm, uWinCool, uWinWarm, uWinCyan, uMist;
+ uniform vec3 uAccents[3];
+ uniform float uGround;
+ varying vec3 vWorld;
+ varying vec3 vNormalW;
+ varying vec3 vLocal;
+ flat varying vec3 vScale;
+ flat varying vec4 vLook;
+ flat varying vec4 vTier;
+ flat varying float vAccent;
+ void main() {
+ vec3 n = normalize(vNormalW);
+ vec3 V = normalize(cameraPosition - vWorld);
+ float seed = vLook.x, lit = vLook.y;
+ vec3 accent = vAccent < 0.5 ? uAccents[0] : (vAccent < 1.5 ? uAccents[1] : uAccents[2]);
+ float heightM = vScale.y;
+ float above = vLocal.y * heightM;
+ // The window grid and its screen-space size are taken before the roof/face branch: derivatives inside
+ // non-uniform control flow are undefined, and would shimmer along every roof edge.
+ float u = dot(vWorld.xz, vec2(-n.z, n.x));
+ vec2 cellSize = vec2(1.4 + floor(fract(seed * 3.7) * 3.0) * 0.3, 3.6);
+ vec2 c = vec2(u, vWorld.y) / cellSize;
+ vec2 fw = max(fwidth(c), vec2(1e-4));
+ vec3 col;
+ if (n.y > 0.55) {
+ // A roof: dark membrane, a lit parapet on some, a landing ring on a few, plant boxes on the rest.
+ vec2 q = vLocal.xz / max(vTier.xy, vec2(1e-3));
+ vec2 half_ = vTier.xy * vScale.xz;
+ vec2 toEdge = (1.0 - abs(q)) * half_;
+ float edge = min(toEdge.x, toEdge.y);
+ col = uClad * 0.55;
+ float rim = (1.0 - smoothstep(0.35, 0.8, edge)) * step(0.45, fract(seed * 7.13));
+ col += accent * rim * 1.4;
+ float r = length(q);
+ float pad = (1.0 - smoothstep(0.0, 0.05, abs(r - 0.5))) * step(0.8, fract(seed * 29.7));
+ col += uWinWarm * pad * 1.2;
+ vec2 cellR = floor(vLocal.xz * vScale.xz / 2.4);
+ float plant = step(0.86, hash12(cellR + seed * 51.0)) * step(1.6, edge);
+ col += uWinCool * plant * 0.08;
+ } else {
+ // A face: glass, windows, seams, crown.
+ vec2 id = floor(c);
+ vec2 f = fract(c);
+ // Light comes in offices: a run of windows on one storey lit together, a few dark desks in it, strays elsewhere.
+ vec2 office = vec2(floor(id.x / 6.0), id.y);
+ float h = hash12(office + seed * 57.0);
+ float on = step(h, lit * 1.25) * step(hash12(id + seed * 173.0), 0.82);
+ on = max(on, step(hash12(id * 2.3 + seed * 5.0), lit * 0.12));
+ // Now and then an office switches.
+ float swap = hash12(office * 1.7 + floor(uTime * 0.1 + h * 9.0) + seed * 11.0);
+ on = swap > 0.994 ? 1.0 - on : on;
+ float pick = hash12(office + 7.1 + seed * 31.0);
+ vec3 wc = pick < 0.58 ? uWinCool : (pick < 0.93 ? uWinWarm : uWinCyan);
+ float bright = (0.4 + 0.6 * hash12(office + 3.3)) * (0.85 + 0.15 * hash12(id + 1.9)) * (0.75 + 0.25 * f.y);
+ // Storey-high glazing: slim mullions, a spandrel band between storeys.
+ vec2 lo = vec2(0.08, 0.12), hi = vec2(0.92, 0.94);
+ vec2 pane = smoothstep(lo, lo + fw, f) * (1.0 - smoothstep(hi - fw, hi, f));
+ float px = max(fw.x, fw.y);
+ float far = smoothstep(0.14, 0.42, px);
+ float win = mix(pane.x * pane.y * on * bright, lit * 0.55, far);
+ vec3 winCol = mix(wc, mix(uWinCool, uWinWarm, 0.32), far);
+ float fres = pow(1.0 - max(dot(n, V), 0.0), 3.0);
+ vec2 toSing = normalize(uSing.xz - vWorld.xz);
+ float facing = max(dot(normalize(n.xz + 1e-4), toSing), 0.0);
+ vec3 sheen = mix(uSheenCool, uSheenWarm, facing * facing * 0.45);
+ float rise = clamp(above / max(heightM, 1.0), 0.0, 1.0);
+ col = uClad * (0.5 + 0.4 * rise) + sheen * (0.025 + fres * 0.16);
+ // Dark panes mirror a little of the sky; a faint line between storeys catches the light.
+ col += sheen * 0.1 * pane.x * pane.y * (1.0 - on) * (1.0 - far);
+ col += sheen * 0.05 * (1.0 - smoothstep(0.0, 0.06 + fw.y, f.y)) * (1.0 - far);
+ col += winCol * win * 1.15;
+ // Corner seams, pulses running up them.
+ vec2 toSide = (vTier.xy - abs(vLocal.xz)) * vScale.xz;
+ float corner = max(toSide.x, toSide.y);
+ float seam = (1.0 - smoothstep(0.12, 0.4, corner)) * vLook.z * vTier.w;
+ float pulse = 0.45 + 0.55 * pow(0.5 + 0.5 * sin(vWorld.y * 0.06 - uTime * 1.8 + seed * 40.0), 3.0);
+ col += accent * seam * pulse * 1.3;
+ // A lit crown band under the top of the tier.
+ float top = vTier.z * heightM - above;
+ col += accent * vLook.w * (1.0 - smoothstep(0.6, 1.4, abs(top - 2.4))) * 1.6;
+ }
+ // Mist over the streets.
+ float low = exp(-max(vWorld.y - uGround, 0.0) / 48.0);
+ col = mix(col, uMist, low * 0.7);
+ col = aerial(col, vWorld);
+ gl_FragColor = vec4(col, 1.0);
+ ${OUTPUT}
+ }
+ `);
+}
+
+/**
+ * Street level: dark blocks with the dots of low roofs, amber streets, avenues with a cyan centre line and the
+ * light of traffic running along them in both directions, and the lit rings of the plaza round the building's
+ * foot. Lines thinner than a pixel turn into their average glow instead of shimmering.
+ */
+export function groundMaterial(uniforms: CityUniforms, centre: { x: number; z: number }, cell: number, avenueEvery: number, plazaRadius: number): ShaderMaterial {
+ return material(uniforms, {
+ uCentre: { value: [centre.x, centre.z] },
+ uCell: { value: cell },
+ uAvenue: { value: cell * avenueEvery },
+ uPlaza: { value: plazaRadius },
+ uAmber: { value: colour(CITY_PALETTE.amber) },
+ uCyan: { value: colour(CITY_PALETTE.cyan) },
+ uHead: { value: colour(CITY_PALETTE.head) },
+ uTail: { value: colour(CITY_PALETTE.tail) },
+ uMist: { value: colour(CITY_PALETTE.mist) },
+ }, /* glsl */ `
+ varying vec3 vWorld;
+ void main() {
+ vec4 world = modelMatrix * vec4(position, 1.0);
+ vWorld = world.xyz;
+ gl_Position = projectionMatrix * viewMatrix * world;
+ }
+ `, /* glsl */ `
+ uniform vec2 uCentre;
+ uniform float uCell, uAvenue, uPlaza;
+ uniform vec3 uAmber, uCyan, uHead, uTail, uMist;
+ varying vec3 vWorld;
+ float line(float d, float halfW, float fw) { return 1.0 - smoothstep(halfW, halfW + fw, d); }
+ void main() {
+ // The grid runs on absolute multiples of the cell, like the plan's lots; the plaza rings round the building.
+ vec2 p = vWorld.xz;
+ float fw = max(fwidth(p.x), fwidth(p.y));
+ vec2 ds = abs(fract(p / uCell + 0.5) - 0.5) * uCell;
+ vec2 da = abs(fract(p / uAvenue + 0.5) - 0.5) * uAvenue;
+ float streetX = line(ds.x, 2.6, fw), streetZ = line(ds.y, 2.6, fw);
+ float aveX = line(da.x, 4.6, fw), aveZ = line(da.y, 4.6, fw);
+ float street = max(streetX, streetZ), avenue = max(aveX, aveZ);
+ // Blocks: dark, with the scattered lights of low roofs.
+ vec2 lotCell = floor(p / 3.0);
+ float dots = step(0.96, hash12(lotCell)) * (0.35 + 0.65 * hash12(lotCell + 9.0));
+ vec3 col = uMist * 0.12 + uAmber * dots * 0.1 * (1.0 - street);
+ // Roads are dark asphalt with a row of lamps along each kerb; an avenue has a cyan centre line and traffic both ways.
+ col = mix(col, uAmber * 0.035, street);
+ float kerbs = max(line(abs(ds.x - 2.2), 0.35, fw) * streetX, line(abs(ds.y - 2.2), 0.35, fw) * streetZ);
+ float aveKerbs = max(line(abs(da.x - 4.2), 0.4, fw) * aveX, line(abs(da.y - 4.2), 0.4, fw) * aveZ);
+ col += uAmber * kerbs * 0.2 + uHead * aveKerbs * 0.3;
+ float centreLine = max(line(da.x, 0.3, fw) * aveX, line(da.y, 0.3, fw) * aveZ);
+ col += uCyan * centreLine * 0.55;
+ // Traffic: a car is a short bright dash on its side of the centre line.
+ vec2 lineId = floor(p / uAvenue + 0.5);
+ float sideX = sign(fract(p.x / uAvenue + 0.5) - 0.5), sideZ = sign(fract(p.y / uAvenue + 0.5) - 0.5);
+ float runZ = fract(p.y / 21.0 - uTime * 0.55 * sideX + hash12(vec2(lineId.x, 3.0)));
+ float runX = fract(p.x / 21.0 - uTime * 0.55 * sideZ + hash12(vec2(lineId.y, 7.0)));
+ float laneX = line(abs(da.x - 2.2), 0.7, fw) * aveX, laneZ = line(abs(da.y - 2.2), 0.7, fw) * aveZ;
+ float carsX = laneX * smoothstep(0.82, 0.97, runZ);
+ float carsZ = laneZ * smoothstep(0.82, 0.97, runX);
+ col += mix(uTail, uHead, step(0.0, sideX)) * carsX * 1.2;
+ col += mix(uTail, uHead, step(0.0, sideZ)) * carsZ * 1.2;
+ // From afar the lines are their average glow.
+ float far = smoothstep(1.2, 5.0, fw);
+ vec3 average = uMist * 0.14 + uAmber * 0.035 + uHead * 0.02 + uCyan * 0.015;
+ col = mix(col, average, far);
+ // The plaza round the building's foot: dark stone, lit rings.
+ float r = length(vWorld.xz - uCentre);
+ float plaza = 1.0 - smoothstep(uPlaza - 4.0, uPlaza, r);
+ float rings = line(abs(fract(r / 9.0) - 0.5) * 9.0, 0.25, fw) * plaza;
+ col = mix(col, uMist * 0.12, plaza);
+ col += uCyan * rings * 0.25 * (0.6 + 0.4 * sin(r * 0.2 - uTime * 0.8));
+ col = aerial(col, vWorld);
+ gl_FragColor = vec4(col, 1.0);
+ ${OUTPUT}
+ }
+ `);
+}
+
+/** Slow, drifting mist between the rooftops: a soft additive sheet, clear over the plaza and gone at the edge. */
+export function mistMaterial(uniforms: CityUniforms, centre: { x: number; z: number }, plazaRadius: number, strength: number, drift: number): ShaderMaterial {
+ return material(uniforms, {
+ uCentre: { value: [centre.x, centre.z] },
+ uPlaza: { value: plazaRadius },
+ uStrength: { value: strength },
+ uDrift: { value: drift },
+ uMist: { value: colour(CITY_PALETTE.mist) },
+ uCyan: { value: colour(CITY_PALETTE.cyan) },
+ }, /* glsl */ `
+ varying vec3 vWorld;
+ void main() {
+ vec4 world = modelMatrix * vec4(position, 1.0);
+ vWorld = world.xyz;
+ gl_Position = projectionMatrix * viewMatrix * world;
+ }
+ `, /* glsl */ `
+ uniform vec2 uCentre;
+ uniform float uPlaza, uStrength, uDrift;
+ uniform vec3 uMist, uCyan;
+ varying vec3 vWorld;
+ void main() {
+ vec2 p = (vWorld.xz - uCentre) * 0.0065 + vec2(uTime * 0.004 * uDrift, uTime * 0.0025);
+ float n = noise2(p) * 0.6 + noise2(p * 2.3 + 4.1) * 0.3 + noise2(p * 5.1 - 2.7) * 0.1;
+ n = smoothstep(0.35, 0.85, n);
+ float r = length(vWorld.xz - uCentre);
+ float clear = smoothstep(uPlaza, uPlaza + 60.0, r);
+ // Lit warm near the singularity, but never over its crater: mist there would veil the core.
+ float toSing = length(uSing.xz - vWorld.xz);
+ float lit = exp(-toSing / 260.0);
+ vec3 col = mix(uMist, uSingGlow * 0.45, lit) + uCyan * 0.05;
+ float a = n * clear * smoothstep(110.0, 220.0, toSing) * uStrength * aerialFade(vWorld);
+ gl_FragColor = vec4(col * a, 1.0);
+ ${OUTPUT}
+ }
+ `, { transparent: true, depthWrite: false, blending: AdditiveBlending, side: DoubleSide });
+}
+
+/**
+ * Flying traffic: every car is a camera-facing streak along its lane, computed on the GPU from its lane and the
+ * time, so thousands of cars cost one draw call and no work per frame. A far streak is kept at least about a
+ * pixel and a half wide and dimmed to match, so it neither vanishes nor flickers.
+ */
+export function trafficMaterial(uniforms: CityUniforms): ShaderMaterial {
+ return material(uniforms, {}, /* glsl */ `
+ uniform float uTime;
+ uniform float uPxScale;
+ attribute vec4 aOrbit; // centre x, centre z, radius x, radius z
+ attribute vec4 aMotion; // height, phase, angular speed (signed), bob
+ attribute vec4 aLook; // colour, streak length
+ varying vec2 vQuad;
+ varying vec3 vColour;
+ varying vec3 vWorld;
+ varying float vDim;
+ void main() {
+ float ang = aMotion.y + uTime * aMotion.z;
+ vec3 c = vec3(aOrbit.x + cos(ang) * aOrbit.z, aMotion.x + sin(ang * 2.0 + aMotion.y * 3.0) * aMotion.w, aOrbit.y + sin(ang) * aOrbit.w);
+ vec3 tangent = normalize(vec3(-sin(ang) * aOrbit.z, 0.0, cos(ang) * aOrbit.w)) * sign(aMotion.z);
+ vec3 toCam = cameraPosition - c;
+ float dist = length(toCam);
+ vec3 side = normalize(cross(tangent, toCam / dist));
+ float minWidth = dist * 1.4 / uPxScale;
+ float width = max(0.5, minWidth);
+ vDim = 0.5 / width;
+ vec3 p = c + tangent * position.x * aLook.w + side * position.y * width;
+ vQuad = position.xy * 2.0;
+ vColour = aLook.rgb;
+ vWorld = p;
+ gl_Position = projectionMatrix * viewMatrix * vec4(p, 1.0);
+ }
+ `, /* glsl */ `
+ varying vec2 vQuad;
+ varying vec3 vColour;
+ varying vec3 vWorld;
+ varying float vDim;
+ void main() {
+ float along = smoothstep(-1.0, 0.75, vQuad.x) * (1.0 - smoothstep(0.75, 1.0, vQuad.x));
+ float across = 1.0 - vQuad.y * vQuad.y;
+ float head = exp(-pow((vQuad.x - 0.82) * 6.0, 2.0)) * across;
+ vec3 col = vColour * (along * pow(across, 2.0) * 0.9 + head * 2.2) * vDim;
+ col *= aerialFade(vWorld);
+ gl_FragColor = vec4(col, 1.0);
+ ${OUTPUT}
+ }
+ `, { transparent: true, depthWrite: false, blending: AdditiveBlending, side: DoubleSide });
+}
+
+/** Aviation lights: points on the tall roofs, red ones breathing slowly, a few white strobes. */
+export function beaconMaterial(uniforms: CityUniforms): ShaderMaterial {
+ return material(uniforms, {
+ uRed: { value: colour(CITY_PALETTE.tail) },
+ uWhite: { value: colour(CITY_PALETTE.head) },
+ }, /* glsl */ `
+ uniform float uTime;
+ uniform float uPxScale;
+ attribute vec2 aBeacon; // kind, phase
+ varying float vKind;
+ varying float vOn;
+ varying vec3 vWorld;
+ void main() {
+ vec4 world = modelMatrix * vec4(position, 1.0);
+ vWorld = world.xyz;
+ vec4 mv = viewMatrix * world;
+ vKind = aBeacon.x;
+ float t = uTime + aBeacon.y * 10.0;
+ vOn = aBeacon.x < 0.5 ? 0.25 + 0.75 * pow(0.5 + 0.5 * sin(t * 1.6), 4.0) : step(0.93, fract(t * 0.7));
+ gl_PointSize = clamp(3.2 * uPxScale / -mv.z, 2.0, 18.0);
+ gl_Position = projectionMatrix * mv;
+ }
+ `, /* glsl */ `
+ uniform vec3 uRed, uWhite;
+ varying float vKind;
+ varying float vOn;
+ varying vec3 vWorld;
+ void main() {
+ vec2 q = gl_PointCoord * 2.0 - 1.0;
+ float r = dot(q, q);
+ float glow = exp(-r * 5.0) + exp(-r * 40.0) * 2.0;
+ vec3 col = (vKind < 0.5 ? uRed : uWhite) * glow * vOn * aerialFade(vWorld);
+ gl_FragColor = vec4(col, 1.0);
+ ${OUTPUT}
+ }
+ `, { transparent: true, depthWrite: false, blending: AdditiveBlending });
+}
+
+/** A light beam: an open cylinder, brightest on its axis and at its foot, with pulses climbing it. */
+export function beamMaterial(uniforms: CityUniforms): ShaderMaterial {
+ return material(uniforms, {}, /* glsl */ `
+ varying vec3 vWorld;
+ varying vec3 vNormalW;
+ varying float vRise;
+ varying vec3 vColour;
+ void main() {
+ ${INSTANCED_WORLD}
+ vec4 world = m * vec4(position, 1.0);
+ vWorld = world.xyz;
+ vNormalW = normalize(mat3(m) * vec3(normal.x, 0.0, normal.z));
+ vRise = position.y;
+ #ifdef USE_INSTANCING_COLOR
+ vColour = instanceColor;
+ #else
+ vColour = vec3(1.0);
+ #endif
+ gl_Position = projectionMatrix * viewMatrix * world;
+ }
+ `, /* glsl */ `
+ varying vec3 vWorld;
+ varying vec3 vNormalW;
+ varying float vRise;
+ varying vec3 vColour;
+ void main() {
+ vec3 V = normalize(cameraPosition - vWorld);
+ float axis = pow(abs(dot(normalize(vNormalW), V)), 2.5);
+ float fade = pow(1.0 - clamp(vRise, 0.0, 1.0), 1.6);
+ float pulse = 0.7 + 0.3 * sin(vRise * 60.0 - uTime * 2.4);
+ vec3 col = vColour * axis * fade * pulse * 1.4 * aerialFade(vWorld);
+ gl_FragColor = vec4(col, 1.0);
+ ${OUTPUT}
+ }
+ `, { transparent: true, depthWrite: false, blending: AdditiveBlending, side: DoubleSide });
+}
+
+/** The sky: a sphere round the camera, drawn first and behind everything; below the horizon the deep haze. */
+export function skyMaterial(uniforms: CityUniforms): ShaderMaterial {
+ return material(uniforms, {}, /* glsl */ `
+ varying vec3 vWorld;
+ void main() {
+ vec4 world = modelMatrix * vec4(position, 1.0);
+ vWorld = world.xyz;
+ gl_Position = projectionMatrix * viewMatrix * world;
+ }
+ `, /* glsl */ `
+ varying vec3 vWorld;
+ void main() {
+ vec3 dir = normalize(vWorld - cameraPosition);
+ vec3 col = skyAt(dir);
+ // Faint stars above the horizon only.
+ vec2 cellS = floor(vec2(atan(dir.z, dir.x) * 220.0, dir.y * 220.0));
+ float star = step(0.9965, hash12(cellS)) * smoothstep(0.02, 0.2, dir.y);
+ col += vec3(star) * 0.5;
+ gl_FragColor = vec4(col, 1.0);
+ ${OUTPUT}
+ }
+ `, { side: BackSide, depthWrite: false, depthTest: false });
+}
+
+// ---------------------------------------------------------------------------
+// The singularity
+// ---------------------------------------------------------------------------
+
+/** The core: black, with a thin photon ring where the eye grazes it. */
+export function coreMaterial(uniforms: CityUniforms): ShaderMaterial {
+ return material(uniforms, { uRim: { value: colour("#ffe2b0") } }, /* glsl */ `
+ varying vec3 vWorld;
+ varying vec3 vNormalW;
+ void main() {
+ vec4 world = modelMatrix * vec4(position, 1.0);
+ vWorld = world.xyz;
+ vNormalW = normalize(mat3(modelMatrix) * normal);
+ gl_Position = projectionMatrix * viewMatrix * world;
+ }
+ `, /* glsl */ `
+ uniform vec3 uRim;
+ varying vec3 vWorld;
+ varying vec3 vNormalW;
+ void main() {
+ vec3 V = normalize(cameraPosition - vWorld);
+ float graze = 1.0 - max(dot(normalize(vNormalW), V), 0.0);
+ vec3 col = uRim * pow(graze, 6.0) * 2.5;
+ gl_FragColor = vec4(col, 1.0);
+ ${OUTPUT}
+ }
+ `);
+}
+
+/**
+ * The accretion disc: white-hot at its inner edge through gold to violet at its rim, spiral arms turning
+ * inwards, finer streams racing round, and the side coming towards the viewer brighter than the side going away.
+ */
+export function discMaterial(uniforms: CityUniforms, inner: number, outer: number): ShaderMaterial {
+ return material(uniforms, {
+ uInner: { value: inner },
+ uOuter: { value: outer },
+ uHot: { value: colour("#fff4e2") },
+ uWarm: { value: colour("#ffaa52") },
+ uCool: { value: colour("#6a4cff") },
+ uRimC: { value: colour("#2ad4ff") },
+ }, /* glsl */ `
+ varying vec3 vLocal;
+ varying vec3 vWorld;
+ void main() {
+ vLocal = position;
+ vec4 world = modelMatrix * vec4(position, 1.0);
+ vWorld = world.xyz;
+ gl_Position = projectionMatrix * viewMatrix * world;
+ }
+ `, /* glsl */ `
+ uniform float uInner, uOuter;
+ uniform vec3 uHot, uWarm, uCool, uRimC;
+ varying vec3 vLocal;
+ varying vec3 vWorld;
+ void main() {
+ float r = length(vLocal.xy);
+ float t = clamp((r - uInner) / (uOuter - uInner), 0.0, 1.0);
+ float ang = atan(vLocal.y, vLocal.x);
+ float spin = uTime * (0.9 / (0.25 + t));
+ float arms = 0.5 + 0.5 * sin(ang * 3.0 + log(r) * 9.0 - spin);
+ float streams = 0.5 + 0.5 * sin(ang * 23.0 + r * 0.35 - spin * 2.3);
+ float grain = noise2(vec2(ang * 12.0 - spin, r * 0.18));
+ vec3 col = mix(uHot * 1.7, uWarm * 0.95, smoothstep(0.0, 0.3, t));
+ col = mix(col, uCool * 0.75, smoothstep(0.3, 0.85, t));
+ col += uRimC * 0.25 * smoothstep(0.7, 0.95, t);
+ float body = smoothstep(0.0, 0.025, t) * (1.0 - smoothstep(0.55, 1.0, t));
+ float a = body * (0.3 + 0.45 * arms + 0.25 * streams) * (0.6 + 0.6 * grain);
+ // Doppler beaming: the approaching side shines brighter.
+ vec3 toCam = normalize(cameraPosition - uSing);
+ vec3 tangent = normalize(vec3(-sin(ang), 0.0, cos(ang)));
+ a *= 0.7 + 0.45 * dot(tangent, toCam);
+ gl_FragColor = vec4(col * a, 1.0);
+ ${OUTPUT}
+ }
+ `, { transparent: true, depthWrite: false, blending: AdditiveBlending, side: DoubleSide });
+}
+
+/**
+ * The lens: a camera-facing sheet round the core with the bright Einstein ring hugging its edge, a fainter
+ * second ring and the wide glow the singularity throws into the night.
+ */
+export function lensMaterial(uniforms: CityUniforms, core: number, size: number): ShaderMaterial {
+ return material(uniforms, {
+ uSize: { value: size },
+ /** The core's radius as a share of the sheet's half width. */
+ uCore: { value: core / (size / 2) },
+ uRing: { value: colour("#ffe7c0") },
+ uViolet: { value: colour("#6d3bff") },
+ }, /* glsl */ `
+ uniform float uSize;
+ varying vec2 vQ;
+ varying vec3 vWorld;
+ void main() {
+ // -1..1 across the sheet.
+ vQ = position.xy / (uSize * 0.5);
+ vec4 world = modelMatrix * vec4(position, 1.0);
+ vWorld = world.xyz;
+ gl_Position = projectionMatrix * viewMatrix * world;
+ }
+ `, /* glsl */ `
+ uniform float uCore;
+ uniform vec3 uRing, uViolet;
+ varying vec2 vQ;
+ varying vec3 vWorld;
+ void main() {
+ float r = length(vQ) / uCore;
+ float ring = exp(-pow((r - 1.06) / 0.035, 2.0)) * 3.0 + exp(-pow((r - 1.22) / 0.12, 2.0)) * 0.55;
+ float shimmer = 0.85 + 0.15 * sin(atan(vQ.y, vQ.x) * 7.0 + uTime * 1.3);
+ float halo = exp(-(r - 1.0) * 0.7) * 0.22;
+ float edge = 1.0 - smoothstep(0.7, 1.0, length(vQ));
+ vec3 col = (uRing * ring * shimmer + mix(uSingGlow, uViolet, smoothstep(1.0, 6.0, r)) * halo) * edge * step(1.0, r);
+ gl_FragColor = vec4(col, 1.0);
+ ${OUTPUT}
+ }
+ `, { transparent: true, depthWrite: false, blending: AdditiveBlending });
+}
+
+/** The orbital rings round the singularity: thin gold filaments, pulses running round them. */
+export function orbitalRingMaterial(uniforms: CityUniforms, direction: number): ShaderMaterial {
+ return material(uniforms, {
+ uGold: { value: colour("#ffc35a") },
+ uDir: { value: direction },
+ uMetal: { value: colour("#151829") },
+ }, /* glsl */ `
+ varying vec2 vUv;
+ varying vec3 vWorld;
+ varying vec3 vNormalW;
+ void main() {
+ vUv = uv;
+ vec4 world = modelMatrix * vec4(position, 1.0);
+ vWorld = world.xyz;
+ vNormalW = normalize(mat3(modelMatrix) * normal);
+ gl_Position = projectionMatrix * viewMatrix * world;
+ }
+ `, /* glsl */ `
+ uniform vec3 uGold, uMetal;
+ uniform float uDir;
+ varying vec2 vUv;
+ varying vec3 vWorld;
+ varying vec3 vNormalW;
+ void main() {
+ vec3 V = normalize(cameraPosition - vWorld);
+ float fres = pow(1.0 - abs(dot(normalize(vNormalW), V)), 2.0);
+ float core = pow(1.0 - fres, 2.0);
+ float run = pow(0.5 + 0.5 * sin(vUv.x * 6.2832 * 4.0 - uTime * 0.5 * uDir), 6.0);
+ float ticks = smoothstep(0.9, 0.97, fract(vUv.x * 96.0)) * 0.6;
+ vec3 col = uGold * core * (0.35 + ticks + 1.8 * run) + uMetal * 0.2;
+ col *= aerialFade(vWorld);
+ gl_FragColor = vec4(col, 1.0);
+ ${OUTPUT}
+ }
+ `, { transparent: true, depthWrite: false, blending: AdditiveBlending });
+}